text:
Q: copy the value with last non zero value sql I have data as below, data is order by date.
I need to copy the last non zero value when there is zero. For example 15th August the count is Zero so the count should show 20 as the last count is 20 (on 15th August), same should happen for 16th - 19 August. Now for 21st - 22nd the count should be 14. If no previous value is available let it be zero in case of 14th Aug.
I have also added the result at last.
Date    Count
14-Aug-15   0
15-Aug-15   20
16-Aug-15   0
17-Aug-15   0
18-Aug-15   0
19-Aug-15   0
20-Aug-15   14
21-Aug-15   0
22-Aug-15   0
23-Aug-15   10
24-Aug-15   0
25-Aug-15   0
26-Aug-15   0
27-Aug-15   0
28-Aug-15   11
29-Aug-15   0
30-Aug-15   0
31-Aug-15   0
01-Sep-15   0
02-Sep-15   0
03-Sep-15   0
04-Sep-15   0

Result
Date    Count
14-Aug-15   0
15-Aug-15   20
16-Aug-15   20
17-Aug-15   20
18-Aug-15   20
19-Aug-15   20
20-Aug-15   14
21-Aug-15   14
22-Aug-15   14
23-Aug-15   10
24-Aug-15   10
25-Aug-15   10
26-Aug-15   10
27-Aug-15   10
28-Aug-15   11
29-Aug-15   11
30-Aug-15   11
31-Aug-15   11
01-Sep-15   11
02-Sep-15   11
03-Sep-15   11
04-Sep-15   11

A: A simple subquery can get you your result set as desired (with the last current or previous non-zero value).
select [Date],
       isnull((select top 1 [Previous].[Count]
               from [Table] as [Previous]
               where [Previous].[Count] <> 0 and
                     [Previous].[Date] <= [Table].[Date] and
                     [Previous].[Id] = [Table].[Id]
               order by [Previous].[Date] desc),
              0) as [Count]
from [Table]

To update values is very similar :
update [Table] set [Count]= isnull((select top 1 [Previous].[Count]
                                    from [Table] as [Previous]
                                    where [Previous].[Count] <> 0 and
                                          [Previous].[Date] <= [Table].[Date] and
                                          [Previous].[Id] = [Table].[Id]
                                    order by [Previous].[Date] desc),
                                   0) as [Count]

A: You may use a variable to achieve it
CREATE TABLE tab
(
  n VARCHAR(10),
  d DATE,
  c INT
);

INSERT INTO tab VALUES ('A', '14-Aug-15', 0);
INSERT INTO tab VALUES ('B', '15-Aug-15', 20);
INSERT INTO tab VALUES ('C', '16-Aug-15', 0);
INSERT INTO tab VALUES ('A', '17-Aug-15', 0);
INSERT INTO tab VALUES ('B', '18-Aug-15', 0);
INSERT INTO tab VALUES ('C', '19-Aug-15', 0);
INSERT INTO tab VALUES ('D', '20-Aug-15', 14);
INSERT INTO tab VALUES ('A', '21-Aug-15', 0);

-- for each n value perform the following update
DECLARE @last INT=0;
UPDATE tab
SET @last=c=CASE WHEN c=0 THEN @last ELSE c END
WHERE n = 'B';

A: I think below code should work for you -
Create table #Source  (
id  char(1) ,
date smalldatetime,
value tinyint)
go

insert into  #Source
 select 'A' ,'14-Aug-15' ,  0
union all  select 'B' , '15-Aug-15' ,  20
union all  select 'B'  , '16-Aug-15'  , 0
union all  select 'B'  , '17-Aug-15'  , 0
union all  select 'B'  , '18-Aug-15'  , 0
union all  select 'A' , '19-Aug-15'  , 0
union all  select 'A' , '20-Aug-15'  , 14
union all  select 'A' , '21-Aug-15'  , 0
union all  select 'B' , '22-Aug-15'  , 0
union all  select 'B', '23-Aug-15'  , 10
union all  select 'B' , '24-Aug-15'  , 0
union all  select 'B' , '25-Aug-15'  , 0
union all  select 'B' , '26-Aug-15'  , 0
union all  select 'C' , '27-Aug-15'  , 0
union all  select 'C' , '28-Aug-15'  , 11
union all  select 'C' , '29-Aug-15'  , 0
union all  select 'C' , '30-Aug-15'  , 0
union all  select 'C' , '31-Aug-15'  , 0
union all  select 'C' , '01-Sep-15'  , 0
union all  select 'B' , '02-Sep-15'  , 0
union all  select 'B' , '03-Sep-15'  , 0
union all  select 'A' , '04-Sep-15'  , 0

select t1.* , t2.value  New_value  ,  RANK() over ( partition by t1.date
order by  t2.date desc    )  as RANK
into #dest
from #Source t1
left join #Source t2 on t1.id = t2.id and  t1.date >= t2.date
and  t1.value=0 and t2.value <>0
order by 2

update s
set s.Value =  d.New_value
from  #Source s join #dest d
on s.id = d.id
and s.date = d.date
and d.RANK = 1 and  d.New_value   is not null


text:
Q: How to take inputs for 2 Dimensional dynamic array in Java? I am writing a code where inputs will be taken from the user and stored in a 2-Dimensional dynamic array. We know the no. of rows of the array. But the number of columns of the array is dynamic.
The input will be in the form as shown below:

3
sghjhlklj
ghgh
ytyhuj

Since 3 is entered first, there would be three subsequent strings which have to be stored in an array.
Following is the code snippet that I have written. But it shows array index out of bounds exception.
import java.util.Arrays;
import java.util.Scanner;

class Main
{
    // Read a String from the standard input using Scanner
    public static void main(String[] args)
    {

        Scanner in = new Scanner(System.in);

        Integer no = in.nextInt();
        System.out.println("You entered string "+no);
        int z = 0,y=0 ;

        char[][] arr = new char[no][];

        for(z=0 ; z<no ; z++)
        {
            String s = in.nextLine();
            String[] arrOfStr = s.split("");
            for( y =0 ; y<arrOfStr.length ; y++)
            {
                arr[z][y]=arrOfStr[y].charAt(0);

            }

        }

        in.close();
    }
}

A: You have 3 issues with your code:

*

*You never initialize the inner arrays. Do it with arr[z] = new char[s.length()];.

*The way you define arrOfStr. You split the string by the blank sub-string. Instead just use s use charAt like this:
arr[z][y] = s.charAt(y);

*As the comments suggested, there is the issue with nextInt that does not take into account the \n (enter) char.
So use int no=Integer.parseInt(in.nextLine());, instead of using nextInt.

The final code should look like this:
for(z=0 ; z<no ; z++)
{
    String s = in.nextLine();
    arr[z] = new char[s.length()];
    for( y =0 ; y<s.length() ; y++)
    {
        arr[z][y]=s.charAt(y);
    }
}

A: In java 2D array is initially 1D array of arrays. This is not C++:

*

*You have to know the number of rows only;

*Each sub-array (a line) could have a different length.

String[][] matrix = new String[3][]; // declare an 2D array with 3 rows and not define column length
matrix[0] = new String[5]; // 1st line has 5 columns; matrix[0][4] is the last column of 1st row
matrix[1] = new String[10]; // 2nd line has 10 columns; matrix[1][9] is the last column of 2nd row
// matrix[2] == null -> true // 3rd line is not initialized

String[][] matrix = new String[2][2]; // declare 2D array and initialize all rows with 1D sub-array with 2 columns (i.e. we have a square).

A: Try this code:
The first problem was you did not initalize the inner array. Furthermore you used both nextInt() and nextLine(). The nextInt() method does not take into account your  \n (newLine symbol) . So the nextLine() method will directly consume it and does not take into account your subsequent input.
public static void main(String[] args) {
        try (Scanner in = new Scanner(System.in)) {
            Integer no;
            do { // this is some flaky code but it works for this purpose
                try {
                    no = Integer.parseInt(in.nextLine());
                    break;
                } catch (Exception e) {
                    System.out.println("please enter only a numeric value");
                }
            } while (true);

            System.out.println("You entered string " + no);
            int z = 0, y = 0;

            char[][] arr = new char[no][];

            for (z = 0; z < no; z++) {
                String s = in.nextLine();
                String[] arrOfStr = s.split("");
                arr[z] = new char[arrOfStr.length];
                for (y = 0; y < arrOfStr.length; y++) {
                    System.out.println();
                    arr[z][y] = arrOfStr[y].charAt(0);
                }
            }
            for (char[] charArr : arr) {
                for (char c : charArr) {
                    System.out.println(c);
                }
            }
        }
    }

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to upload files in postman which is a property in an object of array I am developing a REST API where I need to accept an array of objects. I have made a search and know how to upload a file with other parameters. Also I can send multiple files by adding them to body. But I need to send them as a property of an object and the API endpoint accepts an array of this object.
Let me explain it with an example
public class StaffInfo
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public IFormFile Photo { get; set; }
}

[HttpPost]
[Route("api/staff/create")]
public void AddNewStaff(StaffInfo[] newStaff)
{
    :
    :
}

I want to test this endpoint and can't figure out how to send data with PostMan.
Regards.

A: In Postman, you can pass the array of input as form-data. The format, for example passing the FirstName, would be: newStaff[0].firstName. For the Photo property, you can select the dropdown for the Key in Postman and change the type to File to set the file. Here's what it should look like in Postman:

When sending this, you can see the photo passed in the array in Visual Studio:


text:
Q: Chrome window.localStorage vs. chrome.storage.local in dependencies I am developing a Chrome app that uses some NPM's.  When a dependency in my app uses window.localStoarge is there a way that I can map that to chrome.storage.local?
I want to override window.localstorage with something that works with chrome.storage.local instead.  This way I do not have to replace code in dependencies that are using local storage.
Is there an npm or something that can do this?

A: First problem is that chrome.storage APIs are asynchronous and localStorage is sync. It is theoretically possible to create localStorage mock backed by the chrome.storage, but it will break in many cases.
Second problem is that chrome.storage operates on objects, when localStorage only allows strings. So if you'll have some kind of code which will rely on localStorage mode, you will have only store strings in chrome.storage.local, otherwise you will have very weird bugs.
Last problem is that you can't reassign window.localStorage variable in chrome apps, so the only way is to wrap the code into self executing closure, and provide window and localStorage mocks as closure variables, e.g:
(function(window,localStorage){
    //some code relying on localStorage here
})(windowObjectMock,windowObjectMock.localStorage);

It is easier and more error-prone to rewrite the external code to use chrome.storage.local rather than trying to provide localStorage implementation backed by chrome.storage.local.


text:
Q: Webapp undeployment memory leak when using OkHttp, false alarm or not? OkHttp internally creates threads for the connection pool and for some kind of watchdog. I've seen multiple people struggling with this when shutting down an application using this library. The authors itself do not seem willing to address it (https://github.com/square/okhttp/issues/2482, "marginal benefit"). Specifically, Tomcat complains about memory leaks, since threads are left behind. It looks like these are cleaned up eventually, sometimes after a fairly long delay. So, my question is: is there actually a memory leak because of this issue? Eventually the threads are going away, so this should mean that all of it can be garbage collected. Correct?

A: I'm one of those OkHttp authors that doesn't like Tomcat code unloading. We're shipping our own concurrency abstraction in the next minor release; details here. This might shorten the 60s delay between closing your last response and the last thread exiting.
You shouldn't do code unloading in modern programs. Tomcat came from an age where the JVM was the long-lived container; today that's Kubernetes or other cluster orchestration tech. Tomcat's code unloading strategy forces you to jump through awkward management hoops. If you are fighting class loaders or security managers you are wasting time on a made up problem.


text:
Q: Flutter How can I get progress status of uploading file to google drive by using google drive api? I am using google_apis v3 to upload a file to drive. How can I get the progress percentage of uploading status through the Google Drive API library? And also how can I cancel the uploading file?
The sample source code is as below.
  Future<File> uploadFile(
      GoogleAuthClient googleAuthClient, FileUpload fileUpload) async {
    final DriveApi driveApi = driveDataProvider.getDriveApi(googleAuthClient);

    final Stream<List<int>> mediaStream =
        Future.value(fileUpload.data).asStream().asBroadcastStream();

    Media media = Media(mediaStream, fileUpload.size);

    File createdFile = await driveApi.files.create(fileUpload.file,
        uploadMedia: media, uploadOptions:  UploadOptions.resumable;);

    return createdFile;
  }

A: Try something like this.

int byteCount = 0;
Stream<List<int>> mediaStream = file.openRead().transform(
   StreamTransformer.fromHandlers(handleData: (data, sink) {
        byteCount += data.length;
        //add a callback function here.
        // callback(byteCount);
        sink.add(data);
      }, handleError: (error, stackTrace, sink) {
        //Handle error
      }, handleDone: (sink) {
        sink.close();
      },
   ),
);


text:
Q: Why shouldn't you use an svg file as a website? I'm helping some people without much coding experience make websites using Inkscape. They are creating elements and using small bits of Javascript to animate interactions between them on mouse clicks. So far, they have been saving these as .svg files and opening them in their browsers to test them. They are now at the point where they want to put them on the web. I did some tests with GitHub pages, and it looks like if you upload these SVG files you can interact with them just like you could if you opened them in a browser locally.
Is there anything wrong with putting them on the web in this way? If I were doing it myself, I would at least put the SVG image in an html page, as this would provide much more flexibility. However, in this case, the goal is to keep everything as simple as possible. So if I can avoid teaching them HTML right now, so much the better. But the fact that I've never encountered a website that was literally just an svg file makes me worry that there's a serious problem other than the lack of flexibility in making improvements to the website. Does anyone know of one?

A: No. There is nothing wrong with doing this as long as they are happy with the functionality available in SVGs.
Obviously if they need something like form fields, or formatted text, those things are going to require more effort to achieve than if they were using an SVG embedded in an HTML page.


text:
Q: Declare Two Dimensional Double Array Inside Structure How can I declare a two dimensional double array inside the structure?
public struct PROBABILTY_SETUP
{
    double[,] probablity[2,9613];
}

The above code NOT WORKING...

A: public struct PROBABILTY_SETUP
    {
        double[,] probablity;

        public PROBABILTY_SETUP(double [,] probability)
        {
            this.probablity = probability;
        }
    }

You'll have to call the constructor with the array you require:
PROBABILITY_SETUP mySetup = new PROBABILITY_SETUP(new double[2, 9613]);

A: Because you're in a struct, you'd have to make it static, as you can't have an initializer for a non-static struct member (another option is use a constructor however).
If it was a class however, the below would work without the static keyword.
Try this:
public struct PROBABILITY_SETUP
{
    static double[,] probablity = new double[2, 9613];
}

If you require more than one however, consider using a constructor


text:
Q: How to get column names in awk? I have a data file in the following format:
Program1, Program2, Program3, Program4
0,        1,        1,        0
1,        1,        1,        0

Columns are program names, and rows are features of programs. I need to write an awk loop that will go through every row, check if a value is equal to one, and then return the column names and put them into a "results.csv" file. The desired output should be this:
Program2, Program3
Program1, Program2, Program3

I was trying this code, but it wouldn't work:
awk -F, '{for(i=1; i<=NF; i++) if ($i==1) {FNR==1 print$i>>results}; }'

Help would be very much appreciated!

A: awk -F', *' '
NR==1 {for(i=1;i<=NF;i++) h[i]=$i; next}
{
    sep="";
    for(x=1;x<=NF;x++) {
        if($x) {
            printf "%s%s", sep, h[x];
            sep=", ";
        }
    }
    print ""
}' file

outputs:
Program2, Program3
Program1, Program2, Program3

A: $ cat tst.awk
BEGIN { FS=", *" }
NR==1 { split($0,a); next }
{
    out = ""
    for (i=1; i<=NF; i++)
         out = out ($i ? (out?", ":"") a[i] : "")
    print out
}

$ awk -f tst.awk file
Program2, Program3
Program1, Program2, Program3

A: My take on things is more verbose, but should handle the trailing comma. Not really a one-liner, though.
BEGIN {
    # Formatting for the input and output files.
    FS = ", *"
    OFS = ", "
}

FNR == 1 {
    # First line in the file
    # Read the headers into a list for later use.
    for (i = 1; i <= NF; i++) {
        headers[i] = $i
    }
}

FNR > 1 {
    # Print the header for each column containing a 1.
    stop = 0
    for (i = 1; i <= NF; i++) {
        # Gather the results from this line.
        if ($i > 0) {
            stop += 1
            results[stop] = headers[i]
        }
    }
    if (stop > 0) {
        # If this input line had no results, the output line is blank
        for (i = 1; i <= stop; i++) {
            # Print the appropriate headers for this result.
            if (i < stop) {
                # Results other than the last
                printf("%s%s", results[i], OFS)
            } else {
                # The last result
                printf("%s", results[i])
            }
        }
    }
    printf("%s", ORS)
}

Save this as something like script.awk, and then run it as something like:
awk -f script.awk infile.txt > results


text:
Q: Camel 'OUT' message not populting from 'IN' in Processor Trying to figure out how to propagate the body from my IN message to my OUT in a processor.  See below.  Note that I'm using streamcaching and my original input is a stream.
public void process(Exchange exchange) throws Exception {

    log.debug("In msg:"  + exchange.getIn().getBody(String.class));
    log.debug("Out msg:"  + exchange.getOut().getBody(String.class));

    exchange.setOut(exchange.getIn());

    log.debug("In msg:"  + exchange.getIn().getBody(String.class));
    log.debug("Out msg:"  + exchange.getOut().getBody(String.class));
}

The output is:
In msg: "My Payload"
Out msg: null
In msg: (empty string)
Out msg: (empty string)

What I expect is:
In msg: "My Payload"
Out msg: null
In msg: "My Payload"
Out msg: "My Payload"

Where's that empty string coming from?

A: Per Claus' comment which references the docs:

Consider using getIn() As shown above you most often need to alter the
  existing IN message, than creating a totally new OUT message. And
  therefore it's often easier just to adjust the IN message directly.

A: just try
 exchange.getOut().setBody(exchange.getIn().getBody());

instead of :
       exchange.setOut(exchange.getIn());

A:
I have tested the same code in local and its working as expected below.
In msg: "My Payload"
Out msg: null
In msg: "My Payload"
Out msg: "My Payload".
I am not getting any "empty string" in the console.


text:
Q: Try to connect to Informix database Cisco UCCX with unix ODBC - no success Try to use Informix driver to connect over ODBC to Cisco UCCX database. Install IBM informix SDK
Files of SDK /opt/IBM/Informix_Client-SDK
odbcinst -j
unixODBC 2.3.9
DRIVERS............: /etc/odbcinst.ini
SYSTEM DATA SOURCES: /etc/odbc.ini
FILE DATA SOURCES..: /etc/ODBCDataSources
USER DATA SOURCES..: /home/alexniko/.odbc.ini
SQLULEN Size.......: 8
SQLLEN Size........: 8
SQLSETPOSIROW Size.: 8

odbc.ini
[ODBC Data Sources]
uccx
uccx2

[uccx]
DRIVER={IBM INFORMIX ODBC DRIVER (64-bit)}
UID=uccxhruser
PWD=TrebuSHet{}123
DATABASE=db_cra
HOST=uccx-01.fccps.local
SERVER=uccx_01_uccx
SERVICE=1504
PROTOCOL=onsoctcp
CLIENT_LOCALE=en_US.UTF8
DB_LOCALE=en_US.UTF8

[uccx2]
DRIVER={IBM INFORMIX ODBC DRIVER 2 (64-bit)}
UID=uccxhruser
PWD=TrebuShet{}123
DATABASE=db_cra
HOST=uccx-02.fccps.local
SERVER=uccx_02_uccx
SERVICE=1504
PROTOCOL=onsoctcp
CLIENT_LOCALE=en_US.UTF8
DB_LOCALE=en_US.UTF8

odbcinst.ini
[IBM INFORMIX ODBC DRIVER (64-bit)]
Driver=/opt/IBM/Informix_Client-SDK/lib/cli/iclis09b.so
Description=IBM INFORMIX ODBC DRIVER
UID=uccxhruser
PWD=TrebuShet{}123
DATABASE=db_cra
HOST=uccx-01.fccps.local
SERVER=uccx_01_uccx
SERVICE=1504
PROTOCOL=onsoctcp
CLIENT_LOCALE=en_US.UTF8
DB_LOCALE=en_US.UTF8

[IBM INFORMIX ODBC DRIVER 2 (64-bit)]
Driver=/opt/IBM/Informix_Client-SDK/lib/cli/iclis09b.so
Description=IBM INFORMIX ODBC DRIVER
UID=uccxhruser
PWD=TrebuShet{}123
DATABASE=db_cra
HOST=uccx-02.fccps.local
SERVER=uccx_02_uccx
SERVICE=1504
PROTOCOL=onsoctcp
CLIENT_LOCALE=en_US.UTF8
DB_LOCALE=en_US.UTF8

ldd -v /opt/IBM/Informix_Client-SDK/lib/cli/iclis09b.so
Have no error
Connecttion string in python:
SERVICE=1504;PROTOCOL=onsoctcp;
CLIENT_LOCALE=en_US.UTF8;DB_LOCALE=en_US.UTF8;
DRIVER=IBM INFORMIX ODBC DRIVER (64-bit);
UID=uccxhruser;PWD=TrebuShet{}123;
DATABASE=db_cra;
HOST=uccx-01.fccps.local;
SERVER=uccx_01_uccx;

when I try to connect receive error:
Can't open lib '/opt/IBM/Informix_Client-SDK/lib/cli/iclis09b.so' : file not found (0) (SQLDriverConnect)")

Trying to check driver work with isql -v uccx - receive error
[IM002][unixODBC][Driver Manager]Data source name not found and no default driver specified
[ISQL]ERROR: Could not SQLConnect

what am I doing wrong?


text:
Q: is there a way to implement afterprint on jspdf after using its autoprint function? after the autoprint of jspdf, I want to call certain callback function when user prints or cancel, but I didn't find anyway to trigger afterprint on jspdf. Any help or suggestion would be appreciated, thank you.
I searched a lot on how to implement, even tried to exceute window.afterprint after the autoprint() function but it didn't work.


text:
Q: PIG script: reducer preempted to make room for pending map attempts I run multiples instances of the same PIG script with different parameters.
When the cluster is under heavy load, Map Reduce jobs logs show lots of reducers preempted, which takes times:
Reducer preempted to make room for pending map attempts Container killed
by the ApplicationMaster. Container killed on request. Exit code is 143
Container exited with a non-zero exit code 143

How to avoid such preemptions issue to minimize script execution time ?

A: Have a look at this link.
In short, you can use one of below commands
SET mapred.reduce.slowstart.completed.maps 1.00;
SET mapreduce.job.reduce.slowstart.completedmaps 1.00;

depending on your Hadoop version (latter on is for Hadoop 2.4.1+). It will start reducers once all mappers art done.


text:
Q: Pandas data frame creation inconsistencies I was creating a pandas dataframe from a python dictionary:
import numpy as np
import pandas as pd

obs_dict = {
            'pos':[[0,0],[10,10]],
            'vel':[[0,0],[0,0]],
            'mass':np.array([10000,10000])
           }

print pd.DataFrame(obs_dict)

Returns:
    mass       pos     vel
0  10000    [0, 0]  [0, 0]
1  10000  [10, 10]  [0, 0]

Notice that I have a 2d list as a items in the position ('pos') and velocity ('vel') column. However when I replace the 2d list with a 2d numpy array:
obs_dict = {
            'pos':np.array([[0,0],[10,10]]),
            'vel':np.array([[0,0],[0,0]]),
            'mass':np.array([10000,10000])
           }

I get an exception:
Exception: Data must be 1-dimensional

Unfortunately the data that I am using is contained within a numpy array and I don't want to convert it to a python list, is there any way to make this work?

A: In this code:
obs_dict = {
        'pos':[[0,0],[10,10]],
        'vel':[[0,0],[0,0]],
        'mass':np.array([10000,10000])
       }
print pd.DataFrame(obs_dict)`

you just got a dataframe with some object columns, try dtypes:
tt = pd.DataFrame(obs_dict)
tt.dtypes

shows:
mass     int64
pos     object
vel     object
dtype: object

I don't think this can be done.


text:
Q: Redirect calls to move/copy inside a batch file to own application I have a complicated batch file (under windows), let's call it BigMess.bat. It makes a lot of actions that I would like to monitor (especially the copy/move actions). I wouldn't like to touch the BigMess.bat.
Is it possible to redirect the calls to move/copy to my own application or another batch file?
I tried putting a move.bat file beside the BigMess.bat but it prefers the shell's move. Is it feasible without touching BigMess.bat?

A: if you run BigMess.bat with cmd.exe - no chance. as stated in The Windows NT Command Shell - Command Search Sequence:

If the command name [eg. move, copy] does not specify a path, the shell attempts to match the command name against the list of internal shell commands. If a match is found, the internal command executes.

it might be possible by using another shell. have a look at Take Command. it has a) cmd.exe compatibilty, and b) aliases. aliases are expanded before internal commands, so you could use one like
alias copy=C:\path\to\your\monitor\app

good luck!


text:
Q: xml not being validated without namespace prefix I have an xml that I wanted to verify against an xsd (with multiple schemas). The xml is as follows:
    <?xml version="1.0" encoding="utf-8"?>
<Interchange xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.abc.com.au/eApplications/Interchange/4.2">
  <InterchangeID>19768</InterchangeID>......</Interchange>

This xml didn't pass the validation and was giving me the following error:
The 'http://www.abc.com.au/eApplications/Interchange/4.2:Interchange' element is not declared.

When I introduced namespace with xml like this:
xmlns:ns="http://www.abc.com.au/eApplications/Interchange/4.2"

The error was gone, even I didn't introduce namespace prefix like  or  with any of the xml tags like:
<ns:Interchange>
   <ns:InterchangeID>...

My Findings:
The xml passes the validation if I either introduce :ns as a namespace or remove the line completely (after the parent Interchange tag) containing all the namespace references defined and keep it like that:
<Interchange>
  <InterchangeId>....

which is obviously not good.
Though I was able to fix this by the method explained above, I want to know the reason behind this as I couldn't find it after going through many links this, A Ten-Minute Guide to XML Namespaces and XML Namespaces Explained
Edit
I'm attaching the xsd here:
enter code here
<xs:schema xmlns:eapp="http://www.abc.com.au/eApps/iChange/4.2"
     elementFormDefault="qualified"
      targetNamespace="http://www.abc.com.au/eApps/iChange/4.2"
      xmlns:xs="http://www.w3.org/2001/XMLSchema">

      <xs:include schemaLocation="abc_datatypes.xsd"/>
      <xs:complexType name="abcType">
       <xs:sequence> </xs:sequence>
    </xs:complexType>
    </xs:schema>

  and the xml sample that passes validation is something like:

<soapenv:Envelope xmlns:soapenv="url"
    xmlns:orig="url/OServices" xmlns:ns="http://url/eApps/IChange/4.2">
  <soapenv:Header/>
  <soapenv:Body>
    <or:Originate>
       <!--Optional:-->
       <or:data>
       <ns:InID>2229</ns:InID>
       <ns:ReceiverID>CFS</ns:ReceiverID>
    </or:data>
   </or:Originate>
   </soapenv:Body>
 </soapenv:Envelope>

A: tl;dr

My Findings: The xml passes the validation if I either introduce :ns as a namespace or remove the line completely (after the parent
  Interchange tag) containing all the namespace references defined and
  keep it like that:
<Interchange>
  <InterchangeId>....

which is obviously not good.

It passes validation because both methods remove the default namespace.
Additional explanation...

This xml didn't pass the validation and was giving me the following
  error:
The 'http://www.abc.com.au/eApplications/Interchange/4.2:Interchange' element is not declared.

You didn't supply the schema so we can't verify, but what this is saying is that the Interchange element in the `` namespace does not exist in the schema.
When you declare a namespace without a prefix (xmlns="some uri") that becomes the default namespace for that context.
Since you say there aren't any validation errors when you remove xmlns="http://www.abc.com.au/eApplications/Interchange/4.2" completely, this leads me to believe that Interchange is not in a namespace in the schema.

When I introduced namespace with xml like this:
xmlns:ns="http://www.abc.com.au/eApplications/Interchange/4.2"

The error was gone,...

That's because you bound the namespace uri http://www.abc.com.au/eApplications/Interchange/4.2 to the prefix ns and now there is not a default namespace.


text:
Q: Comparing model to data to find the best fitting variable with scipy.optimize.minimize() [python] I need to compare a model to data to find the best fitting input. My data is surface reflectance of a body (= scattered light + thermal emission) at different wavelengths, and I simulate the reflectance by modeling the thermal emission part with Planck's law.  I need to find the temperature at which the modelled emission (and thus reflectance) fits the observations.
To do it, I define Planck's law as:
h = 6.626070e-34 # the Planck constant
c = 2.997924e+8  # the speed of light in vacuum
k = 1.380649e-23 # the Boltzmann constant

def planck(T):  # Planck's law for black body radiation
    intensity = (2*h*c**2) / ( ((wvleng*1e-9)**5) * (np.exp(h*c/((wvleng*1e-9)*k*T)) - 1.0) )
    thermal = 0.95 * (intensity*np.pi*D**2)/(SSI*1e9)
    return thermal

which returns the thermal emission of the body at different wavelengths.
Then, I defined the function that will qualify the fit (sum of squared difference between model and data at each wavelength):
def residuals(T): #
  S = scat_light + 0.95*planck(T) # simulated reflectance
  return np.sum((reflectance - S)**2)

where T is the black body temperature. Finally, I use optimize.minimize to find which T leads to the best fit between S (simulated reflectance) and data reflectance:
x0 = 345.0  # initial guess, temperature is the only variable
res = scipy.optimize.minimize(residuals, x0, method='SLSQP') # optimization
fitted_temperature = res.x

Here's the problem: it gives me a temperature way below (~220K) than what it should be (around 340K), not fitting the data at all. Does anyone have an idea about why it doesn't converge properly? Thanks in advance.

A: Ok I had several problems in my code:
1) In my planck function, my thermal emission relative to solar spectral irradiance is thermal = 0.95*(intensity*4*np.pi)/(SSI*1e9) instead of thermal = 0.95 * (intensity*np.pi*D**2)/(SSI*1e9).
2) The biggest mistake, which gave me ~200K instead of ~300, was in my residuals function. The idea is to minimize the difference between the observed 'overall' reflectance spectra (= back-scattered light + thermal emission) and the simulated 'overall' spectra (correctly calculated as S = scat_light + 0.95*planck(T) in residuals. The error comes from the fact that this function returns the sum of squared differences between the BACK-SCATTERED light and the simulated OVERALL reflectance spectrum (=baskscaterred + thermal) : as the 'amount' of back-scattered light is much 'smaller' that the thermal emission at the studied wavelengths, it tried to fit a 'smaller' data (and thus explaining the low temperature fit).
I changed that and I now obtain a temperature of ~ 313 K that matches my observed overall reflectance curve very well.
Thank you all for your responses!

A: According to the scipy.optimize.minimize documentation x0 should be, "Initial guess. Array of real elements of size (n,), where 'n' is the number of independent variables." So you're guessing that a temperature of T=345 will minimize the sum of squared differences. This is then returning a single best T for all T's in your data (assuming you have more than one sample) to minimize this function. Since apparently you know the answer should be around 340K I would imagine that there is an error in your formulas leading into or out of the planck() function somewhere.
It also wouldn't hurt to look at the other attributes of the res output to see if there can be additional clues garnered there.


text:
Q: RDC not working from outside I've set up Remote Connection according to : http://windows.microsoft.com/is-IS/windows7/allow-remote-desktop-connections-from-outside-your-home-network
That is,

*

*Allow remote connections to the computer you want to access.

*Make sure Remote Desktop is able to communicate through your firewall.

*Find the IP address of the computer on your home network that you want to connect to.

*Open your router's configuration screen and forward TCP port 3389 to the destination computer's IP address.

*Find your router's public IP address so that Remote Desktop can find it on the Internet.

When I'm inside the LAN, RDC works flawlessly. When I try to connect to the ip given by my ISP it cannot connect.
I've setup port forwarding for 3389 on my netgear router.
Thanks!


text:
Q: Computer Networks & Distributed Systems I am hoping to develop a chat program that will allow two people to communicate over a TCP or a UDP connection, basically with a client and a server.
Could anyone please suggest some books I could use that would cover such topics and perhaps also contains tutorials also.
Thank you for your time :)

A: I suggest you read this book (http://professionalxmpp.com/), it describes the whole chatting stack, frontend and backend along with XMPP protocol explanation, and how to use it to make your chatting application.
let me know if that what you want .. Good luck!
Edit
Also, a good list of books that might help you on the same topic: http://xmpp.org/resources/books/


text:
Q: How to fetch posts order by meta value? Well I am stuck in a sorting posts in wordpress! I know this is a previously asked question, but no luck for me the codes and solutions I found here!
The below is code snippet I am using.
$args = array(
      'showposts'=>10,
      's' => $search,
      'meta_key'        => 'neighboorhood',
      'meta_value'  => $location,
      'orderby'   => 'meta_value_num',
      'meta_key'  => 'is_sort',
    );

A: That can not work, since you use meta_key twice in your array. You should use an meta_query for the where clause, and meta_key only for the sort.
$args = array(
    'showposts'=>10,
    's' => $search,
    'meta_query' => array(

        array(
            'key' => 'neighboorhood',
            'value' => $location
        )
    ),
    'meta_key'  => 'is_sort',
    'orderby'   => 'meta_value_num'
);

A: Just use below mentioned code to fetch posts order by meta_value :
<?php

        $myargs = array(
           'posts_per_page' => 4, //number of post to show
           's' => $search,
           'meta_key' => 'is_sort', //name of meta field
           'orderby' => 'meta_value_num',
           'order' => 'ASC', // you can modify it as per your use
           'meta_query' => array(
                array(
                    'key'       => 'neighboorhood',
                    'value'     => $location,
                    )
                )
        );

        query_posts($myargs );

        if (have_posts()) : while (have_posts()) : the_post(); ?>

<?php the_title();?>

<?php the_content();?>

         <?php endwhile;
           endif;
           wp_reset_query();  ?>

Just use the above mentioned code, you will get your desired result. If you are using this process in case of date field, then please check here for better understanding : http://www.wptricks24.com/how-to-order-wordpress-post-by-custom-field-date


text:
Q: Getting error while indexing csv file in solr I have a file called data.csv in doc file.
while indexing the csv file I am getting below error:
docs]$ curl "http://localhost:8983/solr/update/csv?commit=true" --data-binary @data.csv -H 'Content-type:text/plain; charset=utf-8'<?xml version="1.0" encoding="UTF-8"?>
<response>

<lst name="responseHeader"><int name="status">415</int><int name="QTime">0</int></lst><lst name="error"><str name="msg">Unsupported ContentType: text/plain  Not in: [application/xml, text/csv, text/json, application/csv, application/javabin, text/xml, application/json]</str><int name="code">415</int></lst>

</response>

Can anybody help me out here

A: Did you try seting the Content-type header to text/csv ? Because the error message is pretty clear in it's description
EDIT :
The init method of the CSVRequestHandler looks like this :
  public void init(NamedList args) {
    super.init(args);
    setAssumeContentType("application/csv");
    // log.warn("Using deprecated class: "+this.getClass().getSimpleName()+" -- replace with UpdateRequestHandler");
  }

I guess application/csv could work after all


text:
Q: Notification opening launch activity when app is closed I am Implementing google cloud messaging service (GCM) in my app. I used the gcmIntent service to create a pending intent and open an activity which is not a launch activity. When the app is open it works fine. But when app is closed it opens the launch activity instead of the desired activity. I tried all the solution i could find but nothing is working. I am Struggling for more than a week. Any help will be greatly appreciated.
My code
public class GcmIntentService extends IntentService {
    public static final int NOTIFICATION_ID = 1;
    private NotificationManager mNotificationManager;
    Notification notification;
    NotificationCompat.Builder builder;

public GcmIntentService() {
    super("GcmIntentService");
}
public static final String TAG = "GCM Demo";

@Override
protected void onHandleIntent(Intent intent) {
    Bundle extras = intent.getExtras();
    GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
    String messageType = gcm.getMessageType(intent);

    if (!extras.isEmpty()) {

        if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {

        } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {

        } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
            String [] message={extras.getString("abc"),extras.getString("zyx"),extras.getString("123"),extras.getString("456")};
            if(UserDetails.getPushNotificationStatus(this)){
                sendNotification(message);
            }
        }
    }
    GCMBroadcastReceiver.completeWakefulIntent(intent);
}

private void sendNotification(String[] msg) {
    mNotificationManager = (NotificationManager)
            this.getSystemService(Context.NOTIFICATION_SERVICE);

    Intent notificationIntent = new Intent(getBaseContext(), ShowShoutComment.class);
    // set intent so it does not start a new activity
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
            Intent.FLAG_ACTIVITY_SINGLE_TOP|Intent.FLAG_ACTIVITY_NEW_TASK);
    PendingIntent contentIntent =
            PendingIntent.getActivity(getBaseContext(), 0, notificationIntent, 0);

    Uri notificationUri = RingtoneManager
            .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(this)
    .setSmallIcon(R.drawable.ic_launcher)
    .setLargeIcon(remote_picture)
    .setContentText(Html.fromHtml(msg[2]))
    .setContentTitle("Shout")
    .setSound(notificationUri)
    .setStyle(new      NotificationCompat.BigTextStyle().bigText(Html.fromHtml(msg[2])));

    mBuilder.setContentIntent(contentIntent);
    notification = new Notification();
    notification = mBuilder.build();
    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    notification.flags |= Notification.FLAG_SHOW_LIGHTS;
    notification.defaults |= Notification.DEFAULT_LIGHTS;
    mNotificationManager.notify(NOTIFICATION_ID, notification);

}
}

I get the following stacktrace
05-20 09:47:44.926: I/ActivityManager(753): START u0 {cmp=com.shout.shout/.activities.ShowShoutComment bnds=[0,153][1080,441]} from pid -1
05-20 09:47:44.926: W/ActivityManager(753): startActivity called from non-Activity context; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: Intent { cmp=com.shout.shout/.activities.ShowShoutComment bnds=[0,153][1080,441] }
05-20 09:47:44.976: I/ActivityManager(753): Start proc com.shout.shout for activity com.shout.shout/.activities.ShowShoutComment: pid=4742 uid=10195 gids={50195, 3003, 1028, 1015}
05-20 09:47:45.016: W/ActivityThread(4742): Application com.shout.shout can be debugged on port 8100...
05-20 09:47:45.146: I/ActivityManager(753): START u0 {flg=0x4000000 cmp=com.shout.shout/.activities.ShoutFeed} from pid 4742
05-20 09:47:45.626: I/ActivityManager(753): Displayed com.shout.shout/.activities.ShoutFeed: +476ms (total +668ms)

A: put this in your above (service class)
Intent intent2 = new Intent(context, yourDesiredActivity.class);
intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pIntent = PendingIntent.getActivity(context, 0, intent2, 0);

hope this will help you.

A: Made a few changes.
private void sendNotification(Context context,String[] msg) {

   ....
   Intent notificationIntent = new Intent(context, ShowShoutComment.class);
   ....
   PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
   ...
}


text:
Q: What is the easiest way to substract 6 months from Timestamp php I have a date in timestamp format. From which I need to subtract 6 months from it. This is the current way I do this
 $begin = Carbon::createFromTimestamp($begin, Timezone::IST)->subMonths(6);

But I again the need the timestamp format since I save this as integer (laravel). Is there a better way of doing this

A: Like this
 $Datetime = new DateTime($time);
 $Datetime->modify('-6 months');
 echo $Datetime->format('Y-m-d');

http://php.net/manual/en/class.datetime.php

UPDATE
What is this?

But I again the need the timestamp format since I save this as integer (laravel). Is there a better way of doing this

I mean what does the int look like. You can use something like this DateTime::createfromformat( 'Y-m-d', '2018-01-01')  And then output it as a timestamp with $Datetime->gettimestamp();
So the full code would close to:
$Datetime- = DateTime::createfromformat( '{your date format}', $datestring);
$Datetime->modify('-6 months');
$timestamp = $Datetime->gettimestamp();

You should not subtract an arbitrary number of seconds, because that wont account for leap years, or months with odd numbered days.  Date time relative formats are provided especially for doing this, so it's best to use them.
UPDATE2 ( for Carbon )
If you look at the source for Carbon its an extension of DateTime and thus probably provides the same functionality, and a bit more. So even this may work Carbon::createFromTimestamp($begin, Timezone::IST)->subMonths(6)->gettimestamp()
As this tid bit from the carbon source shows
public function diffInSeconds(Carbon $dt = null, $abs = true)
{
    $dt = $dt ?: static::now($this->getTimezone());
    $value = $dt->getTimestamp() - $this->getTimestamp();
    return $abs ? abs($value) : $value;
}

Specifically $this->getTimestamp(), this is no big surprise as it extends DateTime. That said, I would avoid using the public property of timestamp as it violates the Black Box Protocol ( this is what I call it (BBP)) where a class should be a black box for it's functionality.  And you should only access data from a class using it's public interface ( which interfaces do not contain properties )  That's just my Opinion though.
Now if you were to really dig into the source code for carbon, then this code Carbon::createFromTimestamp($begin, Timezone::IST)->subMonths(6) probably does something very much like this:
$this->datetime = new Datetime($begin, Timezone::IST);
$this->datetime->modify('-6 months');

Specifically
class Carbon extends DateTime{

     //-------- create---------

     public static function createFromTimestamp($timestamp, $tz = null)
    {
        return static::now($tz)->setTimestamp($timestamp);
    }

    public static function now($tz = null)
    {
        return new static(null, $tz);
    }
     /*
        the code "new static" can be a bit confusing, but this is just
        one of many ways to call "new Carbon()", which in turn is calling
        new "DateTime()". They use static so if you extended Carbon it will
        work (as opposed to using "new self") a.k.a "new static" uses late
        static binding.  And they also use static, because it's cleaner then
        doing something like "new __CLASS__", which I believe will not let
        you pass in arguments (without assigning the class name to a
        variable). Where as new static($arg) works fine.  In any case it's
        generally preferred to use something like "new static" then to
        reference the class name directly as in "new Carbon".  Obviously
        this is so if the class name changes there are no repercussions on
        the code, no code to update.
    */

    //-------- subMonth ---------
    public function subMonth($value = 1)
    {
        return $this->subMonths($value);
    }

    public function subMonths($value)
    {
        return $this->addMonths(-1 * $value);
    }

    public function addMonths($value)
   {
        if (static::shouldOverflowMonths()) {
            return $this->addMonthsWithOverflow($value);
        }
        return $this->addMonthsNoOverflow($value);
    }

    public function addMonthsWithOverflow($value)
    {
        return $this->modify((int) $value.' month');
    }

    public function addMonthWithOverflow($value = 1)
    {
        return $this->addMonthsWithOverflow($value);
    }

}

So it calls like 4 or 6 additional function calls, but in the end it's basically the same.  Taken right from the github source code.
For creating they are just making a DateTime object (child) with the current day and then setting the date in it with the timestamp.
All they are doing is taking the 6 you give them *-1 so it's -6 then doing $this->modify('-6 months') which as it extends DateTime is roughly equivalent.
Basically all the code I pasted above, can be done in 3 lines.  But, if it was me I would still use Carbon, as it's the "frameworks" way of doing it, so it's a tad bit more proper.  Also function calls are cheep, and performance wise you wont really notice the few nanosecond difference.  So as always I would lean to Readability ( within the framework ) over performance.
As a side I never used Carbon but it looks interesting.  I delved a bit deeper then I probably should have, but I have been thinking of making something very similar, so perhaps I will just "composer in" Carbon ... lol ... The older I get the lazier I am, 6 years ago, I would have just hammered away at the keys tell I had something very similar to it.  But composer wasn't around then, so ...

A: You can just use ->timestamp:
$begin = Carbon::createFromTimestamp($begin, Timezone::IST)->subMonths(6)->timestamp;

But if you're saving this and all other dates to DB as timestamps, you can set $dateFormat property to U:
protected $dateFormat = 'U';

Then, $begin will be converted to Carbon instance automatically by Laravel. So, you could just do this:
$begin->setTimezone(IST')->subMonths(6);

And then just save it back to DB without manually converting it back to timestamp.
https://laravel.com/docs/5.5/eloquent-mutators#date-mutators


text:
Q: AngularJS - Change properties of a class from a controller I won't harp on about the use-case for this (it's needed to override some behaviour in Angular Material which is causing bugs in Safari), but here's what I'm trying to do:
HTML:

  Some Text

My JS code looks at the height of the browser window, and I need to change the height attribute of .changeme dynamically from my controller.
I CANNOT do this via ng-style, as Angular Material strips ng-styles away from the particular element in question.
Is it possible to manipulate a


text:
Q: Multi-class classification: good accuracy on validation set but prediction on test set I'm trying to classify images belonging to 16 classes. The images have different geometric shapes (see Fig. 2). The training set consists of 16 x 320 = 5120 images, the validation set has 16 x 160 = 2560 images, and the test set has 16 x 2 = 32 images.
I'm using the below code to build the CNN and make predictions.
import numpy as np
np.random.seed(0)

import keras
from keras.models import Sequential,Input,Model
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras.layers.normalization import BatchNormalization
from keras.layers.advanced_activations import LeakyReLU
from keras import regularizers
from keras.layers import Activation

num_classes = 16
classifier = Sequential()
classifier.add(Conv2D(32, kernel_size=(3, 3),activation='relu',input_shape=(64, 64, 3),padding='same'))
classifier.add(MaxPooling2D((2, 2),padding='same'))

classifier.add(Dropout(0.2))

classifier.add(Conv2D(64, (3, 3), activation='relu',padding='same'))
#classifier.add(LeakyReLU(alpha=0.1))
classifier.add(MaxPooling2D(pool_size=(2, 2),padding='same'))

classifier.add(Dropout(0.2))

classifier.add(Conv2D(64, (3, 3), activation='relu',padding='same'))
classifier.add(MaxPooling2D(pool_size=(2, 2),padding='same'))

classifier.add(Dropout(0.25))

classifier.add(Conv2D(128, (3, 3), activation='relu',padding='same'))
classifier.add(MaxPooling2D(pool_size=(2, 2),padding='same'))

classifier.add(Dropout(0.25))

classifier.add(Flatten())
classifier.add(Dense(128, activation='relu'))

classifier.add(Dropout(0.25))

classifier.add(Dense(num_classes, activation='softmax'))

# Compiling the CNN
classifier.compile(optimizer = 'adam', loss = 'categorical_crossentropy', metrics = ['accuracy'])

from keras.preprocessing.image import ImageDataGenerator
from IPython.display import display
from PIL import Image

train_datagen = ImageDataGenerator(rescale = 1./255,
                                   shear_range = 0.2,
                                   zoom_range = 0.2,
                                   width_shift_range=0.1,
                                   height_shift_range=0.1)

test_datagen = ImageDataGenerator(rescale = 1./255)

training_set = train_datagen.flow_from_directory('dataset/training_set',
                                                 target_size = (64, 64),
                                                 batch_size = 32,
                                                 class_mode = 'categorical')

test_set = test_datagen.flow_from_directory('dataset/test_set',
                                            target_size = (64, 64),
                                            batch_size = 32,
                                            class_mode = 'categorical')

from keras.callbacks import ModelCheckpoint
from keras.callbacks import EarlyStopping

STEP_SIZE_TRAIN = training_set.n//training_set.batch_size
STEP_SIZE_TEST = test_set.n//test_set.batch_size

early_stopping_callback = EarlyStopping(monitor='val_loss', patience=3)
checkpoint_callback = ModelCheckpoint('model' + '.h5', monitor='val_loss', verbose=1, save_best_only=True, mode='min')

classifier.fit_generator(training_set,
                    steps_per_epoch = STEP_SIZE_TRAIN,
                    epochs = 10,
                    validation_data = test_set,
                    validation_steps = STEP_SIZE_TEST,
                    callbacks=[early_stopping_callback, checkpoint_callback],
                    workers = 32)

from keras.models import load_model
model = load_model('model.h5')

# Part 3 - making new predictions
import numpy as np
from keras.preprocessing import image
for i in range(1,33):
    test_image = image.load_img('dataset/single_prediction/Image ' + str(i) +'.bmp', target_size = (64, 64))
    test_image = image.img_to_array(test_image)
    test_image = np.expand_dims(test_image, axis = 0)
    #print(model.predict(test_image)[0])
    print(model.predict(test_image)[0].argmax()+1)

I'm getting the following result for the training and validation accuracy and loss.
Epoch 1/10
160/160 [==============================] - 29s 179ms/step - loss: 1.3693 - acc: 0.5299 - val_loss: 0.1681 - val_acc: 0.9297

Epoch 00001: val_loss improved from inf to 0.16809, saving model to model.h5
Epoch 2/10
160/160 [==============================] - 18s 112ms/step - loss: 0.2668 - acc: 0.8984 - val_loss: 0.0773 - val_acc: 0.9699

Epoch 00002: val_loss improved from 0.16809 to 0.07725, saving model to model.h5
Epoch 3/10
160/160 [==============================] - 18s 111ms/step - loss: 0.1469 - acc: 0.9482 - val_loss: 0.0133 - val_acc: 1.0000

Epoch 00003: val_loss improved from 0.07725 to 0.01327, saving model to model.h5
Epoch 4/10
160/160 [==============================] - 18s 111ms/step - loss: 0.0990 - acc: 0.9650 - val_loss: 0.0147 - val_acc: 1.0000

Epoch 00004: val_loss did not improve from 0.01327
Epoch 5/10
160/160 [==============================] - 18s 113ms/step - loss: 0.0700 - acc: 0.9740 - val_loss: 7.3014e-04 - val_acc: 1.0000

Epoch 00005: val_loss improved from 0.01327 to 0.00073, saving model to model.h5
Epoch 6/10
160/160 [==============================] - 18s 114ms/step - loss: 0.0545 - acc: 0.9809 - val_loss: 0.0012 - val_acc: 1.0000

Epoch 00006: val_loss did not improve from 0.00073
Epoch 7/10
160/160 [==============================] - 18s 111ms/step - loss: 0.0374 - acc: 0.9865 - val_loss: 0.0101 - val_acc: 1.0000

Epoch 00007: val_loss did not improve from 0.00073
Epoch 8/10
160/160 [==============================] - 18s 111ms/step - loss: 0.0489 - acc: 0.9832 - val_loss: 0.0200 - val_acc: 0.9992

When trying to test the model on the 32 images of the test set, I got only 3 correct predictions. So my questions are:
1) Why I'm getting a good accuracy on validation but the models fails on the test set?
2) How can I display a random sample of the validation set (say 10 images) with their predicted classes, to have an idea how the CNN is doing on the validation set?
3) Any general tips on how to improve the accuracy on the test set?
Any help is appreciated!
Many thanks :)

A: This could have happened for many reasons, but I will address one which is the difference in data distribution between your train, validation and test sets.
In an ideal situation, you should have your train, validation and test sets come from the same distribution. While this is a concept, in practice it could mean not only the same amount of data points per class, but also among many other dimensions. Such dimension could be the quality of images per splits, i.e. you should avoid having quality images in your train set and valid set, while test set to have low quality images. And there are many more dimensions like this along which distributions ideally should be same.
Therefore it is a game of chances, and you want to avoid a chance of having, on the account of bad luck and no matter how low probable such an event is, ending up with a test set that is different than the rest of the splits.
To overcome this:
1) Choose a different seed while shuffling your data before splitting
2) Choose equal split size for your test and validation sets
3) Use k-fold cross validation
You can do one or any of the above steps alone or in combination. You can read more about  it here:
https://cs230-stanford.github.io/train-dev-test-split.html
Hope this helps


text:
Q: Getting this error org.json.JSONException: Value at 0 of type java.lang.String cannot be converted to JSONObjecton parsing I am getting this error on parsing json. Can anyone help me to solve this.
  {
"website": [
    "http://www.example.com",
    "https://buy.example.com"
],
"number": [
    "4546",
    "54256456"
],
"email": [
    "exam@gmail.com",
    "example@gmail.com"
],
"address": [
    "any adddress here",
    "Address 2"
]
  }

Anyone help me to how exactly parse this json...
Json Parsing code
             String JSON_STRING = response.body().string();
                    Log.e("json_string", JSON_STRING.toString());
                    //Toast.makeText( getApplicationContext(), "Response : "+JSON_STRING, Toast.LENGTH_LONG ).show();

                    JSONObject object = new JSONObject( JSON_STRING );
                    JSONArray jsonArray = object.getJSONArray( "website" );

                        for (int i=0; i<jsonArray.length(); i++)
                        {
                            JSONObject website = jsonArray.getJSONObject( i );
                            Log.e("website", website.toString());
                        }

A: // for email array and response variable is your jsonObject coming from server
JSONArray jsonArray = response.getJSONArray("email")
for(int i = 0; i < jsonArray.length(); i++){
   //get email one by one
   String email = jsonArray.getString(i)
}

Let me know if it is working.

A: try this code
 try {
        JSONObject jsonObject = new JSONObject(json);
        JSONArray websites = jsonObject.getJSONArray("website");
        for (int i = 0; i < websites.length(); i++) {
            Log.d("TAG", websites.getString(i));
        }

    } catch (Exception e) {
        e.printStackTrace();
    }


text:
Q: What is the reason for this geometric answer?
$$\frac{AB}{CD} = \frac{2}{2.6} = 0.77\ldots$$
$$\frac{AC}{AD} = \frac{2}{2.6} = 0.77\ldots$$
$$\frac{BC}{AC} = \frac{2}{2.6} = 0.77\ldots$$
Therefore $\triangle ABC$ and $\triangle ACD$ are similar.
I know from the answer sheet that $y$ is $47^\circ$ and $x$ is $109^\circ$. I don't know the reasons why though. The diagram does not look like a parallelogram because both opposite sides are not parallel.

A: The 3 relations you wrote imply that $ABC$ is similar to $ACD$ hence $\hat{ACD}=x$ and $\hat{ADC}=y$ because of the similarity of the 2 triangles.
Also you get that $\hat{BCA}=\hat{CAD}$.
The reason is that the 3 relations show exactly what is the correspondence of their sides and this gives you also a correspondence of their angles.

A: In calculating ratios of this kind, it would be easier if you divide the largest side of the larger triangle by the largest side of the smaller triangle (medium side by the medium corresponding side, etc.) such that the chance of getting round-off errors can be reduced.
Thus, $\frac{CD}{AB} = \frac {2.6}{2} = 1.3$. Similarly, you will get 1.3 for the other two sets.
After the above has been found, by the theorem "3 sides proportional", you can claim that ⊿ABC is similar to ⊿DCA.
By "corresponding measurements", you can further claim that $\angle BCA = \angle CAD$.
Since these two angles are in the alternate angle positions, by the theorem "alternate angles equal", you can conclude that BC is in fact parallel to AD.

A: Continuing,
since the triangles are similar,
$x = 109$
and
$y
= CAD
=180-(109+47)
=180-156
=24
$.


text:
Q: How do I get a Nexus 5/~5 inch 1080p phone emulator? The Android SDK doesn't ship with a device definition for a Nexus 5 emulator (or a ~4.7 inch 1080p phone in general) and I need one. No problem, right? Just copy the Nexus 4 definition and change the resolution to 1080x1920, right?
Well, that gives me this, which obviously isn't right. So what am I doing wrong? I've tried twiddling with the size buckets and density buckets but it's not changing a thing.

A: Current versions of the Android SDK do ship with a device definition for Nexus 5. There is even a really nice nexus 5 emulator skin on github: https://github.com/markusherzog/android-emulator-skin-nexus-5 :-)


text:
Q: Convert Table to Multidimensional Hash in Ruby I know that there must be some simple and elegant way to do this, but I'm drawing a blank.
I have a table (or group of key value pairs)
id,val
64664,68
64665,65
64666,53
64667,68
64668,6
64668,27
64668,33
64669,12

In most cases there is one value per id. In some cases there are multiples.
I want to end up with each id with multiple values represented as an array of those values
something like this:
[ 64664 => 68,
64665 => 65,
64666 => 53,
64668 =>[6,27,33],
64669 => 12
]

Any brilliant ideas?

A: You can use Hash#merge to merge two hashes. Using Enumerable#inject, you can get what you want.
tbl = [
  [64664, 68],
  [64665, 65],
  [64666, 53],
  [64667, 68],
  [64668, 6],
  [64668, 27],
  [64668, 33],
  [64669, 12],
]

# Convert the table to array of hashes
hashes = tbl.map { |id, val|
  {id => val}
}

# Merge the hashes
hashes.inject { |h1, h2|
  h1.merge(h2) { |key,old,new|
    (old.is_a?(Array) ? old : [old]) << new
  }
}
# => {64664=>68, 64665=>65, 64666=>53, 64667=>68, 64668=>[6, 27, 33], 64669=>12}

A: values = [
  [64664, 68],
  [64665, 65],
  [64666, 53],
  [64667, 68],
  [64668, 6],
  [64668, 27],
  [64668, 33],
  [64669, 12],
]

# When key not present, create new empty array as default value
h = Hash.new{|h,k,v| h[k]=[]}
values.each{|(k,v)| h[k] << v}

p h #=>{64664=>[68], 64665=>[65], 64666=>[53], 64667=>[68], 64668=>[6, 27, 33], 64669=>[12]}


text:
Q: list view selection issue in android I have a listview defined in xml
    <ListView
        android:id="@+id/lv_results"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:choiceMode="singleChoice"
        android:listSelector="@drawable/list_selector" >
    </ListView>

Drawable -> list_selector
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item  android:state_pressed="true"><color android:color="@color/blue"/></item>
<item  android:state_hovered="true"><color android:color="@color/blue"/></item>
<item><color android:color="@color/blue"/></item>

</selector>

Now, I have a dialog box which pops up on selecting an item from the list view. The row which was clicked is highlighted.
Requirement:- On selection of 'No' from the dialog, the listview row item should get deselected. I want it to get transparent.
I have the NegativeDialogClickEvent and I have tried
lv.setSelection, lv.setBackgroundColor but somehow it doesn't seem to work.

A: Keep the checked position in global variable on list item checked.
Let's say checked position is 2. Keep this position in mClickedPos = 2;
And get the callback of "No" option select on dialog. Add the below code.
listView.setItemChecked(mClickedPos, false);

Please refer the below link to know more about listView setItemChecked() method.
link-for-reference


text:
Q: Problema con el teclado del celular android Tengo un problema que cuando ejecuto mi aplicación en Android lo que pasa es que tengo unos botones en la parte inferior de la pantalla y al presionar un EditText aparece el teclado y oculta mis botones, quiero saber como hacer para que el botón suba al nivel del teclado y de esta manera no se oculte

A: La actividad que contiene el boton o botones en el android manifest añade el siguiente atributo:
android:windowSoftInputMode="adjustResize"

El resultado sería:
<activity
    android:windowSoftInputMode="adjustResize"
>

En el xml de la actividad que contiene los botones, añade este atributo en el layout que contiene el boton:
 android:fitsSystemWindows="true"

Si es un solo layout que contiene todos los demás botones o textviews se lo pones a ese, si el botón este dentro de un layout X que a su vez esta dentro de otro layout Y que sería el global, el atributo irá en el layout x , es decir pónselo al layout en concreto donde se encuentran los botones.

A: En tu layout coloca todo el contenido (el EditText y los botones) dentro de un ScrollView.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <EditText
            ... />

        <Button>
            ... />

            ...

    </ScrollView>
</RelativeLayout>


text:
Q: What is the difference between the normal vector to a surface given by the traditional formula and the one given by the gradient?
What is the difference between the normal vector to a surface given by the traditional formula and the one given by the gradient?

In my class we learnt that the normal vector to a surface described by a function $f(x,y)$ can be obtained by using this formula:
$$
n=\langle f_x(x_0,y_0), f_y(x_0,y_0),-1 \rangle
$$
So for example I have an ellipsoid $3x^2+2y^2+12z^2=42$. According to the formula above the normal vector is:
$$
n=\bigg\langle-\frac{3x}{\sqrt{12}\sqrt{42-3x^2-2y^2}},-\frac{2y}{\sqrt{12}\sqrt{42-3x^2-2y^2}},-1\bigg\rangle
$$
On the other hand we learnt that the normal vector to a surface can also be obtained by calculating the gradient so:
$$
n=\langle 6x,4y,24z\rangle
$$
Admittedly, the normal vector obtained by gradient is a much simpler calculation.
Are these results equivalent to one another? Is there any difference? Are there cases when one formula has to be used over another?

A: As you mention, if you have a surface described by $z=f(x,y)$, the normal vector on $(x_0,y_0)$ can be computed by:
$$\vec{n}=\langle f_x(x_0,y_0), f_y(x_0,y_0),-1 \rangle.$$
But $z=f(x,y)$ can also be expressed as implicitly as $g(x,y,z)=f(x,y)-z=0$. In that case, the gradient of $g$ also gives you the normal vector on $(x_0,y_0,z_0)$, where $z_0=f(x_0,y_0)$:
$$\vec{n}=\langle g_x(x_0,y_0,z_0), g_y(x_0,y_0,z_0), g_z(x_0,y_0,z_0) \rangle.$$
Note that if you use the equation of the ellipsoid to substitute $z$ on your second vector. Then normalize both the first and the second one and you will see that both are equal (up to a sign).
You can read about those and many other ways of computing the normal vector here.

A: Well, there are different way to describe a surface with a function
When you say "a surface described by a function $f(x,y)$", you probably mean a surface described by the equation $$
z=f(x,y) \tag{*}$$
and not $$f(x,y)=0$$ because in the second case, the normal vector would have zero $z$ component.
The gradient formula is the general one, and applicable to any surface given by an expression $g(x,y,z)=0$, as in your example (with $g(x,y,z)= 3x^2+2y^2+12z^2-42$).
Now you can rewrite your Eq. (*) as $$g(x,y,z)=f(x,y)-z=0\,,$$and simply apply the gradient formula to obtain your first expression.


text:
Q: computing precision and recall based on two list of bounding box does anyone know, given two lists of the bounding box, one is predicted, the other is the ground truth, is there some existing python library or code I can use to compute the accuracy? There are many existing codes for first calculating the lou, and I know I can compute it on my own. But I thought there should also be some existing tools I can use to directly get the accuracy indexes so that I finish my project in a smarter way than coding by myself.
Thanks!

A: Yes there is a lot of love from sklearn.metrics
Heres a link: http://scikit-learn.org/stable/modules/classes.html#sklearn-metrics-metrics
Here's a basic example:
from sklearn.metrics import accuracy_score
pr_score = accuracy_score(y_test, y_pred)
print(pr_score)

Where y_pred is the predictions and y_test is the so called "ground truth"
In the above link you can read and chose the evaluation metric that suits you.


text:
Q: No Field for Pre Shared Key in Group Policy I am attempting to configure group polocy (Windows 2008 R2) to issues a WPA Pre shared Key on client login.
Through Group Policy I can setup WPA and select PSK (Along with TKIP)
But there's not field to enter my Pre Shared Key!
Any help would be appricaited

A: I have investigated this in the past... MS simply do not support this option.


text:
Q: Which functions are linear combinations of irreducible characters for a given field $\Bbbk$? Let $G$ be a finite group. Then it is well known that a function $f\colon G\to \mathbb C$ is a linear combination of irreducible characters iff it is constant on conjugacy classes.  What is the corresponding result for an arbitrary field $\Bbbk$, i.e., which $\Bbbk$-valued mappings on $G$ are $\Bbbk$-linear combinations of irreducible characters over $\Bbbk$?  I am assuming neither characteristic $0$, nor algebraically closed.  I expect the answer is well known and involves the characteristic and which primitive roots of unity exist. Any references are greatly appreciated.
A more specific question:  Is it true that if $f\colon G\to \Bbbk$ is constant on conjugacy classes and is constant on cyclic subgroups, then it is a linear combination of irreducible characters over $\Bbbk$?

A: I am interpreting your question as talking of $k$-linear combinations of traces of $k$-representations of $G.$ Note that such a function must not only be constant on conjugacy classes, but should also be constant on $p^{\prime}$-sections, where $k$ has characteristic
$p.$ Recall that every element of $G$ may be written uniquely in the form $g = ab = ba,$ where $a$ has order a power of $p$ and $b$ has order prime to $p.$ The element $b$ is called the $p^{\prime}$-part of $g.$ Two elements of $G$ are said to be in the same $p^{\prime}$-section of $G$ if and only if their $p^{\prime}$-parts are conjugate. I think this reduces us to the case where $G$ is a cyclic $p^{\prime}$-group, using Brauer's or Conlon's induction theorem.
 I think you may find the necessary analysis of that case in the 1962 book of Curtis and Reiner.
 Expanded edit: The work (of Berman I believe, if my memory is accurate), I am alluding to,
deals with the fact that dealing with traces of $k$-valued representations forces some equality of traces at group elements at elements which are not $G$-conjugate. We can assume, as I indicated, that $|G|$ is coprime to char $k$ if char $k \neq 0$. So, for example, if $\theta$ is the trace of a $k$-representation and $k$ has $q$ elements, then we must have $\theta(g) = \theta(g^{q})$ for all $g \in G.$ Similarly, if $k = \mathbb{Q},$ and $\theta$ is the trace of a $\mathbb{Q}$-valued representation, we must have $\theta(g) = \theta(h)$ whenever $\langle g  \rangle = \langle h \rangle.$
 So, let us say that $g$ and $g^{m}$ are $k$-conjugate if $\theta(g) = \theta(g^{m})$ whenever $\theta$ is the trace of a representation over $k.$ Then a $k$-valued class function $\psi$ of $G$ is said to respect $k$ if $\psi(g) = \psi(g^{m})$ whenever $g$ and $g^{m}$ are $k$-conjugate. Then the best you can hope for is that the traces of $k$-representations span the space of $k$-valued class functions which respect $k,$ and this is indeed the case.


text:
Q: Entity Framework ignores Column attribute I have a large MySQL database mapped to POCOs using Entity Framework Data Annotations.
Most things work great, except one column in one table(or at least, I have not yet noticed any other similar problems).
mysql > describe _passwords;
+----------------+------------+------+-----+---------------------+----------------+
| Field          | Type       | Null | Key | Default             | Extra          |
+----------------+------------+------+-----+---------------------+----------------+
| id             | bigint(20) | NO   | PRI | NULL                | auto_increment |
| creation_date  | timestamp  | NO   |     | CURRENT_TIMESTAMP   |                |
| user_id        | bigint(20) | NO   | MUL | NULL                |                |
| password_hash  | char(64)   | NO   |     | NULL                |                |
| valid_end_date | timestamp  | NO   |     | 0000-00-00 00:00:00 |                |
+----------------+------------+------+-----+---------------------+----------------+

The password_hash column is mapped like this:
[Required]
[Index(IsUnique=true)]
[Column("password_hash")]
public String PasswordHash
{
    get;
    set;
}

And yet when EF runs this query, it calls it PasswordHash, and naturally, fails.
When I try the same using Fluent API this works:
modelBuilder.Entity<Password>().Property(password => password.PasswordHash).HasColumnName("password_hash");

However, everything else is mapped with Data Annotations, and frankly, I like it this way. So would rather understand the root of this problem over moving this/all mappings to Fluent API


text:
Q: the controller doesn't work Hi everyone at this time I created a new controller, view and helper called Menuprestacionessociales
I have all the files as I think it should be
menuprestacionessociales_controller.rb
class MenuprestacionessocialesController < ApplicationController
    def index
        @variable = "cualquier contenido"
    end
end

menuprestacionessociales/index.html.erb
<%= @variable %>

So I have a simple variable in my controller called @variable but if I try to show the content in the index, it doesn't show anything

A: Put <%= @variable %> somewhere in the index.html.erb file.


text:
Q: Oracle setup estimate I need to set up a new database (Oracle), on a new system. I need to prepare the costing.
Can anyone please suggest what all this will involve. I can think of Oracle licenses, hardware boxes, etc. I've no idea which processor to go for (and how many cores) and how much RAM should be sufficient. Apart from this what else do I need to setup a complete box with Oracle, cluster and SAN as well.
I know the requirement vary from case to case. But in this case the traffic is not be huge.
If someone can give just rough idea and point me somewhere, that will be great.

A: You could start here: Software Investment Guide.
When you understand what Oracle version you need,
you should check the HW and SW requirement here: Oracle Database Online Documentation.


text:
Q: Moving cursor with the arrow keys in vim normal mode inserts ABCD characters As the title says, using the arrow keys puts me in insert mode and adds the A,B,C or D character when I use the arrow keys.
Yes, I got set nocompatible in my .vimrc
Tried setting set t_ku=^[OA, didn't work.
Tried disabling arrow keys in normal mode, didn't work.
I've got ubuntu 16.04 and vim 7.4
Any ideas how I could fix the issue?


text:
Q: Why is my formula not working for a pick list value? I am trying to make a field populate with a formula based on a selection in a picklist value. can you please check my formula?
CASE(FedCapture__Our_Role__c,

"Prime",Total_Contract_Value_USD__c  * ( Calculated_PWIN__c), Total_Contract_Value_USD__c * ((100) * (Calculated_PWIN__c))
)

"Subcontractor",Total_Contract_Value_USD__c  * ( Calculated_PWIN__c), Total_Contract_Value_USD__c * ((100) * (Calculated_PWIN__c))
)

"JV - Managing Partner",Total_Contract_Value_USD__c  * ( Calculated_PWIN__c), Total_Contract_Value_USD__c * ((  G_IAP_Share_JV_Share__c) * (Calculated_PWIN__c))
)

"JV - Minority Partner",Total_Contract_Value_USD__c  * ( Calculated_PWIN__c), Total_Contract_Value_USD__c * ((  G_IAP_Share_JV_Share__c) * (Calculated_PWIN__c))
))

A: The syntax of the CASE() formula is this:
CASE(
    field to compare,
    test_value_1, result_1,
    test_value_2, result_2,
    ...
    test_value_n, result_n,
    default_result
 )

If we use this, and apply it to your provided formula...
CASE(
    FedCapture__Our_Role__c,
    'Prime', Total_Contract_Value_USD__c  * ( Calculated_PWIN__c),
    Total_Contract_Value_USD__c * ((100) * (Calculated_PWIN__c))
),
'Subcontractor', ...

So by the time we get to testing for your second picklist value, you've already exited the CASE() function. Salesforce has no idea what to do with your formula after that point.
By looking at your attempted formula, I can guess that you want to perform an additional test for each picklist value to determine which calculation (one of two) that you want to perform.
You haven't included enough information in your question for me to give an exact formula, but the general version would look something like this:
CASE(
    FedCapture__Our_Role__c,
    "Prime", IF(<some field> = <some value>, Total_Contract_Value_USD__c  * (Calculated_PWIN__c), Total_Contract_Value_USD__c * ((100) * (Calculated_PWIN__c))),
    "Subcontractor",IF(<some field> = <some value>, Total_Contract_Value_USD__c  * ( Calculated_PWIN__c), Total_Contract_Value_USD__c * ((100) * (Calculated_PWIN__c))),
    "JV - Managing Partner", IF(<some field> = <some value>, Total_Contract_Value_USD__c  * ( Calculated_PWIN__c), Total_Contract_Value_USD__c * ((  G_IAP_Share_JV_Share__c) * (Calculated_PWIN__c))),
    "JV - Minority Partner",IF(<some field> = <some value>, Total_Contract_Value_USD__c  * ( Calculated_PWIN__c), Total_Contract_Value_USD__c * ((  G_IAP_Share_JV_Share__c) * (Calculated_PWIN__c)))
)

Notice how I've added an IF() into things here. If you want to perform one of two calculations, that's what you'll need to do. The information about which picklist value is chosen for a given record isn't enough.
You could also simplify the formula a little bit (removing extraneous parenthesis, getting rid of a few non-required field references)
CASE(
    FedCapture__Our_Role__c,
    "Prime", Total_Contract_Value_USD__c  * Calculated_PWIN__c * IF(<some field> = <some value>, 1, 100),
    "Subcontractor",Total_Contract_Value_USD__c  * Calculated_PWIN__c * IF(<some field> = <some value>, 1, 100),
    "JV - Managing Partner", Total_Contract_Value_USD__c  *  Calculated_PWIN__c * IF(<some field> = <some value>, 1 ,  G_IAP_Share_JV_Share__c),
    "JV - Minority Partner",Total_Contract_Value_USD__c  *  Calculated_PWIN__c * IF(<some field> = <some value>, 1 ,  G_IAP_Share_JV_Share__c)
)

+edit:
The above formula could be simplified further still. Since Total_Contract_Value_USD__c  *  Calculated_PWIN__c is common to all picklist values, we can take that out of the CASE() entirely
Total_Contract_Value_USD__c  *  Calculated_PWIN__c *
CASE(
    FedCapture__Our_Role__c,
    "Prime", IF(<some field> = <some value>, 1, 100),
    "Subcontractor", IF(<some field> = <some value>, 1, 100),
    "JV - Managing Partner", IF(<some field> = <some value>, 1 ,  G_IAP_Share_JV_Share__c),
    "JV - Minority Partner", IF(<some field> = <some value>, 1 ,  G_IAP_Share_JV_Share__c)
 )

A: Was able to get it to work thanks!
    CASE(FedCapture__Our_Role__c,
"Prime", Total_Contract_Value_USD__c  * Calculated_PWIN__c,
"Subcontractor", Total_Contract_Value_USD__c  * Calculated_PWIN__c,
"JV - Managing Partner", Total_Contract_Value_USD__c  * Calculated_PWIN__c G_IAP_Share_JV_Share__c, NULL)

Thanks!

A: I'm going to assume Fed_Capture_Our_Role__c is the picklist. So that would play out like this:
IF(
ISPICKVAL(FedCapture__Our_Role__c, "Prime"), Total_Contract_Value_USD__c  * ( Calculated_PWIN__c), Total_Contract_Value_USD__c * ((100) * (Calculated_PWIN__c)),
IF(
ISPICKVAL(FedCapture__Our_Role__c, "Subcontractor"), Total_Contract_Value_USD__c  * ( Calculated_PWIN__c), Total_Contract_Value_USD__c * ((100) * (Calculated_PWIN__c)),
IF(
ISPICKVAL(FedCapture__Our_Role__c, "JV - Managing Partner"), Total_Contract_Value_USD__c  * ( Calculated_PWIN__c), Total_Contract_Value_USD__c * ((  G_IAP_Share_JV_Share__c) * (Calculated_PWIN__c))),
IF(
ISPICKVAL(FedCapture__Our_Role__c, "JV - Minority Partner"), Total_Contract_Value_USD__c  * ( Calculated_PWIN__c), Total_Contract_Value_USD__c * ((  G_IAP_Share_JV_Share__c) * (Calculated_PWIN__c)),
""))))

I think the () line up it got a little confusing at the end of the line, but you get the idea.
EDIT:
You could use CASE but not in the way you currently have this setup. CASE works as CASE(expression, value, result, else_result)
Looking at your first lines you have
expression: FedCapture__Our_Role__c
value: "Prime"
result: Total_Contract_Value_USD__c  * ( Calculated_PWIN__c)
else: Total_Contract_Value_USD__c * ((100) * (Calculated_PWIN__c))
then you close it. Which would work for the one line but you continue the pattern without a new CASE(expression. So if you want to go down that path you need to remove your else result or put more case(FedCapture__Our_Role__c, in there.


text:
Q: Is there an API available to fetch the PCI compliant resources in an Azure subscription? I am trying to fetch the list of Azure resources that are PCI compliant. But didn't get a proper API for this. I have tried all the APIs available in Azure docs, but none of them are related to my requirement. I am in need of resource-level/resource-type level compliant details like the resource/resource-type is PCI compliant or not.
Thanks in advance.


text:
Q: How to make Clang on Windows link against different runtimes While attempting to build a personal project in C++, I've hit a problem. I'm unsure when it manifested as I normally work on the project in a Linux environment but want the project to work on Windows.
Unfortunately the compiler I'm using, Clang, has begun throwing the following error at me:
libboost_filesystem-vc140-mt-1_61.lib(operations.obj) : error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MD_DynamicRelease' doesn't match value 'MT_StaticRelease' in buffer.obj

The problem is I have no idea how to tell Clang which runtime the underlying compiler should use and I do not wish to use clang-cl at this time if I don't have to.
What is the correct way to make Clang on Windows link against the dynamic runtime?

A: I'm not sure which part of what I did stopped the linker from complaining, but in my build script, I specified -D_MT -D_DLL as two of my compiler and linker options and for my linker I had to disable the default libraries (-Xlinker /NODEFAULTLIB) and manually specify which versions of the runtimes to link against (in my case, -lmsvcrt -lucrt -lmsvcprt -lvcruntime). These two changes seem to have stopped all linkage and compilation errors.


text:
Q: Where to write the save function in Django? Where should I write my save() function in Django: in models.py in a model class, or in forms.py in a form?
For example :
models.py
class Customer(models.Model):
    name = models.CharField(max_length=200)
    created_by = models.ForeignKey(User)

    def save():
      ........ some code to override it.......

forms.py
class  Addcustomer(forms.ModelForm):
   class Meta:
       model = Customer
       fields = ('name',)
   def save():
     ........code to override it....

Where should I override my save function?

A: It really depends on what you are trying to achieve. Default realization of ModelForm's save calls Model's save. But it is usually better to override it on form because it also runs validation. So if you are already using form I would suggest overriding ModelForm.save. And by overriding I mean extending using super
Here is default realization of ModelForm.save
def save(self, commit=True):
    """
    Save this form's self.instance object if commit=True. Otherwise, add
    a save_m2m() method to the form which can be called after the instance
    is saved manually at a later time. Return the model instance.
    """
    if self.errors: # there validation is done
        raise ValueError(
            "The %s could not be %s because the data didn't validate." % (
                self.instance._meta.object_name,
                'created' if self.instance._state.adding else 'changed',
            )
        )
    if commit:
        # If committing, save the instance and the m2m data immediately.
        self.instance.save()
        self._save_m2m()
    else:
        # If not committing, add a method to the form to allow deferred
        # saving of m2m data.
        self.save_m2m = self._save_m2m
    return self.instance

save.alters_data = True


text:
Q: How to send a video frame by frame from a Flask app to Flutter app I have to implement a video streaming functionality in Flutter.
The video will be stored in a back-end.
(Streaming as in how people can watch videos in YouTube, the video is fetched in real-time, as required).
How do I do this?
How can I alter the playback speed in the application and pause the video?
I watched a YouTube video on how to Stream a webcam using OpenCV and Flask but how can I do that with a video? video link
More importantly, how do I serve that to a Flutter app?


text:
Q: What is the best-practice for having environment-specific Puppet scripts? I need to remove a few files when in development environment (for example when using Vagrant) but not in production. I want to disable firewalld when in development, but not in production. I would like to disable selinux whenon development, but not on production.
What is the best practice for doing these? I would like to use my puppet scripts both on development environments (with Vagrant) and on production.

A: It is not a good practice to have scripts specific to an environment. Instead you should have scripts which will behave differently based on environment. Let me show you how; there are two steps you will need to do for this to work:

*

*Define environments

You will have to define environments - I would suggest directory based environments (Because config based environment support will be dropped eventually). How to setup environments is an intimate topic and I suggest you check out the documentation

*Use environments in your code

Let's say you have defined environments such as dev, qa, uat, prod etc. You can get the name of current environment by using $environment variable. Your manifests should leverage the environment variable to decide weather a firewall should be enabled/disabled etc. For example:
(Modified based on Felix's comment, thanks @Felix)
include profile::webserver
if $environment != 'dev'
    include profile::firewall

In above piece of code if the $environment does not match to "dev" only then the firewall role is applied!


text:
Q: Dada una fecha (dd-mm-aaaa), obtener el lunes de esa semana. En numero Estoy intentando crear una función con información de datapikcer pero no encuentro la forma de hacerlo.
Dada una fecha, por ejemplo: (01-09-2017), saber cual es el lunes de esta semana¿?
En este caso me tendría que devolver (28-08-2017). (Que sería una caso especial por que el lunes de esta semana corresponde al mes anterior).
Pero un caso normal sería por ejemplo si le paso a la función (06-09-2017), me tendría que devolver (04-09-2017) que es del mismo mes y es el lunes correspondiente a esa semana y a esa fecha.

A: Pues tomando en cuenta que el día domingo es el primer día de la semana, podrías hacer un poco de matemáticas para que te pueda salir el resultado que desees. Te dejo algo de codigo para que puedas revisarlo.

fecha1 = new Date("2017-09-01");
dias1=(fecha1.getUTCDay()-1)*(-1);
fecha1.setDate(fecha1.getDate() + dias1);
console.log("Lunes de la semana:");
console.log(fecha1);

Y si en caso tomas en cuenta el lunes como el primer día de la semana, entonces :

fecha1 = new Date("2017-09-03");
diapararestar=fecha1.getUTCDay();
if(diapararestar==0){
    dias1=(-6);
}else{
    dias1=(diapararestar-1)*(-1);
}

fecha1.setDate(fecha1.getDate() + dias1);
console.log("Lunes de la semana:");
console.log(fecha1);

Bueno espero que el código te sirva.


text:
Q: AngularJS node mongodb auth issue using token auhenticaton I'm studying AngularJS Node and MongoDB, I got a great Video Tutorial from the Internet.  and as I'm getting to the late chapters, I've got stuck in one of the sample applications, that doesn't seem to work.
Error while Login

Possibly unhandled rejection: {"message":"User have no token"}

My code is as follows.
CONTROLLER
mainController.js
angular.module('mainCtrl',[])
.controller('MainController',function($rootScope, $location, Auth){

    var vm = this;

    vm.loggedIn = Auth.isLoggedIn();

    $rootScope.$on('$routeChangeStart',function(){
        vm.loggedIn = Auth.isLoggedIn();

        Auth.getUser()
            .then(function(data){
                vm.user = data.data;
            })
            .catch(function (err) {});
        });

    vm.doLogin = function(){
        vm.processig = true;

        vm.err = '';

        Auth.login(vm.loginData.username,vm.loginData.password)
            .then(function(data){
                vm.processig = false;

                Auth.getUser()
                    .then(function(data){
                        vm.user = data.data;
                    });

                if(data.success)
                    $location.path('/');
                else
                    vm.error = data.message;
            });
    }

    vm.doLogout = function(){
        Auth.logout();
        $location.path('/logout');
    }

});

SERVICE
authServices.js
angular.module('authService',[])

.factory('Auth',function($http, $q, AuthToken){

    var authFactory = {};

    authFactory.login= function(username,password){
        return $http.post('/api/login',{
            username:username,
            password:password
        })
        .then(function(data){
            AuthToken.setToken(data.token);
            return data;
        });
    }

    authFactory.logout = function(){
        AuthToken.setToken();
    }

    authFactory.isLoggedIn = function(){
        if(AuthToken.getToken())
            return true;
        else
            return false;
    }

    authFactory.getUser = function(){
        if(AuthToken.getToken())
            return $http.get('/api/me/');
        else
            return $q.reject({message:"User have no token"});
    }
    return authFactory;
});

.factory('AuthToken', function($window){

    var authTokenFactory = {};

    authTokenFactory.getToken =  function(){
        return $window.localStorage.getItem('token');
    }

    authTokenFactory.setToken = function(token){
        if(token)
            $window.localStorage.setItem('token', token);
        else
            $window.localStorage.removeItem('token');
    }
    return authTokenFactory;
})

.factory('AuthInterceptor',function($q,$location,AuthToken){
    var interceptorFactory = {};

    interceptorFactory.request = function(config){
        var token = AuthToken.getToken();
        if(token){
            config.headers['x-access-token'] = token;
        }

        return config;
    };

    interceptorFactory.responseError = function(response){
        if(response.status == 403)
            $location.path('/login');

        return $q.reject(response);
    }

    return interceptorFactory;
});

what I'm missing..??
check my  Projec Here


text:
Q: using `$router.push` when validating a dynamic route I am using Nuxt and I have created a have a dynamic route which fetches data using vuex and an axios call. I want to route the user back to index when no id params are specified. I see that i can use validate on dynamic routes https://nuxtjs.org/api/pages-validateWhen
I am using the code below, when I navigate to localhost:3000/settings/ i get the following error Cannot read property 'push' of undefined
pages/settings/_id.vue
export default {
  validate({ params }) {
    if (params.id !== null) {
      this.$router.push({ name: 'index' })
    }
    return false
  }
}

A: The validate is called every time before navigating to a new route. It will be called server-side once. This means the validate is executed before your component is created. So you can't access this.$router because this dont exist at this time.
Take a look in Fetch Hook and Nuxt Lifecycle to better explanations:
https://nuxtjs.org/blog/understanding-how-fetch-works-in-nuxt-2-12/#fetch-hook-and-nuxt-lifecycle
Basiclly what we need to do is import the redirect and route from the nuxt context to use it insite or validate function. The ROUTE have all the informations about your request, and the redirect is a function from nuxt is used inside middlewares.
I have created a exemple to you:
<template>
  <v-row>
    <v-col cols="12">
      <pre>
        {{ params }}
      </pre>
    </v-col>
  </v-row>
</template>

<script>
export default {
  data() {
    return {
      params: []
    }
  },
  validate({ redirect, route }) {
    if (route.params) {
      // eslint-disable-next-line no-console
      console.log('RouteParams:', route.params)
      this.params = route.params
    }
    redirect({ name: 'index' })
    // return false
  }
}
</script>


text:
Q: How to get text with line breaks that match the browser view rather than the html source (using python and beautifulsoup) When I use the get_text() function from the BeautifulSoup module in Python it returns text with line breaks that match the HTML source.
However, I want the line breaks to mimic what you would see in a browser (for example, ignore line breaks in the HTML source, one line break for a
 tag, two line breaks between
 tags).
from bs4 import BeautifulSoup

some_html = """
Some
sample html

new line

New paragraph"""

plain_text = BeautifulSoup(some_html,"html.parser").get_text()

Expected result:
Some sample html
new line

New paragraph

Actual result:
Some
sample html
new line
New paragraph

A: I ended up using a few substitutions. It worked for the HTML I was working with.
from bs4 import BeautifulSoup

sample = """
Some
sample html

new line

New paragraph"""

# Remove all line breaks in the source
sample_remove_line_breaks = re.sub(r'\r?\n', ' ', sample)

# Add line breaks for each `<br>` and `<p>` tag
sample_add_html_line_breaks = re.sub(r'
', '\n\n
', re.sub(r'
', '
\n', sample_remove_line_breaks))

plain_text = BeautifulSoup(sample_add_html_line_breaks,"html.parser").get_text()


text:
Q: ViewPager2 + FragmentStateAdapter + offscreenPageLimit = 1 => onResume not called I'm having an issue with my ViewPager, but I don't know why and how to fix it.
So I have a ViewPager2 on which I'm using a FragmentStateAdapter.
This pager contains approx 10 pages (not really important).
On that ViewPager, I also have
viewPager.offscreenPageLimit = 1

From what I understood, when using ViewPager2 + FragmentStateAdapter, onResume should be called on the visible fragment whenever the selected page changes.
However:

*

*Fragment 1 -> Fragment 2 => onResume/onPause not called

*Fragment 2 -> Fragment 3 => onPause called on Fragment 1 and onResume called on Fragment 3

*Fragment 3 -> Fragment 4 => onPause called on Fragment 3 and onResume called on Fragment 4

*And so on.

So the issue here is onResume is not called on Fragment 2 when I go from Fragment 1 to Fragment 2.
If I remove
viewPager.offscreenPageLimit = 1

Then this fixes the issue.
However, I don't understand why...
Is it normal? Is it a bug?
Am I missing something?
Thank you guys in advance.


text:
Q: How to use inner join and left join for two tables in same query using T-SQL Given two tables:

*

*tblBase - database table (code_no, empid)

*@type_temp is a temporary user defined table which will come from vb.net frontend (code_no, name)

Firstly I need to get code_no which are in @type_temp and not in tblBase.
Query:
select
    t.code_no, 'Non-existing' as Remark
from
    @type_temp t
left join
    tblBase b on t.code_no = b.code_no
where
    b.code_no is null

Next I need to get all code_no that have empid = 1.
Query :
select
    t.code_no, 'Existing' as Remark
from
    @type_temp t
inner join
    tblBase b on t.code_no = b.code_no
where
    b.empid = 1

I need to use both these queries together.
Currently I'm using union to club the two.
select
    t.code_no, 'Non-existing' as Remark
from
    @type_temp t
left join
    tblBase b on t.code_no = b.code_no
where
    b.code_no is null

union

select
    t.code_no, 'Existing' as Remark
from
    @type_temp t
inner join
    tblBase b on t.code_no = b.code_no
where
    b.empid = 1

I do not want union here. Any other alternative possible?

A: Does this work for you?
SELECT type_temp.code_no
     , CASE WHEN tblBase.code_no IS NULL THEN 'Non-existing' ELSE 'Existing' END AS Remark
FROM   @type_temp AS type_temp
 LEFT
  JOIN tblBase
    ON tblBase.code_no = type_temp.code_no
WHERE  tblBase.empid = 1
OR     tblBase.code_no IS NULL
;

A: An even better option than @gvee's answer, is to put the conditions into the ON clause
SELECT
  type_temp.code_no,
  CASE WHEN tblBase.code_no IS NULL THEN 'Non-existing' ELSE 'Existing' END AS Remark
FROM @type_temp AS type_temp
LEFT JOIN tblBase ON tblBase.code_no = type_temp.code_no
    AND tblBase.empid = 1;

This is likely to be more performant, as the join is pre-filtered.


text:
Q: Get the value of Select dropdown list when the value sent by the form and that appearing in the dropdown list are different I have a form which has the following Select dropdown list.
<select name="some_options" id="some_options">
@foreach(options as option)
<option value="{{$option->id}}">{{$option->value}}</option>
@endforeach
</select>

Here , the data are being sent from the database via the Controller
The Select data look like this
<select name="some_options" id="some_options">
<option value="opt001">Value 1</option>
<option value="opt002">Value 2</option>
<option value="opt003">Value 3</option>
<option value="opt004">Value 4</option>
<option value="opt005">Value 5</option>
</select>

Now, I have another disabled field which should get the value once the user changes the select option

<input type="text" id="some_options_cng" disabled>

My Javascript code
 var opt = $('#some_options').val();

$('#some_options').on('change',function(){

opt = $('#some_options').val();

$('#some_options_cng').val(opt);

});

Now, the value in the <disabled> input field shows as
opt001 or opt002 and so on.
I want to show values as
Value 1 or   Value 2.
How do I do it?

A: This code will work.
$('#some_options').change(function(){
        var opt = $("#some_options").find(":selected").text(); //This line of code is
                                                               //important
        $('#some_options_cng').val(opt);
      })

$(document).ready(function(){
  $('#some_options').change(function(){
    var opt = $("#some_options").find(":selected").text();
    $('#some_options_cng').val(opt);
  })
});

<select name="some_options" id="some_options">
<option value="opt001">Value 1</option>
<option value="opt002">Value 2</option>
<option value="opt003">Value 3</option>
<option value="opt004">Value 4</option>
<option value="opt005">Value 5</option>
</select>

<input type="text" id="some_options_cng" disabled>


text:
Q: Find c of linear combinations in non vector form? $i + cj - 3k$ is a linear combination of $i + j$ and $j + 3k$.
How do I do this question, if it's not in vector form?
Should my approach be
$i + cj - 3k = a(i + j) + b(j + 3k)$?

A: Starting with
$$\mathbf{i} + c\mathbf{j} - 3\mathbf{j} = a(\mathbf{i} + \mathbf{j}) + b(\mathbf{j} + 3\mathbf{k})$$
you should solve for $a$ and $b$. You can say that all the coefficients of $\mathbf{i}$ on the right side should equal all the coefficients of $\mathbf{i}$ on the right side, same with $\mathbf{j}$ and $\mathbf{k}$. This gives you a system of equations.
$$
\begin{aligned}
1 &= a\\
c &= a + b\\
-3 &= 3b\\
\end{aligned}
$$
This gives $a = 1, b = -1, c = 1 + -1 = 0$. So the linear combination we're talking about here is just negating the second vector and adding it to the first.

A: Your approach is correct. We take $${\bf i} + c{\bf j} - 3{\bf k} = a({\bf i} + {\bf j}) + b({\bf j} + 3{\bf k}) = a{\bf i} + (a + b){\bf j} + 3b{\bf k}$$
We may equate coefficients to observe that $a = 1$ and $3b = -3 \;\;\Rightarrow\;\; b = -1$. So $c = a + b = 1 + (-1) = 0.$