text:
Q: how to write a big string in a file in unix from shell terminal I have a string like below which is a very big
http://i.imgur.com/4QjOLKC.png <-- it gets stuck like this on pasting the command
$str="Hello this question is related to print a big line in a Unix file. this line is very long having more than 300 characters inside it. When I am running the below commands its failing because on a Unix session if we paste big commands it does not get pasted properly";

echo "Hello this question is related to print a big line in a Unix file. this line is very long having more than 300 characters inside it. When I am running the below commands its failing because on a Unix session if we paste big commands it does not get pasted properly" > file.txt

this command is failing, also I tried
cat > file.dat <<_EOF_  "Hello this question is related to print a big line in a Unix file. this line is v.....aste big commands it does not get pasted properly"
_EOF_

But it's not successful. Screen is getting stuck since the full line is too big
I tried few options from
http://www.guguncube.com/2140/unix-set-a-multi-line-text-to-a-string-variable-or-file-in-bash
but did not worked

A: If you are on bash, first execute:
shopt -s checkwinsize

Then:
str=$(cat <<EOF
"Hello this question is related to print a big line in a Unix file. this line is very long having more than 300 characters inside it. When I am running the below commands its failing because on a Unix session if we paste big commands it does not get pasted properly"
EOF
)

To direct insert in file:
cat <<EOF >file.txt
"Hello this question is related to print a big line in a Unix file. this line is very long having more than 300 characters inside it. When I am running the below commands its failing because on a Unix session if we paste big commands it does not get pasted properly"
EOF

If every thing fails broke the line in pieces using the escape char.
cat <<EOF >file.txt
"Hello this question is related to print a big line in a Unix file. this \
line is very long having more than 300 characters inside it. When I am \
running the below commands its failing because on a Unix \
session if we paste big commands it does not get pasted properly"
EOF

Check: http://tldp.org/LDP/abs/html/here-docs.html


text:
Q: Netsuite send an email alert for picking tickets that need to be printed There has to be a better way than having to keep refreshing the print picking ticket page.
I want to get an email alert when a new picking ticket needs to be printed. We do not have WMS or any third-party add-on.

A: Given the url you specified (...accounting/print/printform.nl?printtype=pickingticket&trantype=salesord&method=print&title=Picking+Tickets&whence=#) the picking status (whether or not one needs to be printed) seems to be tied to Sales Orders.  Creating a Transaction saved search and enabling emails to be sent with attached results should meet your requirements.
Saved search criteria:
Type = Sales Order
Main Line = true
To Be Printed = true OR Printed Picking Ticket = false (depending on your use case)

Results:
Add all the column data you'd like to see.  If you want to include a link to print the actual ticket.  Navigate to the print screen in the UI and take note of the url, it is likely standard url with "&id=XXX" to specific which record to print.  You can created the following Formula (Text) to house the url = '<a href=https://XXXX.netsuite.com/....?id='|| {internalid} ||''
Reference Answer Id 8487 for more on Saved search Emails.

redpajama_set_name: RedPajamaStackExchange


text:
Q: html disabled textfield should allow changes made by javascript i have a textfield which should be disabled for user-actions but should be filled by a javascript after another user-action. Is this somehow possible?
It can be a solution made by js, css or even html.

A: Without some code to illustrate your situation it's difficult to say for sure, but something like this might suffice:

function updateTextbox() {
  document.getElementById('text').value = 'Value updated through JavaScript'
}
<input id="text" type="text" disabled="disabled"  />

<button id="update" onclick="updateTextbox()">Update Textbox</button>

Adding disabled="disabled" to your input will disable it from user input, but can still be changed through javascript.
EDIT: If you want to change the value through a click on the element (as suggested in comments) this is a little more difficult as elements do not trigger click events when disabled. We can however use an invisible element in front of the input as a work-around:

function update() {
  document.getElementById('textbox').value="Updated from hidden element click!"
}

  <input type="text" id = "textbox" disabled="disabled" style="width: 250px; height: 20px;"/>

A: Your field
<input type="text" id="text1" name="text1" readonly>

readonly mean the value is not null and the field not changeable. Whereasdisabled might causing the input value being null.
And your javascript is like this
function changeVal(myval){
     document.getElementById('text1').value = myval;
}

Complete Fiddle http://jsfiddle.net/yuk0mcrx/

A: HTML
<input id="myText" type="text" value="Hello">

JS
document.getElementById("myText").disabled = true;
document.getElementById("myText").value = "Yes, Changed!";

In JS you can make whatever changes you want to make and you can trigger it on any user action.
Fiddle


text:
Q: 'Add Service Reference' not working with Azure AppFabric ServiceBus June 2011 CTP I have a computer with no AppFabric sdks installed (neither V1 or V2 CTP). I added a reference to the Microsoft.ServiceBus dll (June 2011 CTP version). When I try to add a Service Reference to Azure Service running locally, I get this error:

Could not load file or assembly 'Microsoft.ServiceBus,
  Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or
  one of its dependencies

I'm not sure why is it trying to get version 1. I even got service model extensions on the web.config and machine.config pointing to version 2.
Any help would be greatly appreciated.

A: Found the problem. I had some machine.config entries still pointing to version 1. Specifically on the policyImporters node. I just changed them to version 2 and it worked!


text:
Q: `git push` automatically closes my `arc diff` I'm stuck on a problem where pushing my code to a remote branch automatically closes my diffs. An example:

*

*I have a diff, say DXXXXXX

*I want to take all the changes in that diff push them to a new branch, say test-branch

*After running git push origin +test-branch:test-branch, Phabricator closes DXXXXXX
Why does this happen?
How can I decouple my diff away from pushing code to a new branch?
I tried to create a brand new git history, so that the test-branch commits have no overlap with the Diff, but that didn't work. Somehow Phabricator still associates the 'new commits' with the old diff :(


text:
Q: Changing aspect ratio of Virtualbox VM under OSX I have a Windows guest on an OSX host, running at 1024x768.
I want to use scale-mode to make the window small enough to have on the side of my screen, but the problem is that since I maximised the VM in scale mode earlier, the aspect ratio is now nearer my 16:10.
I've tried resizing in only one dimension, disabling and re-enabling scale mode and also reinstalling guest additions.
A search of the Virtualbox docs does tell me that maintaining aspect ratio is doable under OSX, but it doesn't say how.
I'd really like to be able to fix this without reinstalling my VM if possible.
I'm running Virtualbox 4.2.16 r86992 under OSX 10.8.4 with a Window 7 guest.

A: The aspect ratio of the guest screen is preserved when resizing the window. To ignore the
aspect ratio, press Shift during the resize operation.
User manual


text:
Q: How to calculated a new column based on inputs in the same database I have a loan portfolio with several clients, each of which can be shown in the following table format.
DATE        DPD    DPD_BUCK    DATE_REST    RESTRUCTURED    REST_PERIOD
2017-03-01  90       90+       NULL             NO           NULL
2017-04-01  90       90+       NULL             NO           NULL
2017-05-01  2        0-29      2017-04-10       YES           1
2017-06-01  0         0        2017-04-10       YES           2
2017-07-01  0         0        2017-04-10       YES           3
2017-08-01  0         0        2017-04-10       YES           4
2017-09-01  0         0        2017-04-10       YES           5
2017-10-01  20       0-29      2017-04-10       YES           6
2017-11-01  51      30-59      2017-04-10       YES           7
2017-12-01  82      60-89      2017-04-10       YES           8
2018-01-01  90       90+       2017-04-10       YES           9
2018-02-01  90       90+       2017-04-10       YES          10
2018-03-01  90       90+       2017-04-10       YES          11
2018-04-01  90       90+       2017-04-10       YES          12

Column names
DPD = Number of overdue days on payments
DPD_BUCK = Risk bucket
DATE_REST = Date of restructuring of the loan
REST_PERIOD = Number of months since last restructuring

I need to add a new column (DPD_UPD) which will adjust the original DPD values based on whether the loan was restructured or not using the following logic:
CASE
WHEN REST_PERIOD = 1 or REST_PERIOD = 2 THEN DPD (value 1 month before restructuring)
WHEN REST_PERIOD = 3 AND DPD = 0 THEN DPD (value from the previous period less 29 days)
WHEN REST_PERIOD = 3 AND DPD <> 0 THEN DPD (value from the previous period plus 29 days)
WHEN REST_PERIOD = 4 AND DPD = 0 THEN DPD (value from the previous period less 29 days)
WHEN REST_PERIOD = 4 AND DPD <> 0 THEN (value from the previous period plus 29 days)
.
.
.

And so on until period 12, however, DPD cannot be less than 0 or more than 90.
The expected results should look like this:
DATE        DPD    DPD_UPD   DPD_BUCK      DATE_REST    RESTRUCTURED    REST_PERIOD
2017-03-01  90       90         90+            NULL             NO           NULL
2017-04-01  90       90         90+            NULL             NO           NULL
2017-05-01  2        90         0-29       2017-04-10          YES            1
2017-06-01  0        90          0         2017-04-10          YES            2
2017-07-01  0        61          0         2017-04-10          YES            3
2017-08-01  0        32          0         2017-04-10          YES            4
2017-09-01  0        3           0         2017-04-10          YES            5
2017-10-01  20       32         0-29       2017-04-10          YES            6
2017-11-01  51       61        30-59       2017-04-10          YES            7
2017-12-01  82       90        60-89       2017-04-10          YES            8
2018-01-01  90       90         90+        2017-04-10          YES            9
2018-02-01  90       90         90+        2017-04-10          YES           10
2018-03-01  90       90         90+        2017-04-10          YES           11
2018-04-01  90       90         90+        2017-04-10          YES           12

I would really appreciate it if someone could help.
Thx in advance

A: I've used the recursive CTE:
with
  r as (
    select top 1 DPD DPD_UPD, * from @lp order by [DATE]
      union all
    select
      case l.RESTRUCTURED
        when 'NO' then l.DPD
        else
          case
            when l.REST_PERIOD < 3 then
              coalesce((select DPD
                        from @lp i
                        where dateadd(mm,
                                datediff(mm, 0, l.DATE_REST) - 1,
                                0) = i.[DATE]), r.DPD_UPD)
            else
              iif(l.DPD = 0,
                  iif(r.DPD_UPD - 29 < 0, 0, r.DPD_UPD - 29),
                  iif(r.DPD_UPD + 29 > 90, 90, r.DPD_UPD + 29))
          end
      end,
      l.*
    from r join @lp l on dateadd(mm, 1, r.[DATE]) = l.[DATE]
  )
select * from r order by [DATE];

Here it is possible to test my attempt.
But a solution with a cursor can be more preferable in terms of performance.


text:
Q: Disable Utility PopOut functionality in an LWC component I have an LWC component which i am rendering in the utility bar in my lightening app.
In that component, i want to disable the pop-out option of the utility bar popup using javascript based on some user action.
I saw that in aura components i can use disableUtilityPopOut controller function to disable the popup functionality.
How can i achieve the same in my LWC component. is there any way to do that?
Please help.

A: Salesforce Console APIs (Navigation Item API, Workspace API, Utility Bar API) are not supported in LWC. To make it work in LWC, you can go with this approach:-
Use Lightning Message Service along with two separate components(An Aura Component and a Lightning Web Component). Aura Component will be used as a service component to provide Salesforce Console APIs (Navigation Item API, Workspace API, Utility Bar API) features to Lightning Web Component. The Lightning Web Component and Aura Component will be communicating with the help of Lightning Message Service.
Checkout a working example here:- SALESFORCE CONSOLE APIS (NAVIGATION ITEM API, WORKSPACE API, UTILITY BAR API) IN LIGHTNING WEB COMPONENT USING AURA AND LIGHTNING MESSAGE CHANNEL


text:
Q: Hem Build: Ignoring looking into old folders while building I am using hem to build my javascript application. It had been working fine since around 10 months. However, now Hem is ignoring looking into old folders in "node_modules" while building, and thus, "require"ing them isnt working.
If i rename the same folder, it is working fine.
eg,
If I have been using this inside node_modules:
footballField
containing, footballField.js
Hem is not able to access footballField.js  .
require('footballField/footballField')

is giving the error,
"Uncaught module 'footballField/footballField' not found"

however, if i rename footballField/footballField to footballField1/footballField everywhere,
it works smoothly.
Is there a way this can be explained?
Thanks :)


text:
Q: Use OpenCV matrix for OpenGL ES texture I am trying to write an AR application, so far I've used opencv for image warping and things, but warping video frames one by one is computationally expensive. Therefore I am trying to migrate to opengl for augmentation.
So far I tried to get camera frame data, convert it to opencv matrix in java part, and then create a texture from it in the native code. It kinda works, but there are some strange marks in the result :

as @Micka suggested , here is my code snippet:
java part :
public void onPreviewFrame(byte[] frame, Camera arg1) {
    mFrame.put(0, 0, frame);
    processFrame(mFrame.getNativeObjAddr());
}

native part :
JNIEXPORT void JNICALL Java_com_..._CameraPreviewer_processFrame( JNIEnv* env, jobject thiz, jlong addr)
    cv::Mat& mFrame = *(cv::Mat*)addr;
    cv::cvtColor(mFrame, buffer[(bI) % 30], cv::COLOR_YUV2BGR_NV21);
}

and onDrawFrame Renderer (native):
{
    ...
    cvtColor(buffer[(bI) % 30], frame, CV_BGR2BGR565);
    glTexSubImage2D(GL_TEXTURE_2D, 0, (1024-frameWidth)/2, (1024-frameHeight)/2, frameWidth, frameHeight, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, frame.ptr());
    ...
}


text:
Q: Apache error log: setrlimit(2) error message I am using a dedicated server managed by 1and1.co.uk (Apache, Linux). My website is running fresh WordPress 3.9, PHP 5, plain CGI is enabled (no Fast CGI).
I'm trying to resolve an error in my log file which is appearing thousands of times:

[info] [pid=7547 euid=0 egid=99] suexec.cpp(317): setrlimit(2): 2 set to  4294967295/4294967295 (soft/hard) bytes

At the exact same time as the above error appears, the following two warnings appear every time:

Cannot get media type from 'x-mapp-cgi'
Cannot get media type from'x-mapp-php4'

What does this error mean and what could be causing it?


text:
Q: Display user#show url as www.fb.com/usrname and www.usrname.fb.com instead of showing www.fb.com/123, in rails 4.2.6 I am trying to show username instead of user_id i.e., (users/4).
i have tried with changing routes file, model file as:
class User < ActiveRecord::Base
  def to_param
    username
  end
end

and routes file as:
get '/:username' => 'users#show'

on show action it must show as fb.com/username url.
thanks in advance.

A: You may use friendly_id gem for this. Here is Rails cast : Pretty URLs with friendly_id On how to use it. You can use the attribute/column you want in the URL.
With FriendlyId, it's easy to make your application use URLs like:
http://example.com/states/washington

instead of:
http://example.com/states/4323454


text:
Q: What is the main difference between RST (0-7) and RST (5.5-7.5) in microprocessor 8085? What's the main different between these two restart instructions?  On the first case they are 1 byte call instruction and next case, they are vectored interrupts but definitely they are also call instructions. Then why RST (0-7) can't be used as interrupts?  What's the underlying difference between them?
I think I am not able to build the concept of RST instructions and that's why asking this silly questions. Thank you so much for helping me.

A: There are four kinds of interrupts on the 8085.  The first three have dedicated interrupt pins: 5.5, 6.5, and 7.5.   So when an interrupt comes in, the processor can immediately go to the proper interrupt handler, by internally generating a RST x.5 instruction where x=5,6 or 7 as appropriate.
Then there is a shared interrupt pin, INTR.  In order for external devices to share this one pin, but at the same time have separate interrupt handlers for each one, there is mechanism whereby the external device places a RST instruction on the bus, along with an interrupt # 0-7.  Then it can vector to the appropriate routine.
So that is the main  difference between the two: for RST 5.5 through 7.5, the processor generates the RST instruction, and for interrupts 0-7 the external hardware does.


text:
Q: Layout Page not rendering Some Pages Asp.net MVC5 i am trying to develop MVC5 applicaiton. i am facing a problem. i have set a layout page placed in shared folder. Home pages of all controls are working properly.

but other pages are not showing in proper way.
I have attached a sample page Details

I checked css is also showing in source but page is not displaying in proper way

Thanks in advance. i am new in MVC

A: If you open your browser's Developer Toolbar and review the network tab you should be able to see if your pages are returning 404 for the files.  When your browser is open press F12 and the toolbars should open.
It looks to me like your references to your local/application based stylesheets/javascript are missing the tilde symbol ~ at the beginning which means in ASP.NET the server-side application root.
For example ~/Content/bootstrap.css would be translated to the URL of the bootstrap.css file that's in the application's root.
You can drag and drop the bootstrap.css file in your content file into the _layout.cshtml file to see the correct path for the href attribute.

A: Put the sympole ~ before the link of css path


text:
Q: $scope.my_model equivalent in angular2? I'm newbie in angular2. Just want to know how to:

*

*read [(ngModel)] from view on the typescript controller side

Let say:
<input type="text" [(ngModel)]="my_model" />

Now, how I want to read the model value in my typescript controller?
The other one is how to set value of the input as '' to my [(ngModel)]?
Example of codes:
View:
<input type="text" [(ngModel)]="my_model" />
<br/>
<button (click)="submit()">Submit</button>

Controller (Typescript)
submit(){
   ... //Then? if angularjs 1 just use $scope.my_model ...
   $scope.my_model = ''; //Only valid for angularjs1
}

Help me please... thanks!

A: The components class is the model
submit() {
 this.my_model = ''
}


text:
Q: I don't imagine how to make a cartesian equation of the parametric one: $x=2 \sin (t), y=-\frac{4\cos (t)^2 (2 + 1.3\cos(t))}{3 + \sin (t)^2}$ I know it's a downvoting question but I'm not good at math. I know that $x=a \sin(t)$ , $y=\frac{a \cos^2(t)(2+ \cos(t))}{(3- \sin^2(t))}$ is $y^2(a^2-x^2)=(x^2+2ay-a^2)^2$ but what it could be as a cartesian equation with the negative $y$ part I can't even imagine. Sorry. Could you help me?

A: $$y=-\frac{4 \cos ^2(t) \left(\frac{13 \cos (t)}{10}+2\right)}{\sin ^2(t)+3}$$
$$\sin t=\frac{x}{2}$$
thus
$$y=-\frac{4 \left(1-\frac{x^2}{4}\right) \left(\frac{13 \cos (t)}{10}+2\right)}{\left(\frac{x}{2}\right)^2+3}$$
with some algebra we get
$$\cos t=\frac{5 \left(x^2 y-8 x^2+12 y+32\right)}{26 \left(x^2-4\right)}$$
and then
$$\cos^2 t=\left(\frac{5 \left(x^2 y-8 x^2+12 y+32\right)}{26 \left(x^2-4\right)}\right)^2$$
as $\cos^2 t= 1-\sin^2 t$ we get
$$1-\frac{x^2}{4}=\left(\frac{5 \left(x^2 y-8 x^2+12 y+32\right)}{26 \left(x^2-4\right)}\right)^2$$
and finally
$$676 \left(x^2-4\right)^2=25 \left(x^2 y-8 x^2+12 y+32\right)^2+169 x^2 \left(x^2-4\right)^2$$

A: $$x=2 \sin (t), ~~~~y=-\frac{4\cos (t)^2 (2 + 1.3\cos(t))}{3 + \sin (t)^2}$$
There's a very useful trigonometric identity:
$$\sin^2\theta+\cos^2\theta\equiv1$$
where the $\equiv$ symbol (the identity symbol) means the equation is true for all values of $\theta$; that's why it's called an identity. In your case, we know that
$$\sin t=\frac{x}{2}$$
Using the above identity,
$$\cos ^2t=1-\sin^2 t=1-\frac{x^2}{4}=\frac{4-x^2}{4}$$
Also,
$$\cos t=\sqrt{\frac{4-x^2}{4}}=\frac{\sqrt{4-x^2}}{2}$$
(The final equality assumes that $\cos t$ is $+$ve. In fact to be completely correct you should use $\cos t=\pm\frac{\sqrt{4-x^2}}{2}$. Thanks for spotting that @GEdgar.)
Try substituting these values into your equation. If you need more help, don;t hesitate to ask!


text:
Q: Spliting string, flatMapping it and creating objects using Java streams? I have 2 classes going like this:
public class Seat extends Moviefiable {

        private int number;
        private Hall hall;

        public Seat(int id, boolean active, int number, Hall hall) {
            super(id, active);
            this.number = number;
            this.hall = hall;
        }

        public Seat() {this(-1, false, -1, null);}

        public static Seat getById(int idSeat) throws SQLException {
            Seat seat = SeatDAO.getById(idSeat);
            return seat;
        }
}

public class Ticket extends Moviefiable {

private Projection projection;
private Seat seat;
private LocalDateTime purchasingDate;
private User user;

public Ticket(int id, boolean active, Projection projection, Seat seat, LocalDateTime purchasingDate, User user) {
    super(id, active);
    this.projection = projection;
    this.seat = seat;
    this.purchasingDate = purchasingDate;
    this.user = user;
}

public Ticket() {this(-1, false, null, null, null, null);}

Now, I need to create two or more Tickets, depending how many tickets loggedInUser chooses. From my JSP page, I'll get something like this:
String uri = request.getQueryString(); //uri looks like this: seats=2&seats=3

I want to create two Ticket objects for two Seat objects. In uri string, chars 2 and 3 are primary keys for seats.
The idea is to use Java streams to perform splitting and creating objects. This is I have so far.
ArrayList<Ticket> newTicketsForSeats = Stream.of(uri.split("&"))
                   .map(s -> s.split("seats=")[1])
                   //.flatMap(Arrays::stream)
                   .mapToInt(Integer::valueOf)
                   .mapToObj(s -> {
                    try {
                        return new Ticket(-1, true, projection, SeatDAO.getById(s),
                                 LocalDateTime.now(), loggedInUser);
                    } catch (SQLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        return null;
                    }
                })
                   .collect(Collectors.toCollection(ArrayList::new));

When I made a test, like this to see the output I'm getting:
Stream.of(uri.split("&"))
    .map(s -> s.split("seats=")[1])
    .mapToInt(Integer::valueOf)
    .forEach(System.out::println); //2 3

Which is okey. But when I run code above, I got:
java.lang.ArrayIndexOutOfBoundsException: 1
at servlets.ConfirmPurchaseServlet.lambda$0(ConfirmPurchaseServlet.java:62)
at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
at java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:948)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:482)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:472)
at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)

projection is also object, which I obtained, this is just reference, it is elsewhere in servlet. loggedInUser I got from session. I'm newbie regarding Java streams, any additional explanation would be excellent.
I get that map() requires IntUnaryOperator lambda expression, something like this:
s -> s * 10

I don't know how to "map" from int (primary key for Seat) to Seat object.
Cheers.

A: Your main problem is that you are trying to assign the stream output to an ArrayList.  Collectors.toList() returns a List that cannot be expected to be a particular implementation.
So either do this:
List<SomeClass> list = ...collect(Collectors.toList());

or this
ArrayList<SomeClass> list = ... collect(Collectors.toCollection(ArrayList::new));

The following should work but it may need some tweaking based on your other classes.
ArrayList<Ticket> newTicketsForSeats = Stream.of(uri.split("&"))
               .map(s -> s.split("seats="))
               .flatMap(Arrays::stream)
               .mapToInt(Integer::valueOf)
               .mapToObj(s -> new Ticket(-1, true, projection, SeatDAO.getById(s),
                     LocalDateTime.now(), loggedInUser))
               .collect(Collectors.toCollection(ArrayList::new));

A: Either of these would probably work:
List<Ticket> newTicketsForSeats = Stream.of(uri.split("&"))
        .map(s -> s.replace("seats=", ""))
        .mapToInt(Integer::valueOf)
        .mapToObj(s -> new Ticket(-1, true, projection, SeatDAO.getById(s), LocalDateTime.now(), loggedInUser))
        .collect(Collectors.toList());

or
List<Ticket> newTicketsForSeats = Stream.of(uri.split("&"))
        .map(s -> s.replace("seats=", ""))
        .map(s -> new Ticket(-1, true, projection, SeatDAO.getById(Integer.valueOf(s)), LocalDateTime.now(), loggedInUser))
        .collect(Collectors.toList());

BTW: you don't seem to have a Ticket constructor which matches the signature:
Ticket(int, boolean, Projection, Seat, LocalDateTime, boolean)


text:
Q: JDBC transaction not getting rolled back - setAutoCommit(false) This is typical project structure, a DB connection is created once user login to application.
Login.java{

    Creating DB Connection

    DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
    java.sql.Connection conn = DriverManager.getConnection(url, strUserDB, strPasswordDB);
    CustomSession customSession = new CustomSession();
    customSession.setConnectionDB(conn);
}

CustomSession.java{
    private Connection      conDBConnection;
    // getter, setter
}

SubmitAction{

method1(ActionMapping map,
            ActionForm form, HttpServletRequest request,
            HttpServletResponse response)

    Connection conDB = null;
    CustomSession customSession = null;

    AService aservice = null;
    BService bservice = null;
    CService cservice = null;

    HttpSession session = request.getSession(false);
    try{
            customSession = (Connection) session.getAttribute("customSession");
            conDB = objOFSession.getDBConnection();
            conDB.setAutoCommit(false);
            aservice = new AService(conDB);
            bservice = new BService(conDB);
            cservice = new CService(conDB);

            aservice.method2();
            bservice.method3();
            cservice.method4(); // Exception comes, and commit is never executed

            conn.commit();

    }catch(Exception e){
        conDB.rollback();
    }

Every service (*aservice, bservice, cservice) typically has not DB Connection and execute stored procedures.
SP's are like doing Select, update, insert operations.
query = conConnectionDB.prepareCall(strCommand);
        query.execute();
        query.close();
          if(errCode != 0){
            throw new Exception(errCode,errorDesc);
          }

}

Problem
I can see Stored Procedure return me error code other than 0, so it goes inside my if condition and throws exception. I am catching Exception and calling rollback(), but as i see none of the changes are rolled back. My transaction moves ahead.
Also i have verified SP's does not contain commit statements.
Neither in Java code commit statement is getting executed, since exception is thrown.
I have also set AutoCommit(false) in the starting.
Please let me know as how can i trouble shoot this further.

A: Quoting from Oracle documentation

A database transaction consists of ...
...
One data definition language (DDL) statement

I.e. after issuing a DDL statement e.g. CREATE TABLE statement all changes done before are commited and the ROLLBACK has no effect on them.
Illustration example
SQL> insert into test(x) values(1);

1 row created.

SQL>
SQL> create table tmp (x number);

Table created.

SQL>
SQL> rollback;

Rollback complete.

SQL>
SQL> select * from test;

         X
----------
         1


text:
Q: Weird objective-c syntax - square brackets and @ sign I'm using GHSidebarNav in one of my projects and I came across this code allocating an array of objects. I just have no idea what its doing. Is it just an array? What is this weird @[...] syntax? I have not seen that before:
NSArray *controllers = @[
    @[
        [[UINavigationController alloc] initWithRootViewController:[[GHRootViewController alloc] initWithTitle:@"Profile" withRevealBlock:revealBlock]]
    ],
    @[
        [[UINavigationController alloc] initWithRootViewController:[[GHRootViewController alloc] initWithTitle:@"News Feed" withRevealBlock:revealBlock]],
        [[UINavigationController alloc] initWithRootViewController:[[GHMessagesViewController alloc] initWithTitle:@"Messages" withRevealBlock:revealBlock]],
        [[UINavigationController alloc] initWithRootViewController:[[GHRootViewController alloc] initWithTitle:@"Nearby" withRevealBlock:revealBlock]],
        [[UINavigationController alloc] initWithRootViewController:[[GHRootViewController alloc] initWithTitle:@"Events" withRevealBlock:revealBlock]],
        [[UINavigationController alloc] initWithRootViewController:[[GHRootViewController alloc] initWithTitle:@"Friends" withRevealBlock:revealBlock]]
    ]
];

A: These are array literals, a type of container literal, available in Xcode 4.4 and later.
See:

*

*"Literal syntax" section of the discussion of arrays in the Programming with Objective C

*Objective-C Literals discussion at the LLVM site

*WWDC 2012 Modern Objective-C, about 19-20 minutes into it

*WWDC 2012 Migrating to Modern Objective-C

A: That's a new objective C literal that is declaring a multi dimensional array.
It's replacing [NSArray arrayWithObjects:[NSArray arrayWithObjects:...], [NSArray arrayWithObjects:..]]];


text:
Q: Suggestion for rewriting query I have a table(TABLEA) with 1 million of records and records are populated from multiple sources into this table(TABLEA).
once data is populated the records processed by downstream.
Whenever data is inserted the value of the column FLAG will be null and once its processed by down stream
the value of the FLAG will be updated as Y.
So basically I have requirement to check before records getting processed by downstream.
Requirement is that for already processed records in TABLEA(FLAG='Y') and CODE='I',  I need to check
is there any other records with same value for COLB  where the FLAG is null. If its there I want to change the CODE='D'(which means marked for delete) and FLAG=NULL
I write a merge for this and its taking like 3 hours to
run. I tried with explain plan and it didnt show me any recommendation. So is there anwyay to rewrite this query.
MERGE INTO TABLEA SRC
using
(select COLB from TABLEA where FLAG IS NULL) TGT
on(SRC.COLB=TGT.COLB and SRC.FLAG is not null and SRC.CODE='I')
when matched then update set
CODE='D',FLAG = NULL;
commit;

This is my input record and before executing the merge query query
COLA     COLB  CODE FLAG
 -------------- --------- ---- ----
 10001   3060   I    Y
 10002   3548   I    Y
 10003   3566   I    Y
 10004   5093   I    Y
 10005   3548   I    Y
 10008   3060   I    NULL

My output should look like something below. Here the COLB value is same for first record(already processed) and last record(yet to process), so after the merge query
this is how the TABLEA looks like
COLA     COLB  CODE FLAG
 -------------- --------- ---- ----
 10001   3060   D    NULL
 10002   3548   I    Y
 10003   3566   I    Y
 10004   5093   I    Y
 10005   3548   I    Y
 10008   3060   I    NULL

A: You can use the following UPDATE statement:
update tablea a
set code = 'D', flag = null
where flag = 'Y' and code = 'I'
  and exists (
    select 1 from tablea b where b.colb = a.colb and b.flag is null
  );

In order to [substantially] improve the performance you can create the following indexes:
create index ix1 on tablea (flag, code);

create index ix2 on tablea (colb, flag);

A: You could have a speed up when the indexes contains all the 3 fields, so db2 can make index scans for the search and needs to read/write on the tablespace only when an update is needed.


text:
Q: Nested php includes get commented out I've written a simple function to switch languages on my site.
domainname.com/minis/ is my regular blog
domainname.com/minis-eng/ is the english version
Here's the switcher, it works alright:
<?php
echo 'Polski';
    }
else
    {echo '/', basename(getcwd()), '-eng/', basename($_SERVER['PHP_SELF']), '">English';}
?>

Now when I place it in an external php and include it in the main index.php- it works alright too. However, I'm using a couple of external .php files to place repeated elements. So index.php looks more or less like this:

*

*include head.php

*include body.php (this contains the navigation menu)

*main content

*include footer.php

Now I'd love to place langswitcher.php in my root directory, and then place this in my body.php:
<?php
define('ROOT', dirname(__FILE__));
include (dirname(ROOT). '/langswitcher.php');
?>

However, apparently the php including code in an included .php doesn't get parsed- in the final result this part is simply written as is and commented out.
Is there anything I can do to make this "included include" get parsed?
Thanks in advance for your help and do let me know if I wasn't clear anywhere.


text:
Q: Cannot retrieve windows product key using VBA - Automation Error The following code throws an 'Automation Error'
Sub GetWindowsProductKey()

Set WshShell = CreateObject("WScript.Shell")
MsgBox WshShell.RegRead("HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\DigitalProductId")

End Sub

But this code works fine
Sub GetPath()

Set WshShell = CreateObject("WScript.Shell")
MsgBox WshShell.RegRead("HKEY_CURRENT_USER\Environment\Path")

End Sub

Clearly this has something to do with the product key being protected or something.
I'm writing a spreadsheet to collect auditing data from remote offices before anyone assumes I'm (really bad at) hacking.

UPDATE
I'm now trying the following approach, but I'm getting a type mismatch error instead on the second function (the first one still works) ...
Sub GetPathUsingStdRegProv()

Const HKEY_CURRENT_USER = &H80000001

strComputer = "."

Set oReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\default:StdRegProv")

strKeyPath = "Environment"
strValueName = "Path"

oReg.GetStringValue HKEY_CURRENT_USER, strKeyPath, strValueName, strValue

MsgBox strValue

End Sub

Sub GetWindowsKeyUsingStdRegProv()

Const HKEY_LOCAL_MACHINE = &H80000002

strComputer = "."

Set oReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\default:StdRegProv")

strKeyPath = "SOFTWARE\Microsoft\Windows NT\CurrentVersion"
strValueName = "DigitalProductId"

oReg.GetBinaryValue HKEY_LOCAL_MACHINE, strKeyPath, strValueName, strValue

For i = LBound(strValue) To UBound(strValue)
    MsgBox strValue(i)
Next

End Sub

strValue is Null in the second function, which explains the type mismatch!!

Update 2
I've use the code from this SO question, along with
ShellRun("wmic path softwarelicensingservice get OA3xOriginalProductKey")

which works on my laptop, but not on one of the desktops, presumably because the key isn't stored in BIOS/UEFI. So I'm still looking for a solution!

update 3
I've executed the code in the answer below as a vbs script, but the value I get on my laptop is different to the one i got from wmic technique above?! Is that a 64-bit issue? This is all very confusing!!


text:
Q: How to retrive each data of map object inside of firestore document for WEB I am trying to fetch data from firestore for a react application. But I am not getting how to show each data from a map object which is inside a document
My firestore database structure
The code I have written in react
the result I am getting
Please explain me as simple as possible


text:
Q: C# application- how to display a website inside a xaml form? I am trying to add a web browser to an existing C# application, but, having not used C# in about 6 years, I am quite unfamiliar with how it works.
The GUI for the application has been created using XAML, and I want to use this to add/ embed the web browser within the application, but I'm not sure how to do this.
I have the following script inside my WebBrowser.xaml class:
<Window x:Class="RiviamAgent.WebBrowser"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:RiviamAgent"
    mc:Ignorable="d"
    Title="WebBrowser" Height="500" Width="500">
<Window.CommandBindings>
    <CommandBinding Command="New" CanExecute="CommonCommandBinding_CanExecute" />
    <CommandBinding Command="Open" CanExecute="CommonCommandBinding_CanExecute" />
    <CommandBinding Command="Save" CanExecute="CommonCommandBinding_CanExecute" />
</Window.CommandBindings>
<DockPanel>
    <ToolBarTray DockPanel.Dock="Top">
        <ToolBar Header="File">
            <Button Command="New" Content="New" ToolBar.OverflowMode="Always" />
            <Button Command="Open" Content="Open" ToolBar.OverflowMode="Always" />
            <Button Command="Save" Content="Save" ToolBar.OverflowMode="Always" />
        </ToolBar>
        <ToolBar Header="Edit" Margin="5.4,0,-5.4,0">
            <Button Command="Cut" Content="Cut" ToolBar.OverflowMode="Always" />
            <Button Command="Copy" Content="Copy" ToolBar.OverflowMode="Always" />
            <Button Command="Paste" Content="Paste" ToolBar.OverflowMode="Always" />
        </ToolBar>
        <ToolBar Margin="9.2,0,-8.2,0">
            <Button Command="Back" ToolTip="Return to the previous page"/>
            <Image Source="C:\Users\elgan\workspace\browser\riviam_windows\Images\navigateBack.png" Width="20" Height="20" Margin="0,0,0,2.4" />
        </ToolBar>
        <ToolBar Margin="16.4,0,-16.2,0" >
            <Button Command="Forward" ToolTip="Proceed to the next page" />
            <Image Source="C:\Users\elgan\workspace\browser\riviam_windows\Images\navigateForward.png" Width="20" Height="20" />
        </ToolBar>
    </ToolBarTray>
    <TextBox AcceptsReturn="True" />
    <WebBrowser Name="browser" Navigating="www.google.com"/>
    <TextBlock HorizontalAlignment="Left" VerticalAlignment="Top" FontSize="12">
       Web page
    </TextBlock>

</DockPanel>

and this is currently showing a blank page, with a toolbar at the top containing 'File' & 'Edit' menus, as well as 'Back' and 'Forward' navigation buttons.
I am now trying to display the contents of a website in the rest of the page, but I'm not sure how to do this.
In the last couple of lines that I have written, I am trying to get Google to display in the main area of the GUI (i.e. below the menus and navigation buttons), but at the moment, nothing is being displayed there, other than the text, "Web page".
Can anyone tell me why this is? How can I get the form to display Google or any other website? Thanks in advance.

A: Try changing:
Navigating="www.google.com"

to...
Source="http://www.google.com"

Hope that helps!

A: First of all  Navigating="www.google.com" - a correct website name would be: https://www.google.com
Try to start all url with http:// or https://
And to navigate trough websites, try to put this somewhere in MainWindow.xaml.cs after
 public MainWindow()
        {
            InitializeComponent();

WebBrowser_Name.Navigate(new Uri(@"https://google.com"));


text:
Q: Can not delete file and folder in android 8 and above i can't delete file & folder in android 8 and above. file.delete() return false in all possible way
File csvFile = new File(Environment.getExternalStorageDirectory().getPath() + "/Notes/help.csv");
File txtFile = new File(Environment.getExternalStorageDirectory().getPath() + "/Notes/MyFile.txt");
folder = new File(Environment.getExternalStorageDirectory().getPath() + "/Notes");

if (csvFile.exists()) csvFile.delete();
if (txtFile.exists()) txtFile.delete();
if (folder.exists()) folder.delete();

A: This may be a permission problem.
Starting from Android 8, READ_EXTERNAL_STORAGE and WRITE_EXTERNAL_STORAGE need to request separately. So even if you can read the file, it is possible you can't delete it.
If you are sure not a permission problem, then change your code to
try {
   Files.delete(theFileName);
} catch (Exception e) {
   log.e(TAG, e.getMessage());
}

Which will give you the reason why delete failed.

A: When you do new File() it doesn't create anything, it is just an object that points to a file (a bit like a path). If you were to write to that file object then it would exist, and then you could delete it.
In other words, I think you can't delete it because you never created it in the first place.


text:
Q: Django Rest Framework cannot access foreign key I am trying to create a product which contains a foreign key yet when sending some JSON it doesn't work.
My models :
class Category(models.Model):
    name=models.CharField(max_length=200)

    objects =  CategoryManager()

    def __str__(self):
        return self.name

class Product(models.Model) :
    name=models.CharField(max_length=200)
    price=models.IntegerField(default=0,blank= True, null=True)
    category = models.ManyToManyField(Category, blank=True, null=True)

The serializers:
class CategorySerializer(serializers.ModelSerializer) :

   class Meta :
       model = Category

       fields = ['name']

class ProductSerializer(serializers.ModelSerializer) :

   category = CategorySerializer(many= True)

   class Meta :

       model = Product

       fields = ['name','price', 'category']

The JSON I send (for ex.):

{
    "name": "HelloThere",
    "price": 30,
    "category": {
        "name": "GeneralKenobi"
    }
}

the view :

@api_view(['GET', 'POST'])
def productcreate(request):
    serializer = ProductSerializer(data=request.data)
    if serializer.is_valid() :
        serializer.save()
    return Response(serializer.data)

When posting the data as it is, I create a product which has a name and a price but category doesn't work.
Thanks in advance for your help,
enter image description here


text:
Q: C++ Boost - serialization of class containing class-hierarchy objects I have a class A, which contains the object of class B and I want to serialize it. The problem is, the class C inherits from B, so A can contain an object of either B or C. How can I efficiently implement the serialization with Boost?
My attempt is below, but I'm getting the error when trying to serialize A with C object, while with B it works correctly. Do you know, what am I doing wrong?
I've found some information about class-hierarchy objects serialization here, but it requires an explicit registration of the type in text_iarchive, whereas I need it to be registered in the A class because I'm not directly serializing B objects.

My attempt:
#include <fstream>
#include <iostream>
#include <vector>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>

class B {
    friend class boost::serialization::access;

private:
    template<class Archive>
    void save(Archive & ar, const unsigned int version) const {
        ar & this->v->size();
        for(int i = 0; i < this->v->size(); i++) {
            ar & (*(this->v))[i];
        }
    };

    template<class Archive>
    void load(Archive & ar, const unsigned int version) {
        size_t size;
        int tmp;
        ar & size;

        this->v = new std::vector<int>(size);
        for(int i = 0; i < size; i++) {
            ar & tmp;
            (*this->v)[i] = tmp;
        }
    }

    BOOST_SERIALIZATION_SPLIT_MEMBER()

protected:
    std::vector<int>* v;

public:
    B();
    B(std::vector<int>* v);
    virtual void print_vals();
};

B::B() {
    this->v = nullptr;
}

B::B(std::vector<int>* v) {
    this->v = v;
}

void B::print_vals() {
    for(auto e : *(this->v)) {
        std::cout << e << std::endl;
    }
}

class C : public B {
    friend class boost::serialization::access;
private:
    int num2;

    template<class Archive>
    void serialize(Archive & ar, const unsigned int version){
        ar & boost::serialization::base_object<B>(*this);
        ar & num2;
    };

public:
    void print_vals() override {
        for(auto e : *(this->v)) {
            std::cout << e << std::endl;
        }
        std::cout << this->num2 << std::endl;
    }

    C();
    C(int num2, std::vector<int>* v);

};

C::C() {
    this->num2 = -1;
    this->v = nullptr;
}

C::C(int num2, std::vector<int> *v) {
    this->num2 = num2;
    this->v = v;
}

class A {
    friend class boost::serialization::access;

private:
    int num;

    B* b_obj;

    template<class Archive>
    void serialize(Archive & ar, const unsigned int version){
        ar & num;
        ar & b_obj;
    };

public:
    A();
    A(int num, B* b);

    void print_vals();
};

A::A() {
    this->num = -1;
    this->b_obj = nullptr;
}

A::A(int num, B* b) {
    this->num = num;
    this->b_obj = b;
}

void A::print_vals() {
    std::cout << this->num << std::endl;
    this->b_obj->print_vals();
}

int main() {
    std::vector<int> v{1,2,3};

    B b = B(&v);

    A a(4, &b);
    std::cout << "a:" << std::endl;
    a.print_vals();

    std::ofstream ofs("a.txt");
    {
        boost::archive::text_oarchive oa(ofs);
        oa << a;
        ofs.close();
    }

    A a2;
    std::ifstream ifs("a.txt");
    {
        boost::archive::text_iarchive ia(ifs);
        ia >> a2;
        ifs.close();
    }
    std::cout << "a2:" << std::endl;
    a2.print_vals();

    C c(2, &v);
    A a3(6, &c);
    std::cout << "a3:" << std::endl;
    a3.print_vals();

    std::ofstream ofs2("a3.txt");
    {
        boost::archive::text_oarchive oa(ofs2);
        oa << a3;
        ofs.close();
    }

    A a4;
    std::ifstream ifs2("a3.txt");
    {
        boost::archive::text_iarchive ia(ifs2);
        ia >> a4;
        ifs.close();
    }
    std::cout << "a4:" << std::endl;
    a4.print_vals();

}

OUTPUT:
a:
4
1
2
3
a2:
4
1
2
3
a3:
6
1
2
3
2
terminate called after throwing an instance of 'boost::archive::archive_exception'
  what():  unregistered class - derived class not registered or exported
Signal: SIGABRT (Aborted)

A: It turns that you have missed BOOST_CLASS_EXPORTfor derived class, i.e.
BOOST_CLASS_EXPORT(C)

Boost serialization cannot serialize pointer to derived object correctly without this macro.
You can find full working code here


text:
Q: How To create Custom Action I want to create one custom action such that on that custom action page one button is available,on that button event i want to show hello word on same custom page

A: Custom Actions generally are used to link to Application Pages which will do the work.
You can include customactions to the Ribbon, to context menus (ECB), or to the Site Settings pages (as well as Central Administration).
The custom action will typically be a custom section with a link to an application page, and within that page you will perform whatever logic you require. You can pass tokens through to the querystring by enclosing them in parenthesis { } such as <UrlAction Url="/_layouts/MyApplicationPage.aspx?ListItem={ItemId}" />
Here's a link to a tutorial on how to create a custom action to appear in the Site Settings page. Google around for simliar tutorials on how to get a custom action to appear in other areas, such as the Ribbon or the ECB.


text:
Q: Tracking continuous days of absence from work days only SQL I'm trying to create a table which takes dates of when a employee is sick and create a new column to provide a "sickness ID", which will identify a unique instance of absence over several dates. I've managed to do this, however I now need to factor in a table which contains the working pattern of each employee, which will let me know if someone was due in work on a given day of the week.
This can be joined using the day_no column in both tables along with the employee_number.
I posted a this question earlier and had a great solution by @GMB, however I need this addition of the working hours.
I have table called sickness which looks like this
date_sick   day_no  day_name    employee_number hours_lost  working_hours
2020-07-14  2       Tuesday     001             7.5         7.5
2020-07-15  3       Wednesday   001             7.5         7.5
2020-07-16  4       Thursday    001             7.5         7.5
2020-07-17  5       Friday      001             7.5         7.5
2020-07-21  2       Tuesday     001             7.5         7.5
2020-07-22  3       Wednesday   001             7.5         7.5
2020-07-23  4       Thursday    001             7.5         7.5
2020-07-24  5       Friday      001             7.5         7.5
2020-07-28  2       Tuesday     001             7.5         7.5
2020-07-29  3       Wednesday   001             7.5         7.5
2020-07-30  4       Thursday    001             7.5         7.5
2020-07-31  5       Friday      001             7.5         7.5
2020-09-09  3       Wednesday   001             7.5         7.5
2020-09-10  4       Thursday    001             7.5         7.5
2020-07-22  3       Wednesday   002             8           8
2020-07-23  4       Thursday    002             8           8

And my working hours table looks like this:
employee_number day_no working_hours
001             1      0
001             2      7.5
001             3      7.5
001             4      7.5
001             5      7.5
001             6      0
001             7      0
002             1      8
002             2      8
002             3      8
002             4      8
002             5      8
002             6      0
002             7      0

Using the following statement, I'm able to apply a unique sickness ID which identifies a unique instance of employee absence over consecutive dates, which is unique to both the employee and the dates there were absence, given by:
IF OBJECT_ID('dbo.sickness ', 'u') IS NOT NULL DROP TABLE dbo.sickness
CREATE TABLE dbo.sickness (date_sick date
                        , day_no int
                        , day_name varchar(10)
                        , employee_number char(5)
                        , hours_lost float
                        , working_hours float)
INSERT INTO dbo.sickness (date_sick, day_no, day_name, Employee_Number, Hours_Lost, Working_Hours)
VALUES
('2020-07-14', '2', 'Tuesday', '001', '7.5', '7.5'),
('2020-07-15', '3', 'Wednesday', '001', '7.5', '7.5'),
('2020-07-16', '4', 'Thursday', '001', '7.5', '7.5'),
('2020-07-17', '5', 'Friday', '001', '7.5', '7.5'),
('2020-07-21', '2', 'Tuesday', '001', '7.5', '7.5'),
('2020-07-22', '3', 'Wednesday', '001', '7.5', '7.5'),
('2020-07-23', '4', 'Thursday', '001', '7.5', '7.5'),
('2020-07-24', '5', 'Friday', '001', '7.5', '7.5'),
('2020-07-28', '2', 'Tuesday', '001', '7.5', '7.5'),
('2020-07-29', '3', 'Wednesday', '001', '7.5', '7.5'),
('2020-07-30', '4', 'Thursday', '001', '7.5', '7.5'),
('2020-07-31', '5', 'Friday', '001', '7.5', '7.5'),
('2020-09-09', '3', 'Wednesday', '001', '7.5', '7.5'),
('2020-09-10', '4', 'Thursday', '001', '7.5', '7.5'),
('2020-07-22', '3', 'Wednesday', '002', '8', '8'),
('2020-07-23', '4', 'Thursday', '002', '8', '8')

GO

IF OBJECT_ID('dbo.working_hours ', 'u') IS NOT NULL DROP TABLE dbo.working_hours
CREATE TABLE dbo.working_hours (employee_number char(5)
                            , day_no int
                            , working_hours float)

INSERT INTO dbo.working_hours (employee_number, day_no, working_hours)
VALUES
('001', '1', '0'),
('001', '2', '7.5'),
('001', '3', '7.5'),
('001', '4', '7.5'),
('001', '5', '7.5'),
('001', '6', '0'),
('001', '7', '0'),
('002', '1', '8'),
('002', '2', '8'),
('002', '3', '8'),
('002', '4', '8'),
('002', '5', '8'),
('002', '6', '0'),
('002', '7', '0');

WITH CTE AS(
    SELECT *,
           ROW_NUMBER() OVER (PARTITION BY employee_number ORDER BY date_sick) AS rn
    FROM dbo.sickness s)

SELECT c.date_sick,
       c.day_no,
       c.day_name,
       c.employee_number,
       c.hours_lost,
       w.working_hours,
       DENSE_RANK() OVER (ORDER BY C.employee_number, DATEADD(DAY, -C.rn, C.date_sick)) AS sickness_id
FROM CTE C
    JOIN working_hours w
        ON  c.employee_number = w.employee_number
        AND c.day_no = w.day_no

ORDER BY C.employee_number,
         C.date_sick
DROP TABLE dbo.sickness
DROP TABLE dbo.working_hours

This outputs the following table:
date_sick   day_no  day_name    employee_number hours_lost  working_hours   sickness_id
2020-07-14  2       Tuesday     001             7.5         7.5             1
2020-07-15  3       Wednesday   001             7.5         7.5             1
2020-07-16  4       Thursday    001             7.5         7.5             1
2020-07-17  5       Friday      001             7.5         7.5             1
2020-07-21  2       Tuesday     001             7.5         7.5             2
2020-07-22  3       Wednesday   001             7.5         7.5             2
2020-07-23  4       Thursday    001             7.5         7.5             2
2020-07-24  5       Friday      001             7.5         7.5             2
2020-07-28  2       Tuesday     001             7.5         7.5             3
2020-07-29  3       Wednesday   001             7.5         7.5             3
2020-07-30  4       Thursday    001             7.5         7.5             3
2020-07-31  5       Friday      001             7.5         7.5             3
2020-09-09  3       Wednesday   001             7.5         7.5             4
2020-09-10  4       Thursday    001             7.5         7.5             4
2020-07-22  3       Wednesday   002             8           8               5
2020-07-23  4       Thursday    002             8           8               5

The issue with this is that it's grouping the consecutive days but only ones that are within the same week. The first 12 rows should all have the same sickness ID. What I want is the following table:
date_sick   day_no  day_name    employee_number hours_lost  working_hours   sickness_id
2020-07-14  2       Tuesday     001             7.5         7.5             1
2020-07-15  3       Wednesday   001             7.5         7.5             1
2020-07-16  4       Thursday    001             7.5         7.5             1
2020-07-17  5       Friday      001             7.5         7.5             1
2020-07-21  2       Tuesday     001             7.5         7.5             1
2020-07-22  3       Wednesday   001             7.5         7.5             1
2020-07-23  4       Thursday    001             7.5         7.5             1
2020-07-24  5       Friday      001             7.5         7.5             1
2020-07-28  2       Tuesday     001             7.5         7.5             1
2020-07-29  3       Wednesday   001             7.5         7.5             1
2020-07-30  4       Thursday    001             7.5         7.5             1
2020-07-31  5       Friday      001             7.5         7.5             1
2020-09-09  3       Wednesday   001             7.5         7.5             2
2020-09-10  4       Thursday    001             7.5         7.5             2
2020-07-22  3       Wednesday   002             8           8               3
2020-07-23  4       Thursday    002             8           8               3

Any ideas? Maybe connecting it to a calendar table?

A: As I mention in the comment, just use a WHERE. This is, of course, a blind guess due to a lack of sample data (the sample has no working hours data):
--I prefer CTEs over subqueries
WITH CTE AS(
    SELECT s.date_sick,
           s.employee_number,
           ROW_NUMBER() OVER (PARTITION BY employee_number ORDER BY date_sick) AS rn
    FROM dbo.sickness s)
SELECT C.date_sick,
       C.employee_number,
       DENSE_RANK() OVER (ORDER BY C.employee_number, DATEADD(DAY, -C.rn, C.date_sick)) AS sickness_id,
       wh.workinghours
FROM CTE C
     JOIN dbo.workinghours wh ON C.employee_number = wh.employee_number
WHERE wh.working_hours > 0
ORDER BY C.employee_number,
         C.date_sick;

A: I think that using lag() to see if the sickness days are consecutive and then a cumulative sum is a better approach for assigning the sickness id.
I am a little unclear on what you want exactly.  But here is one approach:
select date_sick, employee_number,
       sum(case when working_hours > 0 and prev_working_hours > 0 and
                     dateadd(day, -1, date_sick) = prev_date_sick
                then 0 else 1
           end) over (partition by employee_number order by date_sick) as sickness_id
from (select s.*,
             lag(date_sick) over (partition by employee_number order by date_sick) as prev_date_sick,
             lag(working_hours) over (partition by employee_number order by date_sick) as prev_working_hours
      from sickness s left join
           working_hours wh
           on s.date_sick = wh.working_hours
     ) s
order by employee_number, date_sick


text:
Q: Filtering an MS Access form using code upon opening I am trying to put a filter on a form "frmProjectCharter01" where upon opening it (from clicking a button) it will only show records where the field "OnLoad" in its underlying table "tblProjectMasterList" has a "non-null" value.
My current code is
DoCmd.OpenForm "frmProjectCharter01"

Me.Filter = [OnLoad] Is Not Null

Unfortunately, I am getting a "compliation error" message where the private sub opening line is highlighted as well as the "[OnLoad]" field.

A: The Filter property is a string expression, so you can avoid that compile error by adding quotes.
Me.Filter = "[OnLoad] Is Not Null"

However, from the rest of your question, my impression is you should do this with OpenForm WhereCondition (see the help topic for details) instead of setting a Filter:
DoCmd.OpenForm "frmProjectCharter01", WhereCondition:="[OnLoad] Is Not Null"


text:
Q: Is it possible to integrate spring mvc ,hibernate apllication with solr? How can I integrate Spring Hibernate application with solr?
Can anyone please provide me sample working examples?

A: Of course, Spring has one specific project in the Spring Data projects tree.
http://projects.spring.io/spring-data-solr/
You can take a look to ElasticSearch too.
https://github.com/spring-projects/spring-data-elasticsearch


text:
Q: How to randomly choose a number of rectangles to change colour i want my program to randomly change the colour of around 50% of the rectangles within my grid, this is done using jframe.
i have an array with the length of the board and i want 50% of these numbers to be blue.
FALSE = grey
TRUE = blue
Note: this is within paint method using Graphics g
    grid = new boolean[board.length];

    Random r = new Random();
    for(int i = 1;i <grid.length;i++){
        int rand = r.nextInt(i);
    }

A: Take the number of squares on the board and multiply by the target percent.
Assume 8x8 board, so 64 squares * .50 = 32.
I would create a List of all the rectangles.
Begin a loop.  Generate a random number from 0 to the size of the rectangle list.  Remove that position and make it blue.  End loop if all 32 rectangles are identified.
//Pseudo code
java.util.Random random = new Random();
List<Integer> rectangles = new ArrayList<Integer>();
for(int i = 0; i < grid.length; i++)
{
  rectangles.add(i);
}
//Fill the rectangles
for(int i = 0; i < 32; i++)
{
  int position = random.nextInt(rectangles.size());
  Integer toConvert = rectangles.remove(position);
  //perform operation to make toConvert blue.
  grid[toConvert] = true;
}


text:
Q: parsing a complex filter definition with pyparsing I am trying to parse a complex filter definition that will be applied on a set of data. A typical filter could look like this :
attribute1 == value1 and (attribute2 >= 3 or attribute3 != value3)

Of course, the filtering can be much more complex using more nested levels and logical operators. What it all boils down to is :

*

*Extracting the "unit filtering expressions" such as attribute1 == value1

*Run each filter in the set of data

*Combine results using intersections (and) and unions (or)

I heavily reused some examples already provided by Paul McGuire, so my code looks like this :
import pyparsing

def process_results(result):
    for key in result.keys():
        print(key + ":" + str(result[key]))
        if key == 'complex_filter':
            process_results(result[key])

def parse_filter(filter_string):
    # break these up so we can represent higher precedence for 'and' over 'or'
    not_operator        = pyparsing.oneOf(['not','^'], caseless=True).setResultsName("operator")
    and_operator        = pyparsing.oneOf(['and','&'], caseless=True).setResultsName("operator")
    or_operator         = pyparsing.oneOf(['or' ,'|'], caseless=True).setResultsName("operator")

    # db_keyword is okay, but you might just want to use a general 'identifier' expression,
    # you won't have to keep updating as you add other terms to your query language
    ident = pyparsing.Word(pyparsing.alphas+'_'+'-', pyparsing.alphanums+'_'+'-')

    # comparison operators
    comparison_operator = pyparsing.oneOf(['==','!=','>','>=','<', '<='])

    # instead of generic 'value', define specific value types
    integer = pyparsing.Regex(r'[+-]?\d+').setParseAction(lambda t:int(t[0]))
    float_ = pyparsing.Regex(r'[+-]?\d+\.\d*').setParseAction(lambda t:float(t[0]))

    # use pyparsing's QuotedString class for this, it gives you quote escaping, and
    # automatically strips quotes from the parsed text
    quote = pyparsing.QuotedString('"')

    # when you are doing boolean expressions, it's always handy to add TRUE and FALSE literals
    literal_true = pyparsing.Keyword('true', caseless=True)
    literal_false = pyparsing.Keyword('false', caseless=True)
    boolean_literal = literal_true | literal_false

    # in future, you can expand comparison_operand to be its own operatorPrecedence
    # term, so that you can do things like "nucleon != 1+2" - but this is fine for now
    comparison_operand = quote | ident | float_ | integer
    comparison_expr = pyparsing.Group((quote | ident) + comparison_operator + comparison_operand).setResultsName("unit_filter", listAllMatches=True )

    grammar = pyparsing.infixNotation(comparison_expr,
        [
        (not_operator, 1, pyparsing.opAssoc.RIGHT),
        (and_operator, 2, pyparsing.opAssoc.LEFT),
        (or_operator,  2, pyparsing.opAssoc.LEFT),
        ]
    ).setResultsName("complex_filter")

    res = grammar.parseString(filter_string, parseAll=True)

    return res

res = parse_filter('attribute1 == value1 and (attribute2 >= 3 or attribute3 != value3)')

process_results(res)

The output is quite close to what I would like :
complex_filter:[['attribute1', '==', 'value1'], 'and', [['attribute2', '>=', 3], 'or', ['attribute3', '!=', 'value3']]]
unit_filter:[['attribute1', '==', 'value1']]
operator:and

As you can see, it won't keep looping through the "nested" results... I would like the output to be
complex_filter:[['attribute1', '==', 'value1'], 'and', [['attribute2', '>=', 3], 'or', ['attribute3', '!=', 'value3']]]
unit_filter:[['attribute1', '==', 'value1']]
operator:and
complex_filter: [['attribute2', '>=', 3], 'or', ['attribute3', '!=', 'value3']]
unit_filter:[['attribute2', '>=', 3]]
operator:or
unit_filter:[['attribute3', '!=', 'value3']]

Any idea of what I could do to get there ? Thanks !


text:
Q: d3 svg differentiate onclick I'm using d3 to add an onClick() event to my svg container.
   var svg = d3.select("svg").on("click", ()=>{console.log("svg");});

I also have an onclick event for an embedded line Object within the svg;
   var line =d3.select("svg").append("line")
               .attr("x1",10)
               .attr("y1",10)
               .attr("x2",100)
               .attr("y2",100)
               .attr("stroke-width",6)
               .attr("stroke","black")
               .on("click" ()=>{console.log("line");})

I want both events to be separate in the sense, that whenever I click on the
line I only get the output "line" instead of "line" and "svg".
How can I do that?

A: You can do that by using the preventDefault function:
.on("click" ()=>{
    d3.event.preventDefault();
    console.log("line");
})

A: I have to check on th svg if there any prevented events
var svg = d3.select("svg").on("click", ()=>{
                                if(d3.event.defaultPrevented)
                                console.log("svg");});

On the line object then I can use preventDefault()
var line =d3.select("svg").append("line")
           .attr("x1",10)
           .attr("y1",10)
           .attr("x2",100)
           .attr("y2",100)
           .attr("stroke-width",6)
           .attr("stroke","black")
           .on("click" ()=>{
                     d3.event.preventDefault();
                     console.log("line");})


text:
Q: Why doesn't std::sort use my operator< implementation Why doesn't std::sort use my operator< implementation in this code
#include <iostream>
#include <vector>
#include <tuple>
#include <algorithm>
using namespace std;

bool operator<(
    const tuple<int, int>& t1,
    const tuple<int, int>& t2
) {
    return get<1>(t1) > get<1>(t2);// `>` so that it gets sorted in reverse
}

int main() {
    vector<tuple<int, int>> v;
    for (int i = 0; i < 10; ++i) {
        v.push_back(make_tuple(0, i));
    }
    cout << "before sort: ";
    for (auto& x : v) { cout << get<1>(x) << ", "; }
    cout << endl;

    auto v2 = v;
    sort(v2.begin(), v2.end());
    cout << "after sort(begin, end): ";
    for (auto& x : v2) { cout << get<1>(x) << ", "; }
    cout << endl;

    sort(v.begin(), v.end(), [](auto& t1, auto& t2) {
        return get<1>(t1) > get<1>(t2);// `>` so that it gets sorted in reverse
    });
    cout << "after sort(begin, end, comparator): ";
    for (auto& x : v) { cout << get<1>(x) << ", "; }
    cout << endl;

    return 0;
}

The output is:
before sort: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
after sort(begin, end): 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
after sort(begin, end, comparator): 9, 8, 7, 6, 5, 4, 3, 2, 1, 0,

The output I expected is:
before sort: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
after sort(begin, end): 9, 8, 7, 6, 5, 4, 3, 2, 1, 0,
after sort(begin, end, comparator): 9, 8, 7, 6, 5, 4, 3, 2, 1, 0,

A: This has to do with how name lookup works in function templates (commonly referred to as two-phase lookup). std::sort is defined in <algorithm>, and the lookup for < will find those names in scope at the point of the template definition (which yours is not) and those names in the associated namespaces of the dependent function arguments (which for std::tuple would be namespace std, which also does not include yours).
Since the arguments in question are in namespace std, it's actually undefined behavior to add your overload into that namespace. So your options are to either stick with the default behavior (which would be lexicographical <) or to provide your own custom comparator (as you do in your question).


text:
Q: ClassNotFoundException when running hadoop/mapReduce In my MapReduce project, I use the apache-commons CSVParser to parse a CSV file line by line and extract the fields I am interested in.
I use Maven in Eclipse to import the dependencies, and use eclipse to export the project as a jar file.The jar file includes all the dependencies. I am curious why hadoop still throws the following exception:

Error: java.lang.ClassNotFoundException:
  org.apache.commons.csv.CSVParser

I'm on a Windows machine, is there any other better ways of making jar files?

A: First you can put your CSV jars into class path and compile your mapreduce job class. If it compile correctly than While running the mapreduce job, also add this jar in hadoop command.


text:
Q: Configuring Visual Studio to create 32-bit and 64-bit configurations I'm currently trying to configure Visual Studio to automatically set up the appropriate configurations for 32-bit and 64-bit compilation.
Ideally, I'd like to be able to have Visual Studio automatically show x64 as a platform under the Configuration Manager.
How can I configure VS so any new project I create has this?
Thanks!

A: Visual Studio 2010 and 2008 both provide a way to do this.
Project Templates are used by VS to create new projects. These templates can be copied and updated as alternate versions or the originals can even modified in place. You can either use the VS editor to modify the Project Template or you can do it manually; it's your choice:
To use the Visual Studio editor:

*

*Create a new project

*Configure the Project and Build Configuration settings the way you'd like to see all future projects of the same type configured.  In your case, you'll want to add "x64" to the Configuration Manager, then use it in your project's configurations.

*Export the project as a template:  File -> Export Template
To dig into the Project Template files yourself:
Project Template files are stored here: C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\ProjectTemplates
An example is the Windows Forms Application project template, which is housed in this ZIP file: C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\ProjectTemplates\CSharp\Windows\1033\WindowsApplication.zip
The ZIP file contains a handful of files that form the structure of the project (ie: form1.cs) and contain templatized versions of what you get when you create a project of this type.
The important file you'll want to modify is: windowsapplication.csproj. The name of the file will be different for each template, but the .csproj will remain consistent. It is the templatized project file, so modifying this will modify the project settings for all future projects made from this template.
To modify it, simply extract it from the ZIP, make your changes, then put it back into the ZIP file, overwriting the existing one.
In all cases, the result will be:
Now, when you create a new project of that type in the future, just pick YOUR template instead of the default one and you'll have x64 as a Configuration.  You can even share the configuration with your friends since it's stored as a ZIP file.
This MSDN page  documents the steps needed for 2010. Click "Other Versions" at the top of that page to see the instructions for VS 2008:
http://msdn.microsoft.com/en-us/library/ms185319(v=VS.100).aspx


text:
Q: Django Rest Framework does not decode JSON fields in Multipart requests like it does with standard POST requests When I'm submitting a POST request with a Content-Type of application/json, my data at the server is decoded into native Python as it should - JSON objects are presented as dicts, arrays as arrays etc. That's great.
However, when I'm doing a MultiPart post request to my API, which of course also contains a file, any field containing JSON/objects is not decoded at the server and I'm left with strings I need to decode myself. The nature of my app means that I cannot always know which fields I'm about to get.
My question is - how can I submit a multipart request with a file and yet retain DRF's ability to decode JSON data in some of the fields?
I've tried using all 3 major parsers together but that didn't work (by setting the API view's parser_classes to them:

parser_classes = (MultiPartParser, JSONParser, FormParser)

Here are some example requests sent (via Chrome's dev tools):
Standard Post (not multipart, no file):

{"first_name":"Test","last_name":"Shmest","email":[{"channel_type":"Email","value":"test@example.com","name":null,"default":false}],"company":{"position":"Manager","id":"735d2b5f-e032-4ca8-93e4-c7773872d0cc","name":"The Compapa"},"access":{"private":true,"users":[10,1]},"description":"Nice guy!!","address":{"city":"San Fanfanfo","zip":"39292","country":"United States of America","state":"CA","map_url":null,"country_code":"US","address":"123 This street"},"phone":[{"default":false,"type":"Phone","id":"70e2b437-6841-4536-9acf-f6a55cc372f6","value":"+141512312345","name":null}],"position":"","department":"","supervisor":"","assistant":"","referred_by":"","status":"","source":"","category":"Lead","do_not_call":false,"do_not_text":false,"do_not_email":false,"birthday":null,"identifier":""}

This payload gets read by DRF just fine, and all values are set to their native equivalent.
Multipart with file and one of the fields is JSON encoded object:
------WebKitFormBoundaryPfKUrmBd9vRwp5Rb
Content-Disposition: form-data; name="file"; filename="image.png"
Content-Type: image/png

------WebKitFormBoundaryPfKUrmBd9vRwp5Rb
Content-Disposition: form-data; name="first_name"

Test
------WebKitFormBoundaryPfKUrmBd9vRwp5Rb
Content-Disposition: form-data; name="last_name"

Shmest
------WebKitFormBoundaryPfKUrmBd9vRwp5Rb
Content-Disposition: form-data; name="email"

[{"channel_type":"Email","value":"test@example.com","name":null,"default":false}]
------WebKitFormBoundaryPfKUrmBd9vRwp5Rb
Content-Disposition: form-data; name="company"

{"position":"Manager","id":"735d2b5f-e032-4ca8-93e4-c7773872d0cc","name":"The Compapa"}
------WebKitFormBoundaryPfKUrmBd9vRwp5Rb
Content-Disposition: form-data; name="access"

{"private":true,"users":[10,1]}
------WebKitFormBoundaryPfKUrmBd9vRwp5Rb
Content-Disposition: form-data; name="description"

Nice guy!!
------WebKitFormBoundaryPfKUrmBd9vRwp5Rb
Content-Disposition: form-data; name="address"

What I'm looking for is to see if there is some way to have the JSON decoding be automatic in multipart request like it is in regular POST, before I dive into manually decoding all fields to check if they are JSON or not. Most fields I'll be getting will be unknown to me until the request is made as each user might have a different combination of fields.

A: I created a new Parser object to deal with this scenario of MultiPart file upload with fields containing JSON. Code is below if anyone ever needs it.
import json
from rest_framework.parsers import BaseParser, DataAndFiles
from django.conf import settings
from django.http.multipartparser import MultiPartParser as DjangoMultiPartParser, MultiPartParserError
from django.utils import six
from rest_framework.exceptions import ParseError

class MultiPartJSONParser(BaseParser):
    """
    Parser for multipart form data which might contain JSON values
    in some fields as well as file data.
    This is a variation of MultiPartJSONParser, which goes through submitted fields
    and attempts to decode them as JSON where a value exists. It is not to be used as a replacement
    for MultiPartParser, only in cases where MultiPart AND JSON data are expected.
    """
    media_type = 'multipart/form-data'

    def parse(self, stream, media_type=None, parser_context=None):
        """
        Parses the incoming bytestream as a multipart encoded form,
        and returns a DataAndFiles object.
        `.data` will be a `QueryDict` containing all the form parameters, and JSON decoded where available.
        `.files` will be a `QueryDict` containing all the form files.
        """
        parser_context = parser_context or {}
        request = parser_context['request']
        encoding = parser_context.get('encoding', settings.DEFAULT_CHARSET)
        meta = request.META.copy()
        meta['CONTENT_TYPE'] = media_type
        upload_handlers = request.upload_handlers

        try:
            parser = DjangoMultiPartParser(meta, stream, upload_handlers, encoding)
            data, files = parser.parse()
            for key in data:
                if data[key]:
                    try:
                        data[key] = json.loads(data[key])
                    except ValueError:
                        pass
            return DataAndFiles(data, files)
        except MultiPartParserError as exc:
            raise ParseError('Multipart form parse error - %s' % six.text_type(exc))

The parser can be used within the API view like any other:

parser_classes = (MultiPartJSONParser, JSONParser , FormParser)


text:
Q: Why std::basic_ostream has both free and member operator< The title is my question. basic_ostream has both types of the insertion operator. The free operator<< is for chars and the member operator<< is for non char data.
Why is there a need to implement some as free function and others as member function?

A: They could have all been implemented as free functions, and that is the preferred usage nowadays. Back when iostreams was created, they might have been trying to keep the overload set small.
There's a lot of weirdness in the iostreams and locale libraries; they should not be used as model desgins.
In C++98, you can do
int i;
std::ifstream( "data" ) >> i;

but you cannot do
std::string s;
std::ifstream( "data" ) >> s;

The temporary ifstream object will not bind to a reference parameter, but it will bind to this.
That's pretty much the only difference between the member and non-member versions. C++11 smoothed over this difference with rvalue references. (There's also the way you would call them without operator overloading, like cin.operator >> ( i ), but nobody ever does that.)


text:
Q: Install audacity with command line. No root access Is there an easy way to install audacity from the command line with no root access ?
I don't have either apt-get:
apt-get: command not found

Thanks!
EDIT:
Basically, I am looking for an audio player, with a play bar, and in which I can see the signal and zoom in and out.


text:
Q: How can I get this DELETE route to work in my products.js route? I'm having a problem getting my delete route working for removing a single product by grabbing it's _id (5e335c57bd37eb1dd4d99b1f) in Mongoose. I assumed that simply copying the update route and changing it around a bit would work. All the other routes work fine in Postman.
products.js

const express = require("express"),
router = express.Router(),
Product = require("../models/product.model");

// Product list route
router.get("/", function(req, res) {
    Product.find().then(products => {
        res.status(200).json(products);
    }).catch(err => {
        res.status(400).send(`Recieving products failed. Error details: ${err.message}`);
    });
})

// Product details route
router.get("/:product_id", function(req, res) {
    Product.findById(req.params.product_id).then(product => {
        res.status(200).json(product);
    }).catch(err => {
        res.status(400).send(`Recieving product details failed. Error details: ${err.message}`);
    });
})

// Product create logic route
router.post("/add", function(req, res) {
    let product = new Product(req.body);
    product.save().then(product => {
        res.status(200).json({"product": `Product added successfully. Created product details: ${product}`});
    }).catch(err => {
        res.status(400).send(`Adding new product failed. Error details: ${err.message}`);
    });
})

// Product update route
router.put("/:product_id", function(req, res) {
    Product.findById(req.params.product_id).then(product => {
        product.name = req.body.name;
        product.description = req.body.description;
        product.price = req.body.price;
        product.stock = req.body.stock;

        product.save().then(product => {
            res.status(200).json(`Product updated! Updated product details: ${product}`);
        }).catch(err => {
            res.status(400).send(`Update not possible. Error details: ${err.message}`);
        });
    }).catch(err => {
        res.status(404).send(`Product not found. Error details: ${err.message}`);
    });
})

// Product destroy route (NOT WORKING)
router.delete("/:product_id", function(req, res) {
    Product.find(req.params.product_id).then(product => {
        product.remove().then(product => {
            res.status(200).json(`Product deleted! Deleted product details: ${product}`);
        }).catch(err => {
            res.status(400).send(`Delete not possible. Error details: ${err.message}`);
        });
    }).catch(err => {
        res.status(404).send(`Product not found. Error details: ${err.message}`);
    });
})

module.exports = router;

Error in Postman:

<!DOCTYPE html>

 <meta charset="utf-8">
 <title>Error</title>

Cannot DELETE /products/5e335c57bd37eb1dd4d99b1f

Thank you

A: find returns an array, and in array there is no remove() method. You need to use findOne. Also find doesn't throw an error when nothing found. So you had better to check if find returns null.
router.delete("/:product_id", function(req, res) {
  Product.findOne(req.params.product_id)
    .then(product => {
      if (product) {
        product
          .remove()
          .then(product => {
            res.status(200).json(`Product deleted! Deleted product details: ${product}`);
          })
          .catch(err => {
            res.status(400).send(`Delete not possible. Error details: ${err.message}`);
          });
      } else {
        res.status(404).send(`Product not found. Error details: ${err.message}`);
      }
    })
    .catch(err => {
      res.status(500).send(`Error details: ${err.message}`);
    });
});

Also you can shorten this code using findByIdAndDelete method like this:
router.delete("/:product_id", function(req, res) {
  Product.findByIdAndDelete(req.params.product_id)
    .then(product => {
      if (product) {
        return res.status(200).json(`Product deleted! Deleted product details: ${product}`);
      } else {
        return res.status(404).send("Product not found");
      }
    })
    .catch(err => {
      res.status(500).send(`Error details: ${err.message}`);
    });
});


text:
Q: Multiple commands on Keyboard Shortcut in Visual Studio Is it possible to have multiple commands on same Keyboard Shortcut in Visual studio?
like clicking F7 caused two different commands at the same time, instead of only 1 command.

A: You can create a Visual Commander command that calls multiple VS commands and assign a shortcut to it, like this:
public void Run(EnvDTE80.DTE2 DTE, Microsoft.VisualStudio.Shell.Package package)
{
    DTE.ExecuteCommand("Edit.Copy");
    DTE.ExecuteCommand("Edit.Paste");
}


text:
Q: Package private in C#? In Java a method that hasn't any visibility keyword is called package private and can be seen in from objects in the same package.
If a method or a field hasn't any visibility keyword in C# is it also package private and if not whats the visibility then?
And how can I make a field package private in C#?

A: I think the equivalent of a package private in c# is an internal so you can see the method or attributes in the same assembly.
By default a class without access modifier specified is internal.
Here's a good summary

A: I think that the corresponding visibility access keyword is internal. You can also declare assemblies and mark internal members as accesible for them.
http://msdn.microsoft.com/en-us/library/0tke9fxk(v=vs.80).aspx

A: In C#, the default access for methods and fields is private.
C# does not have Java's "package-private", but internal is close; use keyword internal
See this article  and this StackOverflow item.

A: by default, a class is marked as internal if not specified. In this case, only classes from the same assembly can use it.
Actually, this can be overriden by using the InternalsVisibleToAttribute which allow to autorize a specifif other assembly to see internal types

A: By default, a class member is private. The class itself is by default package private.
Package private is called "internal"


text:
Q: How would one iterate over embedded documents in Meteor? I'm in the midst of learning meteorJS, so kindly forgive my ignorance at the moment.
I have a tasks collection at the back end MongoDB which contains something like this:
{
    "name": Something",
    "Address": {
        "Building": A,
        "Street": B,
        "Locality": C
        }
}

My HTML page that contains the template looks like this:
{{#each tasks}}

        {{> task}}

  {{/each}}

<template name="task">

{{Name}}

{{Address}}

</task>

The problem I'm facing is that the Name gets rendered fine. However, the address seems to appear as [object Object]. I'm sure that i've messed up the way I iterate over the address field. Could someone help me with that?

A: You use either the dot notation or the square bracket notation to access the fields in an embedded document:
Dot notation:
<template name="task">

{{Name}}

Address

Building - {{Address.Building}}

Street - {{Address.Street}}

Locality - {{Address.Locality}}

</template>

Square bracket notation:
<template name="task">

{{Name}}

Address

Building - {{Address["Building"]}}

Street - {{Address["Street"]}}

Locality - {{Address["Locality"]}}

</template>


text:
Q: htaccess friendly url tries to open index.php instead of parameter Options +FollowSymLinks
RewriteEngine On
RewriteRule ^portfolio/(.*)/?$ ./portfolio.php?project=$1 [QSA,L]

So when I try to open for example: mywebsite.com/portfolio/my-project, it has to go to mywebsite.com/portfolio.php?project=my-project.
But instead, my url changes to mywebsite.com/portfolio/index.php, which it can't open obviously, because that page doesn't exist. Why is it doing this?
Any suggestions?
EDIT: if (isset($_GET['project'])) { ... } else header('Location: index.php') at the top of my portfolio.php page, was causing this. So it seems as if my project won't get passed to the page, with the $_GET['project'] request?
Fixed: Apparently, I needed -MultiViews in Options +FollowSymlinks -MultiViews

A: Disable MultiViews with
Options -MultiViews


text:
Q: Stopping runaway OpenCL kernel I accidentally wrote a while loop that would never break in a kernel and I sent this to the GPU. After 30 seconds my screens started flickering, I realised what I have done and terminated the application by force. The problem is that I had to shut down the computer afterwards to make sure the kernels are gone. Therefore my questions are:

*

*If I forcefully terminate the program (the program that's launching the kernels) without it freeing the GPU resources (freeing buffers, queues, kernels, CL.destroying) will the kernels still run?

*If they are still running can I do anything to stop them? Say, like, release resources I don't have a handle to any more.

A: If you are using an NVIDIA card, then by terminating the application you will eventually free the resources on the card to allow it to run again.  This is because NVIDIA has a watchdog monitor on the device (which you can turn off).
If you are using an AMD card, you are out of luck AFAIK and will have to restart the machine after every crash.


text:
Q: Logical transition from real problems to chi-squared test So usually the logic for all chi-squared problems is as follows:

*

*Formulate the Null and Alternative  hypothethis

*Calculate pearson residuals

*Now we see, that those residuals fit well into the chi-sqared distribution.

*Use chi-square distribution to get probability of observed data.

I've read and watched many explanations of how chi-squared distribution is build. It's more or less clear here.
But I can't figure out transition between 1 and 2: WHY do we calculate (observed-expected)/sqr(observed) in the first place?.
Why don't we use any other (random) function from "observed" and "expected"?
Why not (observed-expected)^3/log(observed)? Then it wouldn't fit to chi-squared distribution, maybe it will fit for another type of test...


text:
Q: Slider Images working correctly for right cursor but not left I have created a website for a friend which includes a slideshow with his most recent Instagram posts. The slideshow has a right and left arrow cursor.
The right cursor is working how I want it to; it shows each image from the array upon each click, and keeps going regardless of how many times the user clicks the right cursor. When it reaches the last image in the array, it starts at the first image again due to an if statement put in place.
However, I am having trouble with the left cursor and I suspect it is the counter variable? With the current code, what happens is when I click the left cursor (with the page refreshed and without even clicking on the right cursor), it goes to the second image in the array index1, rather than the last. Then I click the left cursor again without any change happening, then when I click it the third time it goes to the last image in the array and works as it should until it reaches the second image in the array again - because after that it does not go to the first image, it skips the first image after another click of nothing happening and then goes to the last image in the array. Repeats itself in that manner (sorry for going so in-detail, but I want people to get an idea of whats happening here if the code doesn't help).

var sliderImages = [];
var counter = 1;

sliderImages[0] = "images/i1.png";
sliderImages[1] = "images/i2.png";
sliderImages[2] = "images/i3.png";
sliderImages[3] = "images/i4.png";
sliderImages[4] = "images/i5.png";

$("#right-arrow").click(function() {

  $(".active").attr("src", sliderImages[counter]);
  counter++;
  $('#count').text(counter);
  if (counter >= sliderImages.length) {
    counter = 0;
  }

});

$("#left-arrow").click(function() {
  $(".active").attr("src", sliderImages[counter]);
  counter--;
  if (counter <= 0) {
    counter = sliderImages.length
  }

});

INSTAGRAM GALLERY

A: When your page loads, you set counter to 1. When you click the left-arrow button, the first thing you do is set the image to the counter value, and so you set the image to 1. (Remember, arrays are 0-indexed, meaning 1 refers to the second item).
You'd be better off if counter was referring to the current image, not trying to assume the upcoming one. See my comments in the modified code below for more information.

var sliderImages = [];
var counter = 0;         //Start with first image instead of second

sliderImages[0] = "images/i1.png";
sliderImages[1] = "images/i2.png";
sliderImages[2] = "images/i3.png";
sliderImages[3] = "images/i4.png";
sliderImages[4] = "images/i5.png";

$("#right-arrow").click(function() {
  counter++;                                           //Moving forward by one
  if (counter > sliderImages.length-1) counter = 0;    //Wrap-around if we exceed length-1
  $(".active").attr("src", sliderImages[counter]);     //Update img src
});

$("#left-arrow").click(function() {
  counter--;                                           //Moving backward by one
  if (counter < 0) counter = sliderImages.length-1;    //Wrap-around if negative
  $(".active").attr("src", sliderImages[counter]);     //Update img src
});

INSTAGRAM GALLERY

A: Use a counter as if you're handling indexes, so set it initially at 0.
Here's the basic logic:

var sliderImages = [
  "//placehold.it/100x100/0bf?text=O",
  "//placehold.it/100x100/f0b?text=1",
  "//placehold.it/100x100/0fb?text=2",
  "//placehold.it/100x100/fb0?text=3",
  "//placehold.it/100x100/b0f?text=4"
];

var n = sliderImages.length; // Total slides
var c = 0;                   // Counter

function anim () {
  $("#mainImage").attr("src", sliderImages[c]);
}

$("#prev").on("click", function() {
  --c;                      // Pre-decrement
  if ( c < 0 ) { c = n-1; } // If lower than 0 - go to last slide
  anim();                   // animate
});

$("#next").on("click", function() {
  ++c;                      // Pre-increment
  if ( c > n-1 ) { c = 0; }   // If greater than num of slides - go to first slide
  anim();                   // animate
});

<button id="prev">←</button>
<button id="next">→</button>

Or here's a neater extracted formula of the above:

var sliderImages = [
  "//placehold.it/100x100/0bf?text=O",
  "//placehold.it/100x100/f0b?text=1",
  "//placehold.it/100x100/0fb?text=2",
  "//placehold.it/100x100/fb0?text=3",
  "//placehold.it/100x100/b0f?text=4"
];

var n = sliderImages.length; // Total slides
var c = 0;                   // Counter

function anim () {
  c = c<0 ? n-1 : c%n;                          // Fix counter
  $("#mainImage").attr("src", sliderImages[c]); // Animate (or whatever)
}

$("#prev, #next").on("click", function() {
  c = this.id==="next" ? ++c : --c;             // Increement or decrement
  anim();                                       // Animate
});

// If you have bullets than you can simply do like:
$(".bullet").on("click", function() {
  c = $(this).index();
  anim();
});

<button id="prev">←</button>
<button id="next">→</button>

A: Updated your code a bit :
var sliderImages = [];
var counter = 0;

sliderImages[0] = "images/i1.png";
sliderImages[1] = "images/i2.png";
sliderImages[2] = "images/i3.png";
sliderImages[3] = "images/i4.png";
sliderImages[4] = "images/i5.png";

$("#right-arrow").click(function() {
  counter++;
  $(".active").attr("src", sliderImages[counter]);
  $('#count').text(counter);
  if (counter >= sliderImages.length) {
    counter = 0;
  }

});

$("#left-arrow").click(function() {
  counter--;
  $(".active").attr("src", sliderImages[counter]);
  if (counter <= 0) {
    counter = sliderImages.length - 1;
  }

});


text:
Q: Get time from long value I am converting milliseconds to the time of the respective country time format, for example, pakistan, US etc
For example
timeinmilliseconds=1549362600000
So its respective Time formate from which I got these milliseconds is 15:30 or 3:30 in 12 hr format
When I want to convert these milliseconds back to that time
I get 10:30 (Five hrs back)
public String getTimeFromLong(long timeInMilliseconds){
String mytime="";
long minute = (timeInMilliseconds / (1000 * 60)) % 60;
long hour = (timeInMilliseconds / (1000 * 60 * 60)) % 24;
mytime = String.format("%02d:%02d", hour, minute);
return mytime;
}

If I select time 4:00
I converted to that to milliseconds (This part is OK)
And wants the time back from milliseconds but get five hours back
For example, If I select time 9:30
convert it to milliseconds and then to time
I get 4:30

A: You need to use your local time zone to get the time in your region, the default is being apllied which is the Greenwich Mean Time (GMT).  For Pakistan use Asia/Karachi like so:
SimpleDateFormat simpleDateFormat= new SimpleDateFormat("hh:mm");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Karachi"));

A: Use this method to convert milliseconds into your local time
public String getTime(long time){
    Calendar calendar = new GregorianCalendar();
    calendar.setTimeInMillis(time);

    SimpleDateFormat format = new SimpleDateFormat("hh:mm a");
    Date date = new Date(time);
    String kTime = format.format(date);
    return kTime;
}

A: Using Java 8 we can do the following.
LocalDateTime dateTime =
LocalDateTime.ofInstant(Instant.ofEpochMilli(longValue), ZoneId.systemDefault());

to get date and time

A:
Use below code to get time from long values:

public String getTimeFromLong(long timeInMilliseconds){
 // Creating date format
 DateFormat simple = new SimpleDateFormat("dd MMM yyyy HH:mm:ss:SSS Z");
 Date result = new Date(timeInMilliseconds);
  return simple.format(result);
}