text:
Q: Get window handle from EnvDTE80.Process2 object I have a piece of Vb.net code that finds the nunit.exe process like this:
Dim proc2 As EnvDTE80.Process2 = dbg2.GetProcesses(trans, "myPC").Item("nunit.exe")

Now I'd like to press a button on the window of that process so I do this:
Dim ButtonHandle As IntPtr = FindWindowEx(X, 0, "Button", "Run")

SendMessage(ButtonHandle, &HF5, 0, 0)

But then I need the IntPtr window handle for proc2 on the spot marked "X".
How do I get it?

A: got it:
System.Diagnostics.Process.GetProcessById(proc2.ProcessID).MainWindowHandle


text:
Q: Receiving in app SMS messages only from certain specified numbers I've recently set up an app that will receive sms messages and then display them as a toast on the main activity. Once the app has received an SMS it will abort broadcast and stop the message from going into the inbox.
Currently it does this with all messages that the phone receives but I would like it to only carry out its job and display the toast when an SMS is received by a specific number. I know that it is a case of putting an if statement into my receiver code but I'm not too sure where abouts the it should be placed.
SmsReceiver.java:
public class SmsReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    Bundle extras = intent.getExtras();

    if (extras ==null)
        return;
    //toast
    Toast.makeText(context, "Received", Toast.LENGTH_LONG).show();

    Object[] pdus = (Object[]) extras.get("pdus");

    for (int i = 0; i < pdus.length; i++) {
        SmsMessage SMessage = SmsMessage.createFromPdu((byte[]) pdus[i]);
        String sender = SMessage.getOriginatingAddress();
        String body = SMessage.getMessageBody().toString();

        Intent in = new Intent("SmsMessage.intent.MAIN").putExtra("get_msg", sender+":"+body);

        context.sendBroadcast(in);
        this.abortBroadcast();

    }
}
}

A: Just put bellow
    String body=....
    if(sender.equals(phoneNumber)) {

                abortBroadcast() then do something...
    }

Be sure to do abortBroadcast as soon as possible, since if you do to many operations before it, the original inbox will pick up the message.

A: if("123456789".equals(sender))
{
 //do something
}

A: You should do:
String body=....
if(PhoneNumberUtils.compare(sender, phoneNumber)) {

            abortBroadcast() then do something...
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Bootstrap a debian build environment and build source packages with no root privileges On debian squeeze, I am trying to do the following :

*

*fetch sources package from the wheezy source repository

*bootstrap a squeeze chroot for several architectures

*build the packages for several architectures (i386, amd64, all  and any)

I want both the fetching, bootstrapping and build operation to be scriptable, repeatable, and run as a normal user. For the environment setup, I want to make as little use of the root account as possible (install the necessary dependencies, and maybe some visudo stuff). If possible I would like to avoid using a VM (pbuilder with user mode linux)
So far I have tried several things with pbuilder (require root), debootstrap (require root) with little success.

A: So, the working solution uses pbuilder and sudo.

*

*After installing both, one has to edit the /etc/sudoers file (using visudo) and allow users in the group pbuilder to run pbuilder without a password.
%pbuilder ALL=(ALL) NOPASSWD: /usr/sbin/pbuilder

*Add the pbuilder group and your build user name builduser to it
root@debian# groupadd pbuilder
root@debian# gpasswd -a builduser pbuilder

You will now be able to bootstrap a Debian chroot and build packages using pbuilder as non-root.
Here is an example script that

*

*fetches the source package given as the first parameter (as builduser, using the answer to that question)

*build packages from sources, for both i386 and amd64 architectures

*upload them with dput to an external repositories given by the second parameter of the script
#/bin/bash

set -e
set -x

THIS=`readlink -f ${0}`
THIS_DIR=`dirname ${THIS}`

PACKAGE=${1}
TARGET_CODENAME=${2}

ARCHS='i386 amd64'
APT_CONF=${THIS_DIR}/tmp/etc/apt.conf

pushd ${THIS_DIR}/src
apt-get update -c ${APT_CONF}
apt-get source ${PACKAGE} -c ${APT_CONF}
popd

for ARCH in ${ARCHS}
do
  BUILD_DIR=${THIS_DIR}/build/${ARCH}
  sudo pbuilder --create --configfile ${BUILD_DIR}/pbuilderrc \
                --buildresult ${BUILD_DIR}/
  sudo pbuilder --build --configfile ${BUILD_DIR}/pbuilderrc \
                --buildresult ${BUILD_DIR}/ ${THIS_DIR}/src/${PACKAGE}*.dsc
  dput ${TARGET_CODENAME} ${BUILD_DIR}/*.changes
done

A: Try to use 'fakeroot' program. Usage of this program - just use instead sudo.
Fakeroot exists in the debian repo, try to sudo apt-get install fakeroot


text:
Q: applescript photoshop apply layer style inner shadow I know this works with strokes but trying to do it with a inner shadow.
After these settings

I think the code is something like this
tell application id "com.adobe.Photoshop"
    activate
    tell current document
        apply layer style current layer using "73 Px Inner Shadow 15% Fill Opacity"
    end tell
end tell

A: I really think this is best done using JavaScript (which you can call from AS, of course, by text or file) using the fairly obtuse but powerful ActionDescriptor method. The best (arguably only) way to do this is by downloading the Scripting Listener plugin (see: http://forums.adobe.com/message/5428603) and using it to parse and steal bits of code and putting these parts in your own JavaScript code. This code can then be used on its own (.jsx files called from within PS) or by calling the JS code from AppleScript.
For example, Below is a script (which can be run as-is in PS CC) taken directly from the Scripting Listener log to make an inner shadow on the currently selected layer, with these settings: Blend mode "Darken", rgb color {111, 22, 3}, Opacity 44%, Angle 55 degrees, Distance: 66 pixels, Choke: 7%, Size: 88px (more info below script code):
// =======================================================
var idsetd = charIDToTypeID( "setd" );
var desc8 = new ActionDescriptor();
var idnull = charIDToTypeID( "null" );
var ref4 = new ActionReference();
var idPrpr = charIDToTypeID( "Prpr" );
var idLefx = charIDToTypeID( "Lefx" );
ref4.putProperty( idPrpr, idLefx );
var idLyr = charIDToTypeID( "Lyr " );
var idOrdn = charIDToTypeID( "Ordn" );
var idTrgt = charIDToTypeID( "Trgt" );
ref4.putEnumerated( idLyr, idOrdn, idTrgt );
desc8.putReference( idnull, ref4 );
var idT = charIDToTypeID( "T   " );
var desc9 = new ActionDescriptor();
var idgagl = charIDToTypeID( "gagl" );
var idAng = charIDToTypeID( "#Ang" );
desc9.putUnitDouble( idgagl, idAng, 55.000000 );
var idScl = charIDToTypeID( "Scl " );
var idPrc = charIDToTypeID( "#Prc" );
desc9.putUnitDouble( idScl, idPrc, 100.000000 );
var idIrSh = charIDToTypeID( "IrSh" );
var desc10 = new ActionDescriptor();
var idenab = charIDToTypeID( "enab" );
desc10.putBoolean( idenab, true );
var idMd = charIDToTypeID( "Md  " );
var idBlnM = charIDToTypeID( "BlnM" );
var idDrkn = charIDToTypeID( "Drkn" );
desc10.putEnumerated( idMd, idBlnM, idDrkn );
var idClr = charIDToTypeID( "Clr " );
var desc11 = new ActionDescriptor();
var idRd = charIDToTypeID( "Rd  " );
desc11.putDouble( idRd, 111.002197 );
var idGrn = charIDToTypeID( "Grn " );
desc11.putDouble( idGrn, 21.999664 );
var idBl = charIDToTypeID( "Bl  " );
desc11.putDouble( idBl, 3.003845 );
var idRGBC = charIDToTypeID( "RGBC" );
desc10.putObject( idClr, idRGBC, desc11 );
var idOpct = charIDToTypeID( "Opct" );
var idPrc = charIDToTypeID( "#Prc" );
desc10.putUnitDouble( idOpct, idPrc, 44.000000 );
var iduglg = charIDToTypeID( "uglg" );
desc10.putBoolean( iduglg, true );
var idlagl = charIDToTypeID( "lagl" );
var idAng = charIDToTypeID( "#Ang" );
desc10.putUnitDouble( idlagl, idAng, 120.000000 );
var idDstn = charIDToTypeID( "Dstn" );
var idPxl = charIDToTypeID( "#Pxl" );
desc10.putUnitDouble( idDstn, idPxl, 66.000000 );
var idCkmt = charIDToTypeID( "Ckmt" );
var idPxl = charIDToTypeID( "#Pxl" );
desc10.putUnitDouble( idCkmt, idPxl, 7.000000 );
var idblur = charIDToTypeID( "blur" );
var idPxl = charIDToTypeID( "#Pxl" );
desc10.putUnitDouble( idblur, idPxl, 88.000000 );
var idNose = charIDToTypeID( "Nose" );
var idPrc = charIDToTypeID( "#Prc" );
desc10.putUnitDouble( idNose, idPrc, 0.000000 );
var idAntA = charIDToTypeID( "AntA" );
desc10.putBoolean( idAntA, false );
var idTrnS = charIDToTypeID( "TrnS" );
var desc12 = new ActionDescriptor();
var idNm = charIDToTypeID( "Nm  " );
desc12.putString( idNm, "Linear" );
var idShpC = charIDToTypeID( "ShpC" );
desc10.putObject( idTrnS, idShpC, desc12 );
var idIrSh = charIDToTypeID( "IrSh" );
desc9.putObject( idIrSh, idIrSh, desc10 );
var idLefx = charIDToTypeID( "Lefx" );
desc8.putObject( idT, idLefx, desc9 );
executeAction( idsetd, desc8, DialogModes.NO );

////////////////end script///

This helps to clarify what some of those cryptic codes represent: http://www.pcpix.com/photoshop/char.htm
[edit May, 2017] The link above is now dead. The info now lives on https://pastebin.com/h9bK3m8D and the original is archived via the "wayback machine": https://web-beta.archive.org/web/20140709161028/http://www.pcpix.com/photoshop/char.htm
If you go this route (and really, I think it is currently the only way to get such a level of control over certain actions), you should be aware that the log needs to live on the desktop, and fills up indiscriminately, so I end up emptying it fairly regularly (and/or turning it off). I realize you may be more comfortable in AS than in JS, but if you learn how to write JS scripts (or even write them on the fly using AS), you become nearly all-powerful (and with great power comes great responsibility). Sometimes you can take out parts of the log-written code and make the code more "efficient", but (obviously, perhaps) mistakes can leave you with broken code and generic errors.
[edit] It is probably best to use, instead of the charIDToTypeID() method, for transfer mode, the stringIDToTypeID() method. Without getting into why, I'll just say that it is easier. Just use "camelCase" versions of the transfer modes, a la:
var idDrkn = stringIDToTypeID( "darken" );

or
//changed variable name to better reflect a generic
var transferModeID = stringIDToTypeID( "colorDodge" );
desc10.putEnumerated( idMd, idBlnM, transferModeID );


text:
Q: How to migrate parameter store data to other Region / AWS Account Consider that I have got a AWS account that already has some parameter store data.
Is there a way to migrate these data from this parameter store to another:

*

*parameter store?

*region?

*AWS account?

I would prefer official tools to do this, but tools similar to dynamoDB dump are also welcome.

A: There is no "official tool" to do this. It could be done by iterating through the existing parameters and creating them in the target.
I found this tool that somebody has written: aws-ssm-copy · PyPI: Copy parameters from a AWS parameter store to another
It looks like it can copy between Regions and between AWS Accounts (by providing multiple Profiles).

A: This article might help
For another account, you need to export parameters from account by using command
aws ssm get-parameters-by-path --path "/" --recursive
and you will get all the parameters as response.
Now you have to login to another account using command aws configure. just replace following values
$ aws configure
AWS Access Key ID [None]: AKIAIOSFODNN7EXAMPLE
AWS Secret Access Key [None]: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
Default region name [None]: us-west-2
Default output format [None]: json

reference here
and then follow the article I shared above.


text:
Q: Accessing a local website on an iPad On my computer I have been learning HTML, CSS and JavaScript and have  made a web app for the iPad, however I have no way of visiting the site on Safari. I have an external Network drive however when I try that address, Safari alerts "Cannot open the page because it is a local file". I know I could get web hosting but this is not ideal.
Is it possible to do this?

A: Normally HTML, CSS and Javascript shouldnt need a websserver.
How are you accessing the file?
Try installing apache on your computer, place the files in webroot and visit the computers IP from the Ipad ( something like 192.168.1.x).
I think that would work for you.

A: You can also use Dropbox for hosting online...
It has a public folder where you can host your files and the whole public>website folder, with index.html page acts as a website. And it's free! 5GB of cloud storage free on dropbox.
5GB free on Google drive too, and that too can be used as a webserver by setting the folder properties to public.


text:
Q: Auto-formatting embed JavaScript in php files in Eclipse Why auto-formatting (by Ctrl-Shift-F) of embed JavaScript inside php file is not working in my Eclipse? I mean formatting of the block like this:
//php code here
?>
<script type="text/javascript">function test(){
console log( a);
        console.log('b');}
</script>
}
<?php
//php code here

I have Eclipse for PHP 2021-06 and WildWebDeveloper installed. If I put the same javascript code inside .js file JavaScript autoformatting works as expected.


text:
Q: Is there a query that can fetch data from another blade and then print or save it as a pdf? I have a web application project where I need to print selected or all the information about that specific person I tried using datatables, it works but it only prints what's inside the table. I need the information about that person which is in another blade.php I was wondering if I there is a code that I could use to link blades using query I'm just new to using laravel
I'm using Laravel framework latest version.

  All

    @if($joinCount == 0)

There's no payslip

    @else

            ID Number
            Name
            Department
            Cut-off

        @foreach($joinn as $join)

            {{$join->idnumber}}
            {{$join->first_name}} {{$join->middle_name}}
                             {{$join->surname}}
            {{$join->department}}
                    {{$join->cut_off}}

                @endforeach


text:
Q: R - Programming: How to loop through a list of dataframes and manipulate specific columns within each? So I have three data frames, each with 14 columns.
iowa <- data.frame() #Has 14 columns; let's say 600 records
maine <- data.frame() #Has same 14 columns; let's say 700 records
texas <- data.frame() #Has same 14 columns; let's say 900 records

I place those data frames within a list,
state_List <- list(iowa, maine, texas)

I then want to change two columns (called "State_Date" and "US_Date") within each data frame within the state_List to date formats, and I would like to change all columns except to one as factors.  I have written the following:
state_List <- lapply(state_List,
                     function(x){
                                 x$State_Date <- as.Date(x$State_Date, format = "%m/%d/%Y")
                                 x$US_Date <- as.Date(x$US_Date, format = "%m/%d/%Y")
                                 x[, c(1:7, 9:14)] <- as.factor(x[, c(1:7, 9:14)]
                                 }
                     )

The error I receive is
Error in sort.list(y) : 'x' must be atomic for 'sort.list'
Have you called 'sort' on a list?

This error is due to the as.factor part.
However, if I get rid of the last evaluation of the function called in lapply, and just keep the two that change the class of the date fields, what I get is:

*

*A list where the 3 names of the data frames it contained are lost

*Each data frame in the list, or should I say each slot for a data frame in the list is now filled with the US_Date column for that state.

What I'd like is:

*

*A list with 3 data frames (that retains the name of the data frames)

*Within each data frame, the two fields, State_Date and US_Date have dates that have been formatted as such

*All columns except for column 8 to be formatted as factors

Thank you for your help!
** CORRECT CODE BELOW SHOWS WHAT I SHOULD HAVE DONE BASED ON THE RESPONSE:
state_List <- list(iowa = iowa, maine = maine, texas = texas)
state_List <- lapply(state_List,
                     function(X){
                                 x$State_Date <- as.Date(x$State_Date, format = "%m/%d/%Y")
                                 x$US_Date <- as.Date(x$US_Date, format = "%m/%d/%Y")
                                 x[, c(1:7, 9:14)] <- lapply( x[, c(1:7, 9:14)] , factor)
                                 return(x)
                                 }
                    )

A: The third line inside that functions should be:
x[, c(1:7, 9:14)] <- lapply( x[, c(1:7, 9:14)] , factor)

And you should return(x) at the end.


text:
Q: Cannot run a Windows command via Ant, but can on cmd.exe I have an ant macro I want to run;
<macrodef name="serviceTask">
    <attribute name="server"/>
    <attribute name="operation"/>
    <attribute name="service"/>
    <sequential>
        <echo message="sc \\@{server} @{operation} @{service}"/>
        <exec executable="sc.exe" failonerror="true">
            <arg line="\\@{server} @{operation} @{service}"/>
        </exec>
    </sequential>
</macrodef>

<target name="startTomcat">
    <echo message="Start Tomcat ${service} on ${server}"/>
    <serviceTask server="MyServer" operation="start" service="Tomcat8180"/>
</target>

But I get an RPC error:
startTomcat:
     [echo] Start Tomcat Tomcat8180 on pacdcdtadeva02
     [echo] sc \\pacdcdtadeva02 start Tomcat8180
     [exec] [SC] OpenSCManager FAILED 1722:
     [exec]
     [exec] The RPC server is unavailable.
     [exec]

stopTomcat:
     [echo] Stop Tomcat Service Tomcat8180 on pacdcdtadeva02
     [echo] sc \\pacdcdtadeva02 stop Tomcat8180
     [exec] [SC] OpenSCManager FAILED 1722:
     [exec]
     [exec] The RPC server is unavailable.
     [exec]
     [echo] -------------------------------------------------------------------
     [echo] --- Completed on 02/01/2011 05:11:42 PM
     [echo] -------------------------------------------------------------------

Now when I run this from the command line like
sc \\stage01 start Tomcat8180

the service starts/stops
C:\usr\svn_workspaces\xIVR\agent-ivr>sc \\stage01 start Tomcat8180

SERVICE_NAME: Tomcat8180
        TYPE               : 10  WIN32_OWN_PROCESS
        STATE              : 2  START_PENDING
                                (NOT_STOPPABLE,NOT_PAUSABLE,IGNORES_SHUTDOWN)
        WIN32_EXIT_CODE    : 0  (0x0)
        SERVICE_EXIT_CODE  : 0  (0x0)
        CHECKPOINT         : 0x1
        WAIT_HINT          : 0xbb8
        PID                : 11228
        FLAGS              :

A: Perhaps this needs a shell environment.  How about trying cmd /c sc ...
<exec executable="cmd.exe" failonerror="true">
    <arg line="/c sc \\@{server} @{operation} @{service}"/>
</exec>

A: This may or may not help you, but I had problems with the <exec> task with ant on a windows machine as well, in combination with the <arg line=..> statement. Ant just refused to treat the line of parameters as separate entities with spaces between them and I got weird errors like "unrecognised parameter" when it should have been a valid one.
My problems disappeared after I exchanged the one <arg line=> with one <arg value=...> for every parameter instead.
I also had to do it like Raghuram specified, and wrap everything in a shell environment as well.
Might be worth a try.


text:
Q: creating new table with dynamic partitions from existing non-partitioned table in Hive I have existing table structure in HIVE which has various fields e.g.(a string, b string, tstamp string, c string) including one tstamp field.
I need to create a new partitioned table(table_partitioned) from the existing table(original_table) but now this new table structure should be partitioned based on the date part of 'tstamp' field.
In order to solve this I created a new table schema similar to the existing table structure, and also added a partition column namely 'date_string' Using the following query :-
CREATE TABLE table_partitioned (a string, b string, tstamp string, c string) PARITITIONED BY (date_string string)

Then I tried to insert data into 'table_partitioned' using following Insert query :-
INSERT OVERWRITE TABLE table_partitioned PARTITION  (date_string) SELECT a,b,tstamp,c,to_date(tstamp) FROM original_table;

But the above Insert statment runs into all sorts of error as follows :-
Diagnostic Messages for this Task:
FAILED: Execution Error, return code 2 from org.apache.hadoop.hive.ql.exec.MapRedTask
MapReduce Jobs Launched:
Job 0: Map: 35   Cumulative CPU: 985.41 sec   HDFS Read: 5011021574 HDFS Write: 2831773796 FAIL
Total MapReduce CPU Time Spent: 16 minutes 25 seconds 410 msec

If I load only some data by putting a where clause in the Insert statement like below then it works it creates partition for matching rows:-
INSERT OVERWRITE TABLE table_partitioned PARTITION  (date_string) SELECT a,b,tstamp,c,to_date(tstamp) FROM original_table WHERE tstamp='2013-07-23 00:02:00'

NOTE:- I have around 2,00,000 data entry for each day e.g.2013-07-23  and the original_table has data for sound 2 years.
How can I insert all the data and at once, am I missing something ?


text:
Q: Facebook returning error '(#200) Requires extended permission: publish_actions' even after getting 'publish actions' permission approved Hi I got 'publish_actions' permission approved for my Facebook App.
But when any user accessing this app, it is not prompting for 'post on your behalf on Facebook' permission. Unless this when any user try to comment on Facebook using this app, Facebook returns error stating:

'(#200) Requires extended permission: publish_actions' OR 'The remote
  server returned an error: (403) Forbidden'.

Can any one please help me in this? Thanks in advance.

A: This error is thrown when you are using publish_actions permission without review.
For testing purpose you can always make a test user in Roles column of MyApp in developers.facebook.com and then use it..

A: Did you log the user in and ask for the publish_actions permission? If so can you provide the code you used for login and for sending the graph request?
The information in https://developers.facebook.com/docs/facebook-login/ios/permissions might be helpful


text:
Q: Is there a way to netboot to a live version of Windows 7? (NOT net-install) I am working on a project and I would like to be able to netboot into a simple image of Windows 7, similar to how one can netboot into a live version of a Linux distribution. I don't need the ability to install Windows 7, just the ability to boot into Windows and have some basic functionality (command prompt, file explorer, etc.). What would be the best way (if any) to do this? What would I need?
I have looked into a program called SERVA, which provides some PXE booting support, and I've actually got it working for a few diagnostic tools (MemTest, SeaTools) as well as installation images for Windows 7 and 8. Would I be able to use SERVA for what I need?

A: There are two ways you can go with this.
Officially, Microsoft offers Windows PE which has very basic functionality.  Typically it's used to deploy another OS or to repair an existing OS.
Unofficially, there are many third-party projects which try to add functionality to Windows PE to produce a live Linux type of experience.  I believe they're all based off WinBuilder, and others have been mentioned here in other answers.

A: Create your own Live Windows with Win7PE SE

This adds Windows Explorer to WinPE and some basic tools.

A: Serva can net install Windows/Linux images, net boot Linux Live distros and also (the Supporter version) can net boot any available Windows PE.
Remember there are license issues with the use of Windows PE plus it is time limited.
You can build customized Windows PE with Microsoft tools or some automated 3rd party tools like Winbuilder.
there is a product called ccboot that claims to boot windows 7 on a diskless client but I have no experience with it.


text:
Q: Generating all pentominoes by cutting and pasting Is it possible to place the twelve pentominoes around a circle in such a way that if two of the pentominoes find themselves next to each other, it is because one of the two can be obtained from the other by cutting out one of its component squares (thus obtaining a tetramino) and glueing it elsewhere?

A: Yes. Ugly representation below (* is the cell to be moved to . to obtain the next pentamino)
                                                                     .
####* -> ###* -> ### -> ### -> ###  -> *##  -> ##  -> ##  -> ##. -> ### ->  *   -> ####. -> #####
.        #.      #*     # .    * #.      ##     ##     #*     #      #     ###.     *
                 .      *                 .     .*     #.     #*     *      #


text:
Q: How do I vertically center numbers on an histogram plot in R? How do I center numbers on columns?
bar <- barplot(VADeaths)

text(rep(bar,each=nrow(VADeaths)),as.vector(apply(VADeaths,2,cumsum)),
 labels=as.vector(apply(VADeaths,2,cumsum)),
 pos=1,cex=1,adj = c(0,0),col="orange",offset = 0.2)

This is how it looks now:

And I need to make it like here:

How do I do this? Thank you!

A: You just need to adjust the y value by half of the bar height - and use adj to centre it...
bar <- barplot(VADeaths)

text(rep(bar, each=nrow(VADeaths)),
     as.vector(apply(VADeaths, 2, cumsum) - 0.5 * VADeaths),  #subtract half of bar height
     labels=as.vector(apply(VADeaths, 2, cumsum)),
     cex = 1, adj = c(0.5, 0.5), col = "orange")

A: the offset in the text function can help you with placing the label text to the center position.
A suggestion for you, try to manipulate the cex so that the size of the label gets shorten according to the bar chart.
bar <- barplot(VADeaths)

text(rep(bar,each=nrow(VADeaths)),as.vector(apply(VADeaths,2,cumsum)),
     labels=as.vector(apply(VADeaths,2,cumsum)),
     pos=1,cex=0.6,adj = c(0,0),col="orange",offset = 1.5)


text:
Q: Can we apply the Fundamental theorem of integration on $f(x)=\frac{1}{x}$ So, we're given $f(x)=\frac{1}{x}$ in $[-1;1]$.
AFAIK, the theorem only works if $f(x)$ is continuous, which in this case it isn't for $x=0$. So we cannot use the theorem.
If we just integrate it:
$\int_{-1}^1 \frac{1}{x}\,dx=ln|1|-ln|-1|=0$
Is this right? I'm just getting started and need a little help!

A: It is not right in because you integrated over an interval with zero as an x value. This has 1/0 which is undefined. If you are in a higher level course you could use the Cauchy principal value and get 0 but, if you are just starting it is wrong.
This is one of those questions that depends on the course.


text:
Q: How can I set ListView's scroll in NestedScroll, ConstraintLayout? I added my items on the ListView.
I can use NestedScroll's scroll but I can't show my listView's items, I can only show 3 one.
I want to a design like Twitter profile page
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context=".ProfileFragment">

    <android.support.design.widget.AppBarLayout...>

        <android.support.design.widget.CollapsingToolbarLayout
            ...>

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbarProfile"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

        </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>

    <android.support.v4.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="none"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        android:fillViewport="true">

        <ListView
            android:id="@+id/listViewProfile"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scrollbars="vertical">
        </ListView>

    </android.support.v4.widget.NestedScrollView>

</android.support.design.widget.CoordinatorLayout>

A: Enable nestedScrolling of your listview :
<ListView
     android:id="@+id/listViewProfile"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:nestedScrollingEnabled="true" \\add this line
     android:scrollbars="vertical">
</ListView>


text:
Q: Looping through a json object to parse a horizontal row using PHP I'm just a bit stuck on how to approach this situation.
I go this JSON that looks like this
[
{
    "date":"oct10",
    "number_x": "100",
    "number_y": "200",
    "number_z": "300"
},
{
    "date":"oct11",
    "number_x": "300",
    "number_y": "600",
    "number_z": "200"
},
{
    "date":"oct13",
    "number_x": "200",
    "number_y": "660",
    "number_z": "230"
}
]

I'm trying to achieve an output similar to this.

        "date":"oct10"
        "date":"oct11"
        "date":"oct12"

        "number_x": "100",
        "number_x": "300",
        "number_x": "200",

        "number_y": "200",
        "number_y": "600",
        "number_y": "660",

        "number_z": "300",
        "number_z": "200",
        "number_z": "230",

Any help or starting point would be greatly appreciated! Thank you for reading.

A: The below code will parse the json string, then build some extra arrays in order to pivot the data.
It will output as desired.
$jsonStr = '[
{
    "date":"oct10",
    "number_x": "100",
    "number_y": "200",
    "number_z": "300"
},
{
    "date":"oct11",
    "number_x": "300",
    "number_y": "600",
    "number_z": "200"
},
{
    "date":"oct13",
    "number_x": "200",
    "number_y": "660",
    "number_z": "230"
}
]';

$obj = json_decode($jsonStr);

foreach($obj as $row){
    $date[] = $row->date;
    $x[] = $row->number_x;
    $y[] = $row->number_y;
    $z[] = $row->number_z;

}

print '
' .
    '
' . implode('	Date: ',$date) . '
' .
    '
' . implode('	Number X : ',$x) . '
' .
    '
' . implode('	Number Y : ',$y) . '
' .
    '
' . implode('	Number X : ',$z) . '
' .
    '
';


text:
Q: AVAudioRecorder records only the audio after interruption In my application for recording and playing audio using AVAudioRecorder and AVAudioPlayer I came across a scenario in the case of incoming phone call.While the recording is in progress and if the phone call comes,the audio recorded after the phone call is only recorded.I want the recording recorded after the phone call to be the continuation of the audio recorded before the phone call.
I track the interruption occuring in audio recorder using the AVAudioRecorderDelegate methods

*

*(void)audioRecorderBeginInterruption:(AVAudioRecorder *)avRecorder
and

*(void)audioRecorderEndInterruption:(AVAudioRecorder *)avRecorder.

In my EndInterruption method I activates the audioSession.
Here is the recording code that I use
- (void)startRecordingProcess
{
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    NSError *err = nil;
    [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:&err];
    if(err)
    {
        DEBUG_LOG(@"audioSession: %@ %d %@", [err domain], [err code], [[err userInfo] description]);
        return;
    }
    [audioSession setActive:YES error:&err];
    err = nil;
    if(err)
    {
        DEBUG_LOG(@"audioSession: %@ %d %@", [err domain], [err code], [[err userInfo] description]);
        return;
    }
    // Record settings for recording the audio
    recordSetting = [[NSDictionary alloc] initWithObjectsAndKeys:
                     [NSNumber numberWithInt:kAudioFormatMPEG4AAC],AVFormatIDKey,
                     [NSNumber numberWithInt:44100],AVSampleRateKey,
                     [NSNumber numberWithInt: 2],AVNumberOfChannelsKey,
                     [NSNumber numberWithInt:16],AVLinearPCMBitDepthKey,
                     [NSNumber numberWithBool:NO],AVLinearPCMIsBigEndianKey,
                     [NSNumber numberWithBool:NO],AVLinearPCMIsFloatKey,
                     nil];
    BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:recorderFilePath];
    if (fileExists)
    {
        BOOL appendingFileExists =
            [[NSFileManager defaultManager] fileExistsAtPath:appendingFilePath];
        if (appendingFileExists)
        {
            [[NSFileManager defaultManager]removeItemAtPath:appendingFilePath error:nil];
        }
        if (appendingFilePath)
        {
            [appendingFilePath release];
            appendingFilePath = nil;
        }
        appendingFilePath = [[NSString alloc]initWithFormat:@"%@/AppendedAudio.m4a", DOCUMENTS_FOLDER];
        fileUrl = [NSURL fileURLWithPath:appendingFilePath];
    }
    else
    {
        isFirstTime = YES;
        if (recorderFilePath)
        {
            DEBUG_LOG(@"Testing 2");
            [recorderFilePath release];
            recorderFilePath = nil;
        }
        DEBUG_LOG(@"Testing 3");
        recorderFilePath = [[NSString alloc]initWithFormat:@"%@/RecordedAudio.m4a", DOCUMENTS_FOLDER];
        fileUrl = [NSURL fileURLWithPath:recorderFilePath];
    }
    err = nil;
    recorder = [[recorder initWithURL:fileUrl settings:recordSetting error:&err]retain];
    if(!recorder)
    {
        DEBUG_LOG(@"recorder: %@ %d %@", [err domain], [err code], [[err userInfo] description]);
        [[AlertFunctions sharedInstance] showMessageWithTitle:kAppName
                                                      message:[err localizedDescription]
                                                     delegate:nil
                                            cancelButtonTitle:@"Ok"];
        return;
    }
    //prepare to record
    [recorder setDelegate:self];
    [recorder prepareToRecord];
    recorder.meteringEnabled = YES;
    [recorder record];

}

While searching for a solution to this issue I came across another link
 how to resume recording after interruption occured in iphone? and http://www.iphonedevsdk.com/forum/iphone-sdk-development/31268-avaudiorecorderdelegate-interruption.html which speaks of the same issue.
I tried the suggestions that were given in those links but were not successful.
I hope to make it work with AVAudioRecorder itself.
Is there any way I could find a solution to this issue?
All valuable suggestions are appreciated.

A: After several research I was notified by Apple that it's an issue with the current API. So I managed to find a workaround for the issue by saving the previous audio file just after interruption and joining it with the resumed audio file. Hope it helps someone out there who may face the same issue.

A: I was also facing a similar issue where AVAudioRecorder was recording only after interruption.
So i fixed this issue by maintaining an array of recordings and keeping them in the NSTemporaryDirectory and finally merging them at the end.
Below are the key steps:

*

*Make your class listen to the AVAudioSessionInterruptionNotification.

*On interruption begin (AVAudioSessionInterruptionTypeBegan), save your recording

*On interruption end(AVAudioSessionInterruptionTypeEnded), start a new recording for interruption option AVAudioSessionInterruptionOptionShouldResume

*Append all recordings on hitting the Save button.

The code snippets for the above mentioned steps are:
// 1. Make this class listen to the AVAudioSessionInterruptionNotification in viewDidLoad
- (void)viewDidLoad
{
    [super viewDidLoad];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(handleAudioSessionInterruption:)
                                                 name:AVAudioSessionInterruptionNotification
                                               object:[AVAudioSession sharedInstance]];

    // other coding stuff
}

// observe the interruption begin / end
- (void)handleAudioSessionInterruption:(NSNotification*)notification
{
    AVAudioSessionInterruptionType interruptionType = [notification.userInfo[AVAudioSessionInterruptionTypeKey] unsignedIntegerValue];
    AVAudioSessionInterruptionOptions interruptionOption = [notification.userInfo[AVAudioSessionInterruptionOptionKey] unsignedIntegerValue];

    switch (interruptionType) {
        // 2. save recording on interruption begin
        case AVAudioSessionInterruptionTypeBegan:{
            // stop recording
            // Update the UI accordingly
            break;
        }
        case AVAudioSessionInterruptionTypeEnded:{
            if (interruptionOption == AVAudioSessionInterruptionOptionShouldResume) {
                // create a new recording
                // Update the UI accordingly
            }
            break;
        }

        default:
            break;
    }
}

// 4. append all recordings
- (void) audioRecorderDidFinishRecording:(AVAudioRecorder *)avrecorder successfully:(BOOL)flag
{
    // append all recordings one after other
}

Here is a working example:
//
//  XDRecordViewController.m
//
//  Created by S1LENT WARRIOR
//

#import "XDRecordViewController.h"

@interface XDRecordViewController ()
{
    AVAudioRecorder *recorder;

    __weak IBOutlet UIButton* btnRecord;
    __weak IBOutlet UIButton* btnSave;
    __weak IBOutlet UIButton* btnDiscard;
    __weak IBOutlet UILabel*  lblTimer; // a UILabel to display the recording time

    // some variables to display the timer on a lblTimer
    NSTimer* timer;
    NSTimeInterval intervalTimeElapsed;
    NSDate* pauseStart;
    NSDate* previousFireDate;
    NSDate* recordingStartDate;

    // interruption handling variables
    BOOL isInterrupted;
    NSInteger preInterruptionDuration;

    NSMutableArray* recordings; // an array of recordings to be merged in the end
}
@end

@implementation XDRecordViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Make this class listen to the AVAudioSessionInterruptionNotification
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(handleAudioSessionInterruption:)
                                                 name:AVAudioSessionInterruptionNotification
                                               object:[AVAudioSession sharedInstance]];

    [self clearContentsOfDirectory:NSTemporaryDirectory()]; // clear contents of NSTemporaryDirectory()

    recordings = [NSMutableArray new]; // initialize recordings

    [self setupAudioSession]; // setup the audio session. you may customize it according to your requirements
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    [self initRecording];   // start recording as soon as the view appears
}

- (void)dealloc
{
    [self clearContentsOfDirectory:NSTemporaryDirectory()]; // remove all files files from NSTemporaryDirectory

    [[NSNotificationCenter defaultCenter] removeObserver:self]; // remove this class from NSNotificationCenter
}

#pragma mark - Event Listeners

// called when recording button is tapped
- (IBAction) btnRecordingTapped:(UIButton*)sender
{
    sender.selected = !sender.selected; // toggle the button

    if (sender.selected) { // resume recording
        [recorder record];
        [self resumeTimer];
    } else { // pause recording
        [recorder pause];
        [self pauseTimer];
    }
}

// called when save button is tapped
- (IBAction) btnSaveTapped:(UIButton*)sender
{
    [self pauseTimer]; // pause the timer

    // disable the UI while the recording is saving so that user may not press the save, record or discard button again
    btnSave.enabled = NO;
    btnRecord.enabled = NO;
    btnDiscard.enabled = NO;

    [recorder stop]; // stop the AVAudioRecorder so that the audioRecorderDidFinishRecording delegate function may get called

    // Deactivate the AVAudioSession
    NSError* error;
    [[AVAudioSession sharedInstance] setActive:NO error:&error];
    if (error) {
        NSLog(@"%@", error);
    }
}

// called when discard button is tapped
- (IBAction) btnDiscardTapped:(id)sender
{
    [self stopTimer]; // stop the timer

    recorder.delegate = Nil; // set delegate to Nil so that audioRecorderDidFinishRecording delegate function may not get called
    [recorder stop];  // stop the recorder

    // Deactivate the AVAudioSession
    NSError* error;
    [[AVAudioSession sharedInstance] setActive:NO error:&error];
    if (error) {
        NSLog(@"%@", error);
    }

    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - Notification Listeners
// called when an AVAudioSessionInterruption occurs
- (void)handleAudioSessionInterruption:(NSNotification*)notification
{
    AVAudioSessionInterruptionType interruptionType = [notification.userInfo[AVAudioSessionInterruptionTypeKey] unsignedIntegerValue];
    AVAudioSessionInterruptionOptions interruptionOption = [notification.userInfo[AVAudioSessionInterruptionOptionKey] unsignedIntegerValue];

    switch (interruptionType) {
        case AVAudioSessionInterruptionTypeBegan:{
            // • Recording has stopped, already inactive
            // • Change state of UI, etc., to reflect non-recording state
            preInterruptionDuration += recorder.currentTime; // time elapsed
            if(btnRecord.selected) {    // timer is already running
                [self btnRecordingTapped:btnRecord];  // pause the recording and pause the timer
            }

            recorder.delegate = Nil; // Set delegate to nil so that audioRecorderDidFinishRecording may not get called
            [recorder stop];    // stop recording
            isInterrupted = YES;
            break;
        }
        case AVAudioSessionInterruptionTypeEnded:{
            // • Make session active
            // • Update user interface
            // • AVAudioSessionInterruptionOptionShouldResume option
            if (interruptionOption == AVAudioSessionInterruptionOptionShouldResume) {
                // Here you should create a new recording
                [self initRecording];   // create a new recording
                [self btnRecordingTapped:btnRecord];
            }
            break;
        }

        default:
            break;
    }
}

#pragma mark - AVAudioRecorderDelegate
- (void) audioRecorderDidFinishRecording:(AVAudioRecorder *)avrecorder successfully:(BOOL)flag
{
    [self appendAudiosAtURLs:recordings completion:^(BOOL success, NSURL *outputUrl) {
        // do whatever you want with the new audio file :)
    }];
}

#pragma mark - Timer
- (void)timerFired:(NSTimer*)timer
{
    intervalTimeElapsed++;
    [self updateDisplay];
}

// function to time string
- (NSString*) timerStringSinceTimeInterval:(NSTimeInterval)timeInterval
{
    NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"mm:ss"];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];
    return [dateFormatter stringFromDate:timerDate];
}

// called when recording pauses
- (void) pauseTimer
{
    pauseStart = [NSDate dateWithTimeIntervalSinceNow:0];

    previousFireDate = [timer fireDate];

    [timer setFireDate:[NSDate distantFuture]];
}

- (void) resumeTimer
{
    if (!timer) {
        timer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                                 target:self
                                               selector:@selector(timerFired:)
                                               userInfo:Nil
                                                repeats:YES];
        return;
    }

    float pauseTime = - 1 * [pauseStart timeIntervalSinceNow];

    [timer setFireDate:[previousFireDate initWithTimeInterval:pauseTime sinceDate:previousFireDate]];
}

- (void)stopTimer
{
    [self updateDisplay];
    [timer invalidate];
    timer = nil;
}

- (void)updateDisplay
{
    lblTimer.text = [self timerStringSinceTimeInterval:intervalTimeElapsed];
}

#pragma mark - Helper Functions
- (void) initRecording
{

    // Set the audio file
    NSString* name = [NSString stringWithFormat:@"recording_%@.m4a", @(recordings.count)]; // creating a unique name for each audio file
    NSURL *outputFileURL = [NSURL fileURLWithPathComponents:@[NSTemporaryDirectory(), name]];

    [recordings addObject:outputFileURL];

    // Define the recorder settings
    NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc] init];

    [recordSetting setValue:@(kAudioFormatMPEG4AAC) forKey:AVFormatIDKey];
    [recordSetting setValue:@(44100.0) forKey:AVSampleRateKey];
    [recordSetting setValue:@(1) forKey:AVNumberOfChannelsKey];

    NSError* error;
    // Initiate and prepare the recorder
    recorder = [[AVAudioRecorder alloc] initWithURL:outputFileURL settings:recordSetting error:&error];
    recorder.delegate = self;
    recorder.meteringEnabled = YES;
    [recorder prepareToRecord];

    if (![AVAudioSession sharedInstance].inputAvailable) { // can not record audio if mic is unavailable
        NSLog(@"Error: Audio input device not available!");
        return;
    }

    intervalTimeElapsed = 0;
    recordingStartDate = [NSDate date];

    if (isInterrupted) {
        intervalTimeElapsed = preInterruptionDuration;
        isInterrupted = NO;
    }

    // Activate the AVAudioSession
    [[AVAudioSession sharedInstance] setActive:YES error:&error];
    if (error) {
        NSLog(@"%@", error);
    }

    recordingStartDate = [NSDate date];  // Set the recording start date
    [self btnRecordingTapped:btnRecord];
}

- (void)setupAudioSession
{

    static BOOL audioSessionSetup = NO;
    if (audioSessionSetup) {
        return;
    }

    AVAudioSession* session = [AVAudioSession sharedInstance];

    [session setCategory:AVAudioSessionCategoryPlayAndRecord
             withOptions:AVAudioSessionCategoryOptionDefaultToSpeaker
                   error:Nil];

    [session setMode:AVAudioSessionModeSpokenAudio error:nil];

    audioSessionSetup = YES;
}

// gets an array of audios and append them to one another
// the basic logic was derived from here: http://stackoverflow.com/a/16040992/634958
// i modified this logic to append multiple files
- (void) appendAudiosAtURLs:(NSMutableArray*)urls completion:(void(^)(BOOL success, NSURL* outputUrl))handler
{
    // Create a new audio track we can append to
    AVMutableComposition* composition = [AVMutableComposition composition];
    AVMutableCompositionTrack* appendedAudioTrack =
    [composition addMutableTrackWithMediaType:AVMediaTypeAudio
                             preferredTrackID:kCMPersistentTrackID_Invalid];

    // Grab the first audio track that need to be appended
    AVURLAsset* originalAsset = [[AVURLAsset alloc]
                                 initWithURL:urls.firstObject options:nil];
    [urls removeObjectAtIndex:0];

    NSError* error = nil;

    // Grab the first audio track and insert it into our appendedAudioTrack
    AVAssetTrack *originalTrack = [[originalAsset tracksWithMediaType:AVMediaTypeAudio] firstObject];
    CMTimeRange timeRange = CMTimeRangeMake(kCMTimeZero, originalAsset.duration);
    [appendedAudioTrack insertTimeRange:timeRange
                                ofTrack:originalTrack
                                 atTime:kCMTimeZero
                                  error:&error];
    CMTime duration = originalAsset.duration;

    if (error) {
        if (handler) {
            dispatch_async(dispatch_get_main_queue(), ^{
                handler(NO, Nil);
            });
        }
    }

    for (NSURL* audioUrl in urls) {
        AVURLAsset* newAsset = [[AVURLAsset alloc]
                                initWithURL:audioUrl options:nil];

        // Grab the rest of the audio tracks and insert them at the end of each other
        AVAssetTrack *newTrack = [[newAsset tracksWithMediaType:AVMediaTypeAudio] firstObject];
        timeRange = CMTimeRangeMake(kCMTimeZero, newAsset.duration);
        [appendedAudioTrack insertTimeRange:timeRange
                                    ofTrack:newTrack
                                     atTime:duration
                                      error:&error];

        duration = appendedAudioTrack.timeRange.duration;

        if (error) {
            if (handler) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    handler(NO, Nil);
                });
            }
        }
    }

    // Create a new audio file using the appendedAudioTrack
    AVAssetExportSession* exportSession = [AVAssetExportSession
                                           exportSessionWithAsset:composition
                                           presetName:AVAssetExportPresetAppleM4A];
    if (!exportSession) {
        if (handler) {
            dispatch_async(dispatch_get_main_queue(), ^{
                handler(NO, Nil);
            });
        }
    }

    NSArray* appendedAudioPath = @[NSTemporaryDirectory(), @"temp.m4a"]; // name of the final audio file
    exportSession.outputURL = [NSURL fileURLWithPathComponents:appendedAudioPath];
    exportSession.outputFileType = AVFileTypeAppleM4A;
    [exportSession exportAsynchronouslyWithCompletionHandler:^{

        BOOL success = NO;
        // exported successfully?
        switch (exportSession.status) {
            case AVAssetExportSessionStatusFailed:
                break;
            case AVAssetExportSessionStatusCompleted: {
                success = YES;

                break;
            }
            case AVAssetExportSessionStatusWaiting:
                break;
            default:
                break;
        }

        if (handler) {
            dispatch_async(dispatch_get_main_queue(), ^{
                handler(success, exportSession.outputURL);
            });
        }
    }];
}

- (void) clearContentsOfDirectory:(NSString*)directory
{
    NSFileManager *fm = [NSFileManager defaultManager];
    NSError *error = nil;
    for (NSString *file in [fm contentsOfDirectoryAtPath:directory error:&error]) {
        [fm removeItemAtURL:[NSURL fileURLWithPathComponents:@[directory, file]] error:&error];
    }
}

@end

I know its too late to answer to question, but hope this helps someone else!


text:
Q: i need to create a text file that contains the output of my function in haskell I just want to write something on the code that creates a text file that contains the output of a function. I want to specify the name of the text file on the code
Like: create a file named "output.txt" that contains the output of the function rectangleArea.
How do I turn thsi into code?
I haven't tried anything yet because i really have no idea how this works. I've read tutorials but I still couldn't find a way to do this.

A: Well then lets try something like this:
main = writeFile filename $ show $ func parameters

For your case this would be something like this:
main = writeFile "output.txt" $ show $ rectangleArea parameter1 parameter2

A small working example:
main = do
  width <- fmap read $ getLine
  height <- fmap read $ getLine
  filename <- getLine
  writeFile filename $ show $ rectangleArea width height

rectangleArea w h = w * h

Getting input by the user works best when using getLine, like this for example:
main = do
    name <- getLine
    print ("Hello " ++ name)

For further information on in- and output in Haskell I strongly recommend this chapter from the LYAH tutorial as it covers the basics extremely well and will help you with your problem.


text:
Q: Container view's collectionVC blocked with Parent's tapGesture recognizer I have an extension of UIViewController as follows to dismiss the keyboard if the user taps on the screen. Within this view I have a scroll containing textfields and two container views. The container views contain a collectionView. I want my overall viewController to dismiss when tapped around but I still want my collectionView's didSelectitemAtIndexPath to trigger. How can I achieve this?
public extension UIViewController {
    public func hideKeyboardWhenTappedAround() {
        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
        view.addGestureRecognizer(tap)
    }

    public func dismissKeyboard() {
        view.endEditing(true)
    }
}

and
class RegisterVC: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        logViewLoad()
        self.hideKeyboardWhenTappedAround()
        let controller = self.storyboard?.instantiateViewController(withIdentifier: "CollectionViewSearchVC") as! CollectionViewSearchVC
        controller.type = "SC"
        addChildViewController(controller)
        controller.view.translatesAutoresizingMaskIntoConstraints = false
        controller.delegate = self
        containerView.addSubview(controller.view)

        NSLayoutConstraint.activate([
            controller.view.leadingAnchor.constraint(equalTo: containerView.leadingAnchor),
            controller.view.trailingAnchor.constraint(equalTo: containerView.trailingAnchor),
            controller.view.topAnchor.constraint(equalTo: containerView.topAnchor),
            controller.view.bottomAnchor.constraint(equalTo: containerView.bottomAnchor)
            ])

        controller.didMove(toParentViewController: self)
        subContractorVC = controller

        let employeeController = self.storyboard?.instantiateViewController(withIdentifier: "CollectionViewSearchVC") as! CollectionViewSearchVC
        employeeController.type = "V"
        employeeController.delegate = self
        addChildViewController(employeeController)
        employeeController.view.translatesAutoresizingMaskIntoConstraints = false
        employeeContainerView.addSubview(employeeController.view)

        NSLayoutConstraint.activate([
            employeeController.view.leadingAnchor.constraint(equalTo: employeeContainerView.leadingAnchor),
            employeeController.view.trailingAnchor.constraint(equalTo: employeeContainerView.trailingAnchor),
            employeeController.view.topAnchor.constraint(equalTo: employeeContainerView.topAnchor),
            employeeController.view.bottomAnchor.constraint(equalTo: employeeContainerView.bottomAnchor)
            ])

        employeeController.didMove(toParentViewController: self)
    }

A: Implement the delegate methods for the GestureRecogniser in your ViewController and check for the class which is being touched, if that is of kind UICollectionView, then ignore that touch and let it do the default behaviour, i.e didSelect otherwise allow tap.
class ParentViewController: UIViewController {
var tap: UITapGestureRecognizer?

override func viewDidLoad() {
    super.viewDidLoad()
    tap = UITapGestureRecognizer(target: self, action: #selector(self.dismissKeyboard))
    view.addGestureRecognizer(tap!)
}

public func hideKeyboardWhenTappedAround() {
    dismissKeyboard()
}

@objc public func dismissKeyboard() {
    view.endEditing(true)
}
}

class RegisterVC: ParentViewController, UIGestureRecognizerDelegate {
override func viewDidLoad() {
  super.viewDidLoad()
  tap?.delegate = self
// YOUR EXISTING CODE HERE
}
// NEW CODE ADDED HERE
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
    print("shouldReceive")
    print(gestureRecognizer.view as Any) // CHECK FOR WHICH CLASS YOU ARE GETTING HERE WHEN YOU CLICK ON COLLECTIONVIEW
    if (gestureRecognizer.view?.isKind(of: UICollectionView.self))! {
        return false
    }
    return true
}
}

Try it and share the results.

A: You need to create a view behind the child VC's views and add the gesture to it


text: Q: Which are the spectral lines used to calculate the redshift? I'm not sure if this is correct but I read in an article that the light of a distant star is first passed through a tube containing hydrogen gas and then through the prism for getting the absorption lines of Hydrogen. However, doesn't the atmosphere of the star itself have different elements (hydrogen, helium, etc.) which already absorb the frequencies of light according to their properties? I believe then the light as it is emitted from the star should already have absorption lines, whose redshift could be studied without passing through any additional gas. I'm a bit confused regarding the process used. Is the composition of the star first figured out from the spectral line spacings and then the shift observed?


text:
Q: Angular2 Dart - get child elements of component I have a component called button-search which has a dropdown with search options:
<button-search>
    <item type="identifier">Identifier</item>
    <item type="title">Title</item>
    <item type="city">City</item>
    <item type="town">Town</item>
    <item type="address">Address</item>
    <item type="postal">Postal</item>
    <item type="divider"></item>
    <item type="clear">Clear Search</item>
</button-search>

The item component is not supposed to render anything directly and is rather for passing complex params into the button-search component so that the button-search component can render those dropdown items the way it should be rendered.
Item is defined as follow:
@Component(
    selector: 'item',
    template: '')
class Item {

    @Input() String type = "type-goes-here";

}

ButtonSearch is defined as follow:
@Component(
    selector: 'button-search',
    directives: const[Item],
    template: '''
       ... enormous template ...
    ''')
class ButtonSearch {

    ButtonSearch(@ViewChildren(Item) QueryList<Item> items){

        print(items);

    }
}

Instead of seeing a list of 9 items being printed to the console, all I'm seeing is [].
I've tried using a String param instead of an object, but it still gives me null.
ButtonSearch(@ViewChildren('item') QueryList<Item> items){

*

*What am I missing to make @ViewChildren get all the items and print something other than []

*Is there something special that needs to be done to get the text between <item> and </item> or will @ViewChild work for that ?
Update: Changing the template to include <ng-content></ng-content>:
template: '''
          <ng-content></ng-content>
           ... enormous template ...
        ''')

I can see the following being printed in the browser as part of the button-search component:

Identifier, Title, City, Town, Address, Postal, Clear Search

So at least I know the page I'm on does have items in its button-search component.

A: It should be
@Component(
    selector: 'button-search',
    directives: const[Item],
    template: '''
       <ng-content></ng-content>
       ... enormous template ...
    ''')
class ButtonSearch implements AfterContentInit{
    @ContentChildren(Item) QueryList<Item> items;

    ngAfterContentInit() {
        print(items);
    }
}

See also https://stackoverflow.com/a/35209681/217408
There is also the @Query() annotation which allows to constructor-inject references to child elements but it is marked deprecated.
<ng-content>
If you pass "content" as children to your component, then you can query them using @ContentChildren() instead of @ViewChildren(). If you want them to be displayed in the DOM you also need to add the <ng-content></ng-content> tag as a target for the transclusion. You can also have multiple <ng-content></ng-content> tags where a select=".someCssSelector" can be used to transclude a subset of content at a specific target location. There should be only one <ng-content></ng-content> without the select attribute though. The first without select will target all content that doesn't match other selectors.
Plunker example


text:
Q: Android Bitmap Memory Use I am running a stack of image filters and seem to be hitting some memory issues.
At the beginning of the image processing I am using this much memory:
GC_FOR_MALLOC freed 3K, 45% free 3237K/5831K, external 47586K/49634K, paused 17ms

At the end I am using this much (after all processing is finished):
GC_EXTERNAL_ALLOC freed 5K, 16% free 16056K/18951K, external 51430K/52196K, paused 23ms

After I am finished with each bitmap I set it to recycle and to null:
someBitmap.recycle();
someBitmap = null;

Is there anything else I should be doing to them? Is there any cleanup I should do to the Canvas being used?
Also my filters are objects instantiated like:
BoxBlurFilter blurFilter = new BoxBlurFilter();

Is there anything I should do to release them? In iOS memory allocated with "new" I am responsible to free.
Sorry for the trivial memory management questions, but I am quite new to Android dev and things are quite different than iOS.
Thank you!
EDIT 2, I removed my full filter code.

A: So after setting the filter instances to null and all the byte arrays to null (in the code above and in the filter objects) I now have approximately the same size heap as I did before I run the filter:
GC_EXPLICIT freed 5126K, 77% free 3243K/13703K, external 51430K/53478K, paused 18ms

That means it went from 16mb being used to 3.2mb. Much better!
So I guess the answer to my question is make sure you set everything to null if you want it to be freed.


text:
Q: Java equivalents of DBL_MIN_10_EXP, FLT_RADIX and others from float.h I'm working on adding sys.float_info to Jython. It has several attributes from float.h.
I'm trying to find the Java equivalent for DBL_MIN_10_EXP, DBL_MANT_DIG, FLT_RADIX and FLT_ROUNDS.
Any ideas?
I think I have the rest of the attributes, some from java.lang.Double and the rest from looking at Num class in the ssj library.

A: I don't recall those constants being part of any standard class (java.lang.Double and java.lang.Float being the most likely places).  Seems like you would be safe in just defining them on your own since Java floats and doubles follow the IEEE 754 standard by spec.  http://en.wikipedia.org/wiki/IEEE_754
DBL_MIN_10_EXP = -307
DBL_MANT_DIG = 53
FLT_RADIX = 2

Not sure about FLT_ROUNDS though... might be 1 (nearest), but you could use -1 (unknown) to be on the safe-side.


text:
Q: Find the maximum value of $\sqrt{x - 144} + \sqrt{722 - x}$
Find the maximum value of $\sqrt{x - 144} + \sqrt{722 - x} .$

What I Tried :- Let me tell you first . What I Tried is absolutely silly , but you may check for it .
I thought AM-GM would do the trick and got :-
$\sqrt{x - 144} + \sqrt{722 - x} \geq 2 \sqrt{\sqrt{(x - 144)(722 - x)}}$
$\rightarrow \sqrt{x - 144} + \sqrt{722 - x} \geq 2 \sqrt{\sqrt{(-x^2 + 866x + 103968)}}$
From here I realised that there's no useful information I can find for $x$ .
Back to Another Attempt :- let $P = \sqrt{x - 144} + \sqrt{722 - x}$ . Then :-
$P^2 = 578 + 2\sqrt{(x - 144)(722 - x)}$
As $P \geq 0$ , we have that $P^2 \geq 578 \rightarrow P \geq 17\sqrt2 .$
This Attempt seemed reasonable and I thought I already found the solution, but then I realised that this is the minimum value of $P$ , and now I am hopeless .
Wolfram Alpha gives the answer to be $34$ , which can also be checked by Trial and Error of integer values , but that does not seem to be a proof of this problem .
Can anyone help me with this?

A: By Cauchy-Schwartz:
$a=x-144,b=722-x$
$\sqrt{a}+\sqrt{b}\le \sqrt{(a+b)(1+1)}=\sqrt{1156}$
(You can read https://en.wikipedia.org/wiki/Cauchy%E2%80%93Schwarz_inequality)
Alternbatively
${(\sqrt{a}+\sqrt{b})}^2=a+b+2\sqrt{ab}$
recall by AM-Gm
$2\sqrt{ab}\le a+b$
thus
${(\sqrt{a}+\sqrt{b})}^2\le 2(a+b)$
So finally,
$\sqrt{a} + \sqrt{b} \le \sqrt{2(a+b)}$
Equality holds for $a=b$.

A: We have that $P^2=578+2\sqrt{(x-144)(722-x)}$
To maximize $P^2$ is to maximize $(x-144)(722-x)$, which is a downward parabola. By symmetry, it is maximized right between the two roots, i.e. at $x=\frac{(722+144)}{2}=433$
This also maximizes $P$ since it is always positive, so the maximum is $P$ evaluated at $433$, which yields $34$

A: Use
$$2(p^2+q^2)-(p+q)^2=\cdots\ge0$$
$$\implies p+q\le\sqrt{2(p^2+q^2)}$$
Here $p^2=x-144,q^2=722-x$

A: I agree with Evariste's answer, but would like to offer an alternative approach.  My approach begins with Evariste's conclusion that it is desired to maximize
$(x - 144)(722 - x) = -x^2 + x(866) - (144 \times 722).$
This is equivalent to trying to maximize
$-x^2 + x(866)$, where (presumably) $x$ is required to be in the interval [144, 722].
Suppose you pose the equation $-x^2 + x(866) = k.$
Then the question is what is the largest possible (real) value for $k$
that will generate at least one real root for $x.$
The above equation is equivalent to the equation $x^2 - x(866) + k = 0.$
This equation will have at least one real root if and only if
$[(866)^2 - 4k] \;\geq\; 0.$
This means that the largest permissible value of $k$ is
$\frac{1}{4} \times (866)^2.$
It is immediate that choosing this value for $k$ will cause
$[(866)^2 - 4k]$ to equal 0.
This means that with this choice of $k$, the root(s) of
$x^2 - x(866) + k = 0$ will be
$x = (866/2)$.
By the above analysis, the OP's original expression should therefore be maximized by
$x = 433.$

A: By C-S $$\sqrt{x-144}+\sqrt{722-x}\leq\sqrt{(1+1)(x-144+722-x)}=34.$$
The equality occurs for $(1,1)||(x-144,722-x),$ which says that we got a maximal value.


text:
Q: bpf_map_get_next_key and BPF_MAP_GET_NEXT_KEY returns -1 errno = 2 | ebpf xdp So I have this kernel ebpf program and usersapce program, in userspace loader program I am calling bpf_map_get_next_key to get the key but calls to this returns -1
I checked the code in bpf_map_get_next_key there is not much except populating union bpf_attr attr; but followinfg sys_call inside the bpf_map_get_next_key cause errno to be 2 so I check googling and I just dont get any link useful except that it may be permission issue or somet thing [https://github.com/falcosecurity/falco/issues/1299]
So I like to knw what am I doing wrong in following user loader program and kernel ebpf program. Can any one please guide me through this error
this is libbpf function that cause syscall to return -1 libbpf/src/bpf.c
int bpf_map_get_next_key(int fd, const void *key, void *next_key)
{
    union bpf_attr attr;

    memset(&attr, 0, sizeof(attr));
    attr.map_fd = fd;
    attr.key = ptr_to_u64(key);
    attr.next_key = ptr_to_u64(next_key);

    int x=sys_bpf(BPF_MAP_GET_NEXT_KEY, &attr, sizeof(attr));
    printf("errno = %d | bpf_map_get_next_key = %d\n",errno,x);
    return x;
}

This is my kernel ebpf program
/* SPDX-License-Identifier: GPL-2.0 */

#include <linux/bpf.h>

#include <bpf/bpf_helpers.h>
#include <linux/if_ether.h>
#include <linux/ip.h>
#include <linux/udp.h>
void *memcpy(void *, const void *, unsigned long);

int IPPROTO_UDP = 17;

struct share_me
{

    struct iphdr dest_ip;
};

struct bpf_map_def SEC("maps") ip_map = {
    .type = BPF_MAP_TYPE_HASH,
    .key_size = sizeof(int),
    .value_size = sizeof(struct share_me),
    .max_entries = 64,  /* Assume netdev has no more than 64 queues */
};

struct bpf_map_def SEC("maps") xsks_map = {
    .type = BPF_MAP_TYPE_XSKMAP,
    .key_size = sizeof(int),
    .value_size = sizeof(int),
    .max_entries = 64,  /* Assume netdev has no more than 64 queues */
};

struct bpf_map_def SEC("maps") xdp_stats_map = {
    .type        = BPF_MAP_TYPE_PERCPU_ARRAY,
    .key_size    = sizeof(int),
    .value_size  = sizeof(__u32),
    .max_entries = 64,
};

SEC("xdp_sock")
int xdp_sock_prog(struct xdp_md *ctx)
{
    int index = ctx->rx_queue_index;
    __u32 *pkt_count;

    void *data = (void *)(long)ctx->data;
    void *data_end = (void *)(long)ctx->data_end;
    struct ethhdr *eth = data;
    struct share_me me;

    if ((void *)eth + sizeof(*eth) <= data_end)
    {

        struct iphdr *ip = data + sizeof(*eth);
        //me.dest_ip=ip;

        if(((void *)ip+sizeof(*ip))<=data_end)
        {
             struct iphdr ip_temp=(struct iphdr)*ip;
            memcpy(&me.dest_ip,&ip_temp,sizeof(ip_temp));
            bpf_map_lookup_elem(&ip_map, &index);
            bpf_map_update_elem(&ip_map,&index,&me,0);
            if ((void *)ip + sizeof(*ip) <= data_end)
            {

                if (ip->protocol == IPPROTO_UDP)
                {

           struct udphdr *udp = (void *)ip + sizeof(*ip);
           if ((void *)udp + sizeof(*udp) <= data_end)
           {
               //u64 value = htons(udp->dest);
               //counter.increment(value);
           }
                }
            }
         }
    }

    pkt_count = bpf_map_lookup_elem(&xdp_stats_map, &index);
    if (pkt_count) {

        /* We pass every other packet */
        if ((*pkt_count)++ & 1)
            return XDP_DROP;
    }

    /* A set entry here means that the correspnding queue_id
     * has an active AF_XDP socket bound to it. */
    if (bpf_map_lookup_elem(&xsks_map, &index))
        return bpf_redirect_map(&xsks_map, index, 0);

    return XDP_PASS;
}

char _license[] SEC("license") = "GPL";

and this is my userspace loader program
/* SPDX-License-Identifier: GPL-2.0 */

#include <assert.h>
#include <errno.h>
#include <getopt.h>
#include <locale.h>
#include <poll.h>
#include <pthread.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>

#include <sys/resource.h>

#include <bpf/bpf.h>
#include <bpf/xsk.h>

#include <arpa/inet.h>
#include <net/if.h>
#include <linux/if_link.h>
#include <linux/if_ether.h>
#include <linux/ipv6.h>
#include <linux/icmpv6.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#include <linux/types.h>
#include "../common/common_params.h"
#include "../common/common_user_bpf_xdp.h"
#include "../common/common_libbpf.h"

struct share_me
{

    struct iphdr dest_ip;
};

int map_data(int map_fd)
{

    int key = 0, next_key=0;
    __u64 value;

    while (bpf_map_get_next_key(map_fd, &key, &next_key) == 0)
    {
        struct share_me value;
        bpf_map_lookup_elem(map_fd, &next_key, &value);
        //print_stack(&next_key, value);
        struct iphdr *iph;
        iph=&value.dest_ip;
        printf("ihl = %x\n",iph->ihl);
        printf("tos = %x\n",iph->tos);
        printf("id = %x\n",ntohs(iph->id));
        key = next_key;
    }

}

int main()
{
    struct bpf_object *bpf_obj;
    struct bpf_program *bpf_prog;
    bpf_obj = load_bpf_object_file("af_xdp_kern.o", 0);
    if (!bpf_obj) {
        printf("ERR: loading file:\n");
        exit(EXIT_FAIL_BPF);
    }
    else{
        printf("load_bpf_object_file fine\n");
    }
             bpf_prog = bpf_program__next(NULL, bpf_obj);
    if (!bpf_prog)
    {
        printf("bpf_program_next:\n");
        exit(0);
    }
    else{
        printf("bpf_progra_next fine\n");
    }
    int prog_fd = bpf_program__fd(bpf_prog);
    if (prog_fd <= 0) {
        printf("prog fd <0");
    }
    else{
        printf("bpf_program_fd fine\n");
    }
    int err = xdp_link_attach(if_nametoindex("eno1"), 0, prog_fd);
    if(err)
    {

        printf("xdp_link_attach\n");
        exit(0);
    }
    else{
        printf("xdp_link_attacj fine\n");
    }
    struct bpf_map *map1 = bpf_object__find_map_by_name(bpf_obj, "ip_map");
    int map_fd = bpf_map__fd(map1);
    if(map_fd<0)
    {
        printf("map fd <0\n");
        exit(0);

    }
    else
    {
        printf("bpf_map_fd fine\n");
    }

    map_data(map_fd);
    bpf_set_link_xdp_fd(if_nametoindex("eno1"), -1,0);

    return 0;

}

Update
bpf map dump ip_map
shows
# bpftool map dump ip_map
Usage: /usr/lib/linux-tools/5.13.0-25-generic/bpftool map { show | list }   [MAP]
       /usr/lib/linux-tools/5.13.0-25-generic/bpftool map create     FILE type TYPE key KEY_SIZE value VALUE_SIZE \
                                  entries MAX_ENTRIES name NAME [flags FLAGS] \
                                  [inner_map MAP] [dev NAME]
       /usr/lib/linux-tools/5.13.0-25-generic/bpftool map dump       MAP
       /usr/lib/linux-tools/5.13.0-25-generic/bpftool map update     MAP [key DATA] [value VALUE] [UPDATE_FLAGS]
       /usr/lib/linux-tools/5.13.0-25-generic/bpftool map lookup     MAP [key DATA]
       /usr/lib/linux-tools/5.13.0-25-generic/bpftool map getnext    MAP [key DATA]
       /usr/lib/linux-tools/5.13.0-25-generic/bpftool map delete     MAP  key DATA
       /usr/lib/linux-tools/5.13.0-25-generic/bpftool map pin        MAP  FILE
       /usr/lib/linux-tools/5.13.0-25-generic/bpftool map event_pipe MAP [cpu N index M]
       /usr/lib/linux-tools/5.13.0-25-generic/bpftool map peek       MAP
       /usr/lib/linux-tools/5.13.0-25-generic/bpftool map push       MAP value VALUE
       /usr/lib/linux-tools/5.13.0-25-generic/bpftool map pop        MAP
       /usr/lib/linux-tools/5.13.0-25-generic/bpftool map enqueue    MAP value VALUE
       /usr/lib/linux-tools/5.13.0-25-generic/bpftool map dequeue    MAP
       /usr/lib/linux-tools/5.13.0-25-generic/bpftool map freeze     MAP
       /usr/lib/linux-tools/5.13.0-25-generic/bpftool map help

       MAP := { id MAP_ID | pinned FILE | name MAP_NAME }
       DATA := { [hex] BYTES }
       PROG := { id PROG_ID | pinned FILE | tag PROG_TAG | name PROG_NAME }
       VALUE := { DATA | MAP | PROG }
       UPDATE_FLAGS := { any | exist | noexist }
       TYPE := { hash | array | prog_array | perf_event_array | percpu_hash |
                 percpu_array | stack_trace | cgroup_array | lru_hash |
                 lru_percpu_hash | lpm_trie | array_of_maps | hash_of_maps |
                 devmap | devmap_hash | sockmap | cpumap | xskmap | sockhash |
                 cgroup_storage | reuseport_sockarray | percpu_cgroup_storage |
                 queue | stack | sk_storage | struct_ops | ringbuf | inode_storage |
          task_storage }
       OPTIONS := { {-j|--json} [{-p|--pretty}] | {-f|--bpffs} |
                {-m|--mapcompat} | {-n|--nomount} }


text:
Q: BETWEEN and DATE_ADD is not working in my case I have sales in my database going back 9 days and this query is not returning anything why?
SELECT * FROM `sales`
WHERE date BETWEEN CURRENT_DATE AND
(DATE_ADD(CURRENT_DATE, INTERVAL -10 DAY))

A: You have to switch the parameter. From must be lower than to.
SELECT * FROM `sales`
WHERE date BETWEEN
(DATE_ADD(CURRENT_DATE, INTERVAL -10 DAY)) AND CURRENT_DATE

Your current query would return records greater than now or earlier than 10 days ago, thus excluding the very range you intended to target.
For more Informations see the documentation.

If expr is greater than or equal to min and expr is less than or equal
  to max, BETWEEN returns 1, otherwise it returns 0. This is equivalent
  to the expression (min <= expr AND expr <= max) if all the arguments
  are of the same type. Otherwise type conversion takes place according
  to the rules described in Section 12.2, "Type Conversion in Expression
  Evaluation", but applied to all the three arguments.


text:
Q: Unable to Enter zero after a decimal Point in Edit Text My edit text is not allowing to enter zero after the decimal point.
user should be allowed to enter input like "123.09" but as soon i entered decimal point zero is not allowed in edit text.
my edit view :
 <EditText
                android:id="@+id/getPrincipal_editText"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentStart="true"
                android:layout_alignParentTop="true"
                android:layout_marginLeft="5dp"
                android:layout_marginTop="15dp"
                android:ems="7"
                android:inputType="numberDecimal"
                android:text=""
                android:textColor="@color/Black"
                android:textCursorDrawable="@drawable/edittextstyle" />

my Text listeners :
EditText et =null;
et =  (EditText) getActivity().findViewById(R.id.getPrincipal_editText);
        df = new DecimalFormat("#,##,###.####");
        df.setDecimalSeparatorAlwaysShown(true);

        dfnd = new DecimalFormat("#,##,###");
        hasFractionalPart = false;
        et.addTextChangedListener(this);

 @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (s.toString().contains(String.valueOf(df.getDecimalFormatSymbols().getDecimalSeparator())))
        {
            hasFractionalPart = true;
        } else {
            hasFractionalPart = false;
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

        et.removeTextChangedListener(this);

        try {
            int inilen, endlen;
            inilen = et.getText().length();

            String v = s.toString().replace(String.valueOf(df.getDecimalFormatSymbols().getGroupingSeparator()), "");
            Number n = df.parse(v);
            int cp = et.getSelectionStart();
            if (hasFractionalPart) {

                et.setText(df.format(n));

            } else {

                et.setText(dfnd.format(n));
            }
            endlen = et.getText().length();
            int sel = (cp + (endlen - inilen));
            if (sel > 0 && sel <= et.getText().length()) {
                et.setSelection(sel);
            } else {
                // place cursor at the end?
                et.setSelection(et.getText().length() - 1);
            }
        } catch (NumberFormatException nfe) {
            // do nothing?
        } catch (ParseException e) {
            // do nothing?
        }

        et.addTextChangedListener(this);

    }


text:
Q: how does laravel eloquent model works? in db Seller table and this table have seller_id and i have column paid and i want to get that data using model so consider in controller i use
$seller = User::all();

in User Model
public function benefits(){
     return $this->belongsTo('App\Seller' , 'seller_id');
}

in view
@foreach($sellers as $key => $seller)
    <td>{{ $seller->benefits->paid}}<\td>
@endforeach

but problem is that i am unable to get value from column paid in seller table my result is null how this query will work?

A: *

*There is no $sellers variable in your code.

*$seller is a collection, not a single record.

*Eager load benefits relationship to avoid making too many queries.

$sellers = User::with('benefits')->all();

@foreach ($sellers as $seller)
    <td>{{ $seller->benefits->paid }}<\td>
@endforeach

If seller_id is a column in the Seller model's table, then the benefits relationship in the User model is either hasOne or hasMany
// User Model
public function benefits()
{
    return $this->hasOne('App\Seller', 'seller_id');
}

// Seller Model
public function user()
{
    return $this->belongsTo('App\User', 'seller_id');
}


text:
Q: SSL Handshake failure - HttpClient 4.1.2 I am trying to make an API call on a server but getting an SSL handshake failure. The library i am using is httpclient 4.1.2.
Here is the how i am creating the httpClient object
System.setProperty("https.protocols","TLSv1");
SSLContext sslContext = SSLContext.getInstance("TLSv1");
sslContext.init(null, null, null);

SSLSocketFactory sslSocketFactory = new SSLSocketFactory(sslContext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
Scheme httpsScheme = new Scheme("https", 443, sslSocketFactory);

SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(httpsScheme);

ClientConnectionManager cm = new SingleClientConnManager(schemeRegistry);

HttpClient httpClient = new DefaultHttpClient(cm);

Here are the SSL Handshake logs
trigger seeding of SecureRandom
done seeding SecureRandom
main, setSoTimeout(0) called
Allow unsafe renegotiation: false
Allow legacy hello messages: true
Is initial handshake: true
Is secure renegotiation: false
%% No cached client session
*** ClientHello, TLSv1
RandomCookie:  GMT: 1440191547 bytes = { 208, 238, 36, 204, 125, 170, 169, 142, 211, 115, 213, 236, 25, 69, 216, 182, 176, 189, 232, 38, 244, 13, 172, 17, 249, 254, 183, 21 }
Session ID:  {}
Cipher Suites: [SSL_RSA_WITH_RC4_128_MD5, SSL_RSA_WITH_RC4_128_SHA, TLS_RSA_WITH_AES_128_CBC_SHA, TLS_RSA_WITH_AES_256_CBC_SHA, TLS_DHE_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_RSA_WITH_AES_256_CBC_SHA, TLS_DHE_DSS_WITH_AES_128_CBC_SHA, TLS_DHE_DSS_WITH_AES_256_CBC_SHA, SSL_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA, SSL_RSA_WITH_DES_CBC_SHA, SSL_DHE_RSA_WITH_DES_CBC_SHA, SSL_DHE_DSS_WITH_DES_CBC_SHA, SSL_RSA_EXPORT_WITH_RC4_40_MD5, SSL_RSA_EXPORT_WITH_DES40_CBC_SHA, SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA, SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA, TLS_EMPTY_RENEGOTIATION_INFO_SCSV]
Compression Methods:  { 0 }
***
main, WRITE: TLSv1 Handshake, length = 81
main, WRITE: SSLv2 client hello message, length = 110
main, READ: TLSv1 Alert, length = 2
main, RECV TLSv1 ALERT:  fatal, handshake_failure
main, called closeSocket()
main, handling exception: javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure
main, IOException in getSession():  javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure
main, called close()
main, called closeInternal(true)
main, called close()
main, called closeInternal(true)
javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated

    at com.sun.net.ssl.internal.ssl.SSLSessionImpl.getPeerCertificates(SSLSessionImpl.java:352)
    at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:128)
    at org.apache.http.conn.ssl.SSLSocketFactory.connectSocket(SSLSocketFactory.java:397)
    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:148)
    at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:149)
    at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:121)
    at org.apache.http.impl.client.DefaultRequestDirector.tryConnect(DefaultRequestDirector.java:573)
    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:425)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:820)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:754)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:732)
    at com.waseem.stuff.HttpClientExample2.sendPost(HttpClientExample2.java:107)
    at com.waseem.stuff.HttpClientExample2.main(HttpClientExample2.java:29)

A: I was having the same issue using Rest Assured, and updating my HTTP Client library to 4.5.3 fixed it.


text:
Q: Is this the right way to think about relative probability? I have two groups of people, let's call them bowlers. One group uses a heavy ball and the other group uses a light ball.
Everyone rolls just once. Of the people who use the light ball, 34% roll a gutterball. Of the people who use the dark ball, 39% roll a gutterball.
Is it fair to say that people who use the dark ball are 13% more likely to roll a gutterball?


text:
Q: Can not show images on harbor I installed harbor through helm-harbor which version is v1.1.0.
My problem is that I can docker login succeed on terminal, and successfully docker push images, but after that there is no image showing in harbor web page, there is no any image there.
I checked the log of the container registry of pod harbor-registry which constantly generate the following information, I don't know if this has some relationship with my problem.
10.244.3.1 - - [05/Jul/2019:16:52:08 +0000] "GET / HTTP/1.1" 200 0 "" "kube-probe/1.12"
10.244.3.1 - - [05/Jul/2019:16:52:12 +0000] "GET / HTTP/1.1" 200 0 "" "kube-probe/1.12"
time="2019-07-05T16:52:15.959957799Z" level=info msg="response completed" go.version=go1.11.8 http.request.host="telling-hydra-harbor-registry:5000" http.request.id=4e553265-0dcc-4e8d-86fe-80f76bfc1a1d http.request.method=GET http.request.remoteaddr="10.244.3.193:57186" http.request.uri="/v2" http.request.useragent="Go-http-client/1.1" http.response.contenttype="text/html; charset=utf-8" http.response.duration="276.091µs" http.response.status=301 http.response.written=39
10.244.3.193 - - [05/Jul/2019:16:52:15 +0000] "GET /v2 HTTP/1.1" 301 39 "" "Go-http-client/1.1"
time="2019-07-05T16:52:15.963158432Z" level=debug msg="authorizing request" go.version=go1.11.8 http.request.host="telling-hydra-harbor-registry:5000" http.request.id=3e6c1e3e-f26a-411f-bd53-05a5bedfe562 http.request.method=GET http.request.referer="http://telling-hydra-harbor-registry:5000/v2" http.request.remoteaddr="10.244.3.193:57186" http.request.uri="/v2/" http.request.useragent="Go-http-client/1.1"
10.244.3.193 - - [05/Jul/2019:16:52:15 +0000] "GET /v2/ HTTP/1.1" 401 87 "http://telling-hydra-harbor-registry:5000/v2" "Go-http-client/1.1"
time="2019-07-05T16:52:15.963272246Z" level=warning msg="error authorizing context: authorization token required" go.version=go1.11.8 http.request.host="telling-hydra-harbor-registry:5000" http.request.id=3e6c1e3e-f26a-411f-bd53-05a5bedfe562 http.request.method=GET http.request.referer="http://telling-hydra-harbor-registry:5000/v2" http.request.remoteaddr="10.244.3.193:57186" http.request.uri="/v2/" http.request.useragent="Go-http-client/1.1"

Is there any one can help me? Thanks.

A: Creating /etc/docker/daemon.json file and adding the below content and then doing a docker restart on CentOS 7 and  ubuntu resolved the issue.
{
    "insecure-registries" : [ "Docker_registery_IP:5000" ]
}


text:
Q: AWS Redshift alter append command not working for inserting data I have to insert records into Redshift table on a periodic basis.
So I chose the strategy where I will copy s3 data into stage table and then append the stage table data into actual table using alter append command.
In my case.
Stage table - URL_DATA_TEMP
Actual Table - URL_METADATA
now both tables I created using the same command and only changing the table name.
ex:
CREATE TABLE _360_model.URL_METADATA
(
URL VARCHAR(8000),
URL_MD5 VARCHAR(300),
INDEX VARCHAR(200),
ASSET_TYPE VARCHAR(200)
);

CREATE TABLE _360_model.URL_DATA_TEMP
(
URL VARCHAR(8000),
URL_MD5 VARCHAR(300),
INDEX VARCHAR(200),
ASSET_TYPE VARCHAR(200)
);

Still when I try to use following append command, it complains.
alter table _360_model.URL_METADATA append from _360_model.URL_DATA_TEMP;

error:  Columns don't match.
code:      8001
context:   Column "asset_type" has different attributes in the source table
and the target table. Columns with the same name must have the same
attributes in both tables.

I am not able to understand when I used almost same command to create table, how can column structure can be different.

A: This may be from column compression differences. On the copy command, are you using the option "COMPUPDATE ON" as shown below? If so, it is likely your staging table's column compression options are different than your target table.
copy <table name> from 's3://<data location>'
CREDENTIALS <creds>
region <region>
GZIP
CSV
IGNOREHEADER 1
TIMEFORMAT 'auto' manifest
COMPUPDATE ON;

I ran into a similar issue and did the following.
1) Load data with a copy command and turn COMPUPDATE ON
See: http://docs.aws.amazon.com/redshift/latest/dg/copy-parameters-data-load.html#copy-compupdate
2) Afer the load is complete, use the query below to see the automatic compression applied.
select "column", type, encoding, distkey, sortkey
from pg_table_def where tablename = '<table name>';

See: http://docs.aws.amazon.com/redshift/latest/dg/t_Compressing_data_on_disk.html
3) Recreate your target table using the same compression as the staging table.
create table <target table name> (
    <column name> <type> encode <encoding>,
    ...
)

See: http://docs.aws.amazon.com/redshift/latest/dg/r_CREATE_TABLE_NEW.html
Other table attributes such as sortkey will need to match in both your staging and target tables.

A: I'm not able to recreate the issue with the SQL you've provided (using psql).
Try running your SQL with psql to see if your tool is altering the submitted SQL in some way.

A: This may be due to the different compression types of the target and staging table. Sometimes due to the different sortkeys in the target and staging table it happens. Steps to resolve it:

*

*In redshift: show table 'target table name'. This will generate the DDL statement of the target table name

*Drop the staging table :    drop table  'staging table name'

*Recreate the staging table using the DDL command generated from the 1 command, just replace the table name with the staging table name


text:
Q: Python min() function returns incorrect results I Am writing a python program that auto adjusts it's learning rate to find the best in the least number of iterations.
from random import randint, seed
from matplotlib.pyplot import plot, show, xlabel, ylabel

#NumIN must be a multiple of ExpOut
#Changing seed may cause the Best Evolution Rate to be drastically different at Low NumIn and ExpOut values
seed(572649)
TestEvoRateUpTo = 100
EvolutionRate = 0 #Dont change
numIN = 15
ExpOut = 12180
Scores = []
EvoScores = []
Iteration = 1 #Dont change

#define a class called AI. It contains an number
class AI:
  def __init__(self, eq):
    self.eq = eq

for x in range(TestEvoRateUpTo - 1):
  #Increate Evolution Rate
  EvolutionRate = EvolutionRate + 1

  #give each bot a random number
  Bot0 = AI(randint(1, 100))
  Bot1 = AI(randint(1, 100))
  Bot2 = AI(randint(1, 100))
  Bot3 = AI(randint(1, 100))
  Bot4 = AI(randint(1, 100))

  while True:
    #Test Each Bot's abilities
    Bot0Score = abs(ExpOut - (numIN * Bot0.eq))
    Bot1Score = abs(ExpOut - (numIN * Bot1.eq))
    Bot2Score = abs(ExpOut - (numIN * Bot2.eq))
    Bot3Score = abs(ExpOut - (numIN * Bot3.eq))
    Bot4Score = abs(ExpOut - (numIN * Bot4.eq))

    # Put scores in a list from Bot1 to Bot5
    Scores.append(Bot0Score)
    Scores.append(Bot1Score)
    Scores.append(Bot2Score)
    Scores.append(Bot3Score)
    Scores.append(Bot4Score)

    #get the min of these Scores (Lower is better)
    Biggest = min(Scores)
    Winner = Scores.index(Biggest)
    #give each bot the base of the winner and mutate it
    if(Winner == 0):
      Bot0 = AI(Bot0.eq + randint(-EvolutionRate, EvolutionRate))
      Bot1 = AI(Bot0.eq + randint(-EvolutionRate, EvolutionRate))
      Bot2 = AI(Bot0.eq + randint(-EvolutionRate, EvolutionRate))
      Bot3 = AI(Bot0.eq + randint(-EvolutionRate, EvolutionRate))
      Bot4 = AI(Bot0.eq + randint(-EvolutionRate, EvolutionRate))
    elif(Winner == 1):
      Bot0 = AI(Bot1.eq + randint(-EvolutionRate, EvolutionRate))
      Bot1 = AI(Bot1.eq + randint(-EvolutionRate, EvolutionRate))
      Bot2 = AI(Bot1.eq + randint(-EvolutionRate, EvolutionRate))
      Bot3 = AI(Bot1.eq + randint(-EvolutionRate, EvolutionRate))
      Bot4 = AI(Bot1.eq + randint(-EvolutionRate, EvolutionRate))
    elif(Winner == 2):
      Bot0 = AI(Bot2.eq + randint(-EvolutionRate, EvolutionRate))
      Bot1 = AI(Bot2.eq + randint(-EvolutionRate, EvolutionRate))
      Bot2 = AI(Bot2.eq + randint(-EvolutionRate, EvolutionRate))
      Bot3 = AI(Bot2.eq + randint(-EvolutionRate, EvolutionRate))
      Bot4 = AI(Bot2.eq + randint(-EvolutionRate, EvolutionRate))
    elif(Winner == 3):
      Bot0 = AI(Bot3.eq + randint(-EvolutionRate, EvolutionRate))
      Bot1 = AI(Bot3.eq + randint(-EvolutionRate, EvolutionRate))
      Bot2 = AI(Bot3.eq + randint(-EvolutionRate, EvolutionRate))
      Bot3 = AI(Bot3.eq + randint(-EvolutionRate, EvolutionRate))
      Bot4 = AI(Bot3.eq + randint(-EvolutionRate, EvolutionRate))
    elif(Winner == 4):
      Bot0 = AI(Bot4.eq + randint(-EvolutionRate, EvolutionRate))
      Bot1 = AI(Bot4.eq + randint(-EvolutionRate, EvolutionRate))
      Bot2 = AI(Bot4.eq + randint(-EvolutionRate, EvolutionRate))
      Bot3 = AI(Bot4.eq + randint(-EvolutionRate, EvolutionRate))
      Bot4 = AI(Bot4.eq + randint(-EvolutionRate, EvolutionRate))

    #Reset some values
    Scores = []
    Iteration = Iteration + 1
    if(Biggest == 0):
      EvoScores.append(Iteration)
      print(f"Evolution Rate of {len(EvoScores) + 1} had {Iteration} Iterations")
      Iteration = 1
      break

#Find the best Evolution Rate
BestEvoRate = min(EvoScores)
print(f"Best Evolution Rate was {EvoScores.index(BestEvoRate) + 1}")

#plot results
plot(EvoScores)
xlabel("Evolution Rate")
ylabel("Iterations")
show()

While my program says the best Learning rate was 89, the program also says that other Learning rate values (Like 90) could get to the goal in less iterations.
I expected the program to return the Learnign rate that resulted in the lowest number of iterations. I have look over my program multiple times, and i cannot seem to find the issue. I assume it might be a problem with this part of the code:
#Find the best Evolution Rate
BestEvoRate = min(EvoScores)
print(f"Best Evolution Rate was {EvoScores.index(BestEvoRate) + 1}")


text:
Q: Avoiding control paint spam (during the heavy update of treeview, listview controls) I've got an application which adds 10+ items to a treelist every second. This causing the control and UI to unresponsive and sometimes can't even paint it enough, also consumes a lot of CPU.
These new items coming from different threads so I can't use .BeginUpdate() unless I do some sort of local caching.
If I do BeginUpdate() and EndUpdate in fixed intervals then control stuck unpainted/blank between the intervals.
What's the best solution against this problem? Caching sounds stupid to me because in theory control got it's own caching anyway, so there should be a way for me to tell the control do not update but leave the control in the last painted state instead of something blank.

A: Since the new Items come from different threads you already need Control.Invoke , you might as well batch that. So push your items in a Queue, and on the main thread poll that queue (using a Timer probably) and add a batch of Items in a BeginUpdate/EndUpdate block. The Timer interval will let you configure responsiveness. You will have to lock the queue but you no longer need Invoke.

A: If you have multiple threads suppling the additions then they must be marshalled onto the control's owning thread anyway.
As such it is simple to implement a single batching mechanism post marshalling.
The control's caching is unlikely to be designed around your specific requirements (this is not normal behaviour for widget toolkits of this kind) so it is likely that you can do better with a cache specific to your load and responsiveness needs.

A: It looks as though your issue is the responsiveness of the application rather than anything else.  10 items a second does not sound very intensive (unless they are very heavy items) therefore they shouldnt  cause a problem.
I would guess that adding Application.DoEvents would make your application respond as you expect.  It seems the issue is with processing windows messages in a timely fasion rather than the load that is being done.
You will need to invoke to the main thread to add the items to the control therefore there should be no problem with calling a DoEvents a few times a second as you go through.  This wont be a massively efficient solution but I think it will address your lack of responsivness.


text:
Q: How to expose a gRPC service both as Protobuf and JSON Can we expose gRPC service (in JAVA) with both encoding (Protobuf and JSON)? Like we can do in HTTP+REST, where server creates and set response header basis client Content-Type : (application/json or application/xml or application/proto).

A: gRPC supports streaming, which cannot be implemented in HTTP/1. It is not possible to make a gRPC service available as classic HTTP+REST.
Twirp should be pretty close to what you want. It uses plain HTTP/1, is generated from service definitions in .proto files. It only supports unary methods.
https://twitchtv.github.io/twirp/docs/intro.html
gRPC-web is an alternative if you are looking to consume your service with a web browser. It supports unary and server streaming methods. Most importantly, you can use the envoy proxy to make your existing gRPC services available as gRPC-web.


text:
Q: Constraint of a variable with an expression in nonlinear model fitting - independent variable constraint? I am attempting to fit a set of experimental binding data:
data={{0.1, 0.127}, {0.142, 0.131}, {0.203, 0.163}, {0.289, 0.303}, {0.411,0.45}, {0.585, 0.648}, {0.833, 0.7}, {1.19, 1.02}, {1.69,1.1}, {2.4, 1.27}, {3.42, 1.44}, {4.87, 1.62}, {6.93, 1.69}, {9.87,1.85}, {14, 1.82}, {20, 1.87}}

with a nonlinear least squares model. The data is organized as a list of of lists with $(x_T,<x>) $ experimental measurements (in $\mu M$) where $x_T$ is the total ligand present and $<x>$ is the moles of ligand bound per moles of total protein.
I have tried searching through some previous forum posts as well as the wolfram documentation
but I am still having a little bit of trouble defining my model. Here is the model I would like to fit:
$$<x>\:= \frac{2k_1 x+2k_1 k_2x^2}{1+2k_1x+k_1k_2x^2} $$
where
$$x=\:x_T\: -<x> \times \: concentration$$ is the expression for x in the model. Is it possible to set it up such that x is represented implicitly in the model? My goal is to obtain parameter estimations for $k_1$ and $k_2$.
Here is the nonlinear model I currently have set up:
concentration = 1
indNonIdenticalModel := (2 k1 x + 2 k1 k2 x^2)/(1 + 2 k1 x + k1 k2 x^2)
nlm = NonlinearModelFit[data, indNonIdenticalModel, {k1, k2}, {x}]

This evaluates, but I'm not convinced my implementation is doing what I intend / expect it to be doing because I haven't supplied any information about the constraint for x. I also tried to use the syntax {model,{constraints}} but I'm not specifying conditional expressions such as x>5 so I didn't understand how I could implicitly define a constraint on x that is derived from the experimental data.
indNonIdenticalModel := (2 k1 x + 2 k1 k2 x^2)/(1 + 2 k1 x + k1 k2 x^2)
nlm = NonlinearModelFit[data, {indNonIdenticalModel, {x=}}{k1, k2}, {x}]

I apologize if I'm missing something painfully obvious here. I am relatively new to mathematica.
Heres an image of the agreement I have. It looks quite good but the constants are different than I expected when compared to another software (around k1=2.210^7 and k2= 8.710^5 M)
EDIT:
I realize now why the models are getting vastly different parameter estimations, but I'm unsure how to resolve the issue mathematica is generating. Attached are some pictures. I think what I need to do is mandate the fit be valid across the independent variable range (lets say 0<x<20), but I tried to use the form from the documentation and couldn't constrain x.
nlmTest = NonlinearModelFit[data, {indNonIdenticalModel, {0 < x < 20}}, {n, k}, x]

Here is the equation for the plot:
keyPlot =  Show[Plot[(44.` x + 38.279999999999994`x^2)/(1+44.`x+19.139999999999997` x^2), {x, 0, 20},PlotRange -> All]]


text:
Q: Find the 10 most frequently occurring words with morphology Please tell me how to solve this problem better.
I have the text of the Russian and I want to find the 10 most common words with morphology.
Maybe there is any open source libraries to solve this issue in python?

A: You can use one of Python morphology analyzers for Russian to normalize the word:

*

*https://github.com/kmike/pymorphy2

*https://github.com/kmike/pymorphy

*https://github.com/irokez/Pyrus
There is also a Porter stemmer for Russian in https://github.com/nltk/nltk. Also, you could employ http://company.yandex.ru/technologies/mystem/ from a command line.
I'd recommend pymorphy2 for your task, but I'm a bit biased :)

A: PyStemmer and NLTK are the two obvious libraries here.