text:
Q: Remotely turning on or rebooting a frozen computer I use a remote desktop program (usually Microsoft's Remote Desktop) to connect to a Windows machine everyday. The remote computer has a fixed IP address, and if the computer is on and responsive, I can access it and even reboot the computer remotely if necessary.
Unfortunately, if the remote computer freezes (for example, if it gets a blue screen), as far as I know, I can't use a remote desktop solution to restart it. Similarly, if my computer is off, I can't use remote desktop to boot it.
I know that one solution is to ask somebody who is physically near the computer to press the reboot or power on button, but I am opening this thread because I am interested in solutions that do not require the physical presence of people to turn on or reboot a remote frozen computer.
Is this possible? If so, what are my options?

A: I haven't found a way to reboot a computer that is hung up besides a remote power switch device. I use this one ip-p3 and it supports rebooting over the LAN or telephone. It's $200 though.
If you need something a little simpler, you could check this one out this. It's only $100, but the features of the IP-P3 are a lot better.

A: Server-grade computers by most major manufacturers have provided these types of management capabilities for many years.  Watchdog timers in the BIOS, COM-based Telnet console redirect, IP based COM, remote KVM, etc.
For a desktop-grade computer you have a few options:
1) Replace your system with one that has these types of management features (out-of-band management).
Intel offers their AMT (Advanced Management Technologies) on the desktop as well, which when adhering to the certain requirement is branded as vPro. (Basically a vPro-compatible board and CPU).
AMD has DASH; with similar requirements I'm sure. I've never used it, and haven't seen any 3rd party support for it.
I prefer Intel's AMT personally.  All versions (that are 'vPro') allow shutdown, power-on, reset (hard), as well as a textual BIOS and boot view.  The newest versions include a VNC-based "KVM" that allows you interact with the boot process as well as the OS, so it can be used to diagnose boot problems (BIOS, POST, Bluescreens, etc.) as well as end-user and OS support.
2) Get a remote-controlled power strip:
As echoback mentioned, there's products by DLI (Digital Loggers Inc.):

I looked into this, and it was too expensive for small-time use. Perhaps the price has come down though.  It was feature rich, but I've never actually used it.
Another option is Technology On Demand's recent iRemoteReset product:

It is aimed mainly for auto-rebooting a router/modem combo (we use them mainly for that), but it shouldn't have a problem dealing with a desktop computer as a load.  You can hit it by HTTP and reset the sockets manually (individually), as well as have it auto-reset due to lack of Internet connectivity, schedules and such.
3) Build an Interent-enabled robotic arm.

:)

A: Another option can be using a virtual machine. It might take some time to move your server to the a virtual machine but it is free anyway. (VMWare is very nice for this and is free.)
Once you manage to migrate your server, you can install remote desktop server to virtual machine and a text-based (ssh-like) server to the real machine. I don't really know it VMWare has support for console commands, but I bet they have. So, you will use the same desktop software and you will connect directly to the virtual machines, your using habits wouldn't change and in case of system failure, you can easily restart, reboot or even reinstall windows to the machine.
It also provides a wall of security as virtual servers cannot access the data above as long as you don't give permission explicitly.
But also, if the windows machine is used on regular basis on local(w/o remote) using a virtual machine can be, disturbing.
-----edit----
Another budget option which solves the hardware failures as well. You can buy a 2nd hand cheap phone which has a vibration motor. Dissamble the phone and remove the vibration motor, throw it away, open your mainboard connect the reset pins to the remaining vibration pins on the phone by a relay contact. (requires soldering)
So when you call the phone, it will try to vibrate and eventually activate the relay which will hard reset the computer.
There a chance that you can break the cell phone completely while trying to dissamble and solder it, but so long as you use relays correctly, it is nearly impossible to do damage the mainboard.

A: Another option, though not exactly what you're asking for, is a "watchdog timer".  This is an add-in piece of hardware that reboots the system if the timer is not reset in a given interval of time.  (The reset is performed from a loop in a software module that continually checks system health.)
A few years back when I checked there were a number of different types of these being made, though I haven't checked recently.

A: They are not cheap, but many companies offer remote power switches which provide a web interface to toggle power to a given outlet. These are typically used in data centers and server rooms to simplify maintenance, so if you can find a place nearby that is getting rid of equipment, you might be able to work something out for considerably less.

A: In the case of Windows Remote Desktop Connection (RDC), which you appear to use, assuming it's not the blue-screen-of-death and just a frozen program causing RDC to hang, which is typically the case, I highly recommend PsTools. PsTools is free at Windows Sysinternals, the location of Mark Russinovich's developer tools for Windows. It's like using telnet in Linux, which you could also use in Windows for this by installing/enabling a telnet client locally and remotely. The nice thing about PsTools is that it requires no remote software installations.
After downloading PsTools and unzipping the executables into a folder, open a Windows Command Prompt and navigate to that folder. Using PsExec from the Command Prompt, execute the following command using the parameters that you normally use for Remote Desktop Connection (if you use VPN, you must login to that first to use the internal network syntax shown here, otherwise replace \\remotecomputername with the remote Windows computer's IP address):
psexec \\remotecomputername -u username -p password cmd

This will log you onto your remote Windows machine at the Command Prompt. You can then execute the following command, as if you were sitting at the computer:
shutdown -r -t 1

You can optionally add -f to the command to force the restart. To watch the whole shutdown and restart operation, before issuing that command, open another local Command Prompt window and ping the remote computer continuously for 99 seconds:
ping -t99 \\remotecomputername

If it is a properly frozen blue-screen-of-death situation, I'd use a networked AC power switch, power over LAN or auto-restart upon shutdown in the BIOS settings on the remote computer, and a networked RaspberryPi2 in an industrial-grade metal case installed near the power switch. That way, it should be trivial to issue commands to the RasPi2 over telnet to control the physical power to the remote computer for ~$150. You can obviously do other many interesting things by having a RasPi2 installed locally too, such as issue a shutdown command to the remote computer on weekends or at night or if there hasn't been any activity in the room for an hour, using a light sensor, range sensor, or the RasPiCam.
The original short version of this solution is posted here.

A: There's an option in sysdm.cpl -> Advanced tab -> Startup and Recovery section (settings) -> called "Automatically restart" that will automatically restart the machine upon a blue screen.
Machines that depend on remote access for configuration/support need to have this enabled.  You can then check eventvwr.msc or use a utility like NirSoft's BlueScreenView to later determine the STOP code and find why it crashed.
There are many types of freezes.  A "hard freeze" where even the mouse stops working has a high percentage of defective hardware as the cause and needs to be physically looked at when that occurs.  I've had users say their systems are frozen, but the system is just "stuck" at some point and they can still move the mouse.  I've been able to use Sysinternal's PsExec sometimes to get a remote command prompt and issue a shutdown -r -t -0 command which reboots it.
At my place of work, we are a Dell shop.  A lot of newer "high-end" Dell computers (T5400 and T5500 specifically) have a feature called AMT (that we don't use for some reason...).  Supposedly it is a component that lets you remote reboot (even if the system is hung or powered off) and access the BIOS remotely.  I don't know if you can get something with similar capability on a PCI card.  I'm sure other manufacturers have a similar feature in their higher-end workstations and something like this is likely what you want.

A: Check if your motherboard have watchdog timer. If it does (many do) then just install and configure proper software. Motherboard will reboot your computer if OS hangs.

A: Kind of an odd way to do it, but I have a home-made watchdog timer.
My Linux server instructs a PLC to perform various automation tasks in my house, but unfortunately freezes from time to time. I set my Cron scheduler to send a command to the PLC to tell it that it's still alive. If the PLC doesn't get the keep-alive command within its preset time, it clicks a relay that I wired up to the reset pins on my server.
Done.
Quite expensive, but it could be done cheaper. Get yourself an on-delay timer, and set it to say, a few minutes. Have your computer apply power to it (via printer port, breakout board) to keep the delay at a high value. If there is no power from the printer port, and the timer elapses, it resets the system.
Done.

A: Since you say your IP remains the same and is known to you, you can use this from the command prompt of your PC:
shutdown -r -m \\IP-Address

For example:
shutdown -r -m \\14.233.90.157

The only limitation is that the remote machine should have been last logged in with the same user account as the user from whose PC you are running this command.

A: I also use a WSL system in a windows machine, and I access it through the internet to do some development.
I fixed it with two things:

*

*A WiFi smart switch. You can find them from $20.

*A setting in my BIOS.

When the PC becomes unresponsive, I turn it on/off using the smart switch.
I use a GA-Z97X-UD3H board, and it has an option in the Power Options part that is called something like "AC recovery". It controls what happens when the motherboard power supply turns back on. By default, it is on "off" but there is a "memory" option that will start the computer if it was on and will not start it if it was off when the power went off unexpectedly (i.e., without pressing the power button or shutting down normally). There should also be an "on" option that will always turn on your computer when power is back on, regardless of the state it was in. Depending on what you want to do (reset when the computer freezes or turns on when it is turned off), you may want to use either "memory" or, most likely, "on".
Disclaimer: The names are probably not the same as I wrote, but they are easy to find.

A: easy
no watchdog?
why buy expensive eth-switches ???
you have an analogue phone line near the computer?
just give this line a number only you use, (perfect if you have a i.e. FritzBox near the machien with a free analogue line)
attach a relais (with rect. and cap.) and connect the relais-close to the reset-switch, in parallel to the existing reset switch.
Now it the machine hangs, just call that number,
let it ring one time,
the machine gets its hit in the neck and reboots.
just wait for finish all this scandisk crap till its finished booting and continue your work.

A: I know this is an old post, and I hate to resurrect.
But there is a thing called the Windows Emergency Management Services. It requires a USB connection to another computer on the network. (I've been thinking about trying to do this over a USB-server/network extender device.)
It is limited in its authentication requirements however, so I would recommend if you have two servers, or a server and a management computer, that you could have these systems monitor each other.
https://technet.microsoft.com/en-us/library/cc736319(v=ws.10).aspx
It isn't as robust as HP's iLO or Dell's iDRAC, but it is both cheaper, and more featured than an IP controlled power bar.
Of course, your mileage shoehorning this onto newer server OSes may vary.
Updated link to newer system set-up information.
https://msdn.microsoft.com/en-ca/library/windows/hardware/ff542193(v=vs.85).aspx

A: I have a similar issue and have been thinking of trying a wifi light switch wired to a relay so when closed it "pushes" the reset button.  This to me looks like the cheapest option with some wifi switches at or below $30.  Sadly I am still travelling so I am still using my brother as the reset switch.  Just thought I'd throw the idea out there, even if this is an old thread.

A: *

*using RealVNC and sending ctrl-Alt-Del may solve the issue if you can connect remotely (this is possible even if the PC is frozen - RealVNC can comment on this)

*using another remote PC on the same location and using RDP or pstools to reboot the remote PC

*in my case, i am using all the above including Intel AMT and I created a small C# program to restart the pc forcefully (this is to make sure that i don't turn off the pc but simply re-starting it) when the computer is awake. Just to make sure that PC will be fresh again.

A: We had a Qwest Actiontec PK5000 hang up while we were out of town for an extended month trip. We had a security camera running through the modem/router and of course we lost usage of the security camera as soon as the modem/router hung. A friend suggested the cheapest route would be to install a timer between the modem/router and AC power supply and have it be powered off each day for 5 mins. Of couse during a non-critical time frame.


text:
Q: Cannot get slickgrid to save data to hidden field First of all I have seen SO many answers to a question like this, without sample code that seems to apply to me.  I went through the examples on the project wiki page, and none seem to be applicable to me that I can see.  I'm not asking this to be lazy, but after three days, I really am at a loss...
I instantiate a grid inside a form, then on submit, I need to save the form data to a serialized hidden input field (or convert it to modal, but have NO idea how to do this, although it sounds like the perfect solution...
HTML
<form id="myGridForm" action="" method="post">

Date: <input type="text" id="datepicker" name='datepicker'size="30"/>

Instructions:

Select the date by clicking the date image above the table

Enter your event data (you can enter multiple events for that date)

To add another event, hit your TAB key and a new row will be created

When you're all done for this date, click the Commit Changes button to have your events saved to the site

Options:

    <input type="hidden" name="p" id="p" value="<?=$_POST['p']?>" />
    <input type="hidden" name="k" id="k" value="<?=$_POST['k']?>" />
    <input type="hidden" name="i" id="i" value="<?=$_POST['i']?>" />
    <input type="hidden" name="d" id="d" value="<?=$_POST['d']?>" />
    <input type="hidden" name="gridData" id="gridData" />

 <button type="submit">Submitter</button>

        Search

</form>

.js scripts being loaded
js/slickGrid/lib/firebugx.js
js/jquery-ui-1.8.20.custom.min.js.php
js/json2.js.php
js/slickGrid/plugins/slick.cellrangedecorator.js
js/slickGrid/plugins/slick.cellrangeselector.js
js/slickGrid/plugins/slick.cellselectionmodel.js
js/slickGrid/slick.formatters.js
js/slickGrid/slick.editors.js

Code to instantiate the grid, and then make it visible (nested to resolve dependencies)

Final scripts at end of page (footer)

<? //Instantiate   slickGrid jQueryUI widget ?>

As you can see, I have been trying for a while to get data out of the grid what with all the alerts and console log tests trying to implement the various answers I have found on SO.  However, noone has posted final code samples of a working application of this.  Once I get it working, I plan on submitting it to mbielman's exxamples page to try and help what so many users are running into.  Also if someone can show me how to instantiate the grid as a modal, that would be great information too :)
Currently, my logs reply the following, see the commands to write to the log in the submit functionality at end of script.  It appears I can get an object from console.log ( ' myGrid data2: '+ $('#myGrid').data() );, I just can't seem to do anything with it, or else it is null, not even sure how to display it to the screen to see the contents for debug...
firebug console output
myGrid data1: null
myGrid data2: [object Object]
myGrid data3:
data is undefined

Note, while I am a fairly advanced programmer in many languages, some of the syntax/properties of javascript/jQuery are very confusing to me.  So any additional time you could spend on explaining what is going wrong, how to do it better, reference links, would be fantastic as I really want to get better at working with this language.  Again, sorry about the really long post, if you got here, I really appreciate your time.  I'm trying to be as thorough as possible so others have a thorough reference point when they are having as much trouble as I am...

A: You are trying the data from the grid.  Don't.  The data is in your data JavaScript variable (though you can also get it via grid.getData()).  Use whatever mechanism you like to serialize all or parts of that data and send it to the server.
Also, don't try working with SlickGrid as if it were a jQuery widget - it isn't.  All of SlickGrid's API is exposed via the JavaScript object you created var grid = new Slick.Grid(...) and not through the jQuery widget semantics (e.g. $("#myGrid").xxx()).

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is the url for an Eclipse Dynamic Web project's jsp files? I have added a dynamic web project in Eclipse and can access the static HTML files and resources in the WebContent folder.  I have placed my JSP files in WebConent\WEB-INF
This works fine:  "http://localhost:8080/HelloWorld/index.htm"
This tells me the resource is not found: "http://localhost:8080/HelloWorld/Logon.jsp"
I have not defined any JSP servlet mappings.  I have the default web.xml which only has the welcome files in it.  I right click the project name and choose Debug On Server to run the app.
Update: I've had some success.  I added the following to the Eclipse project's web.xml (in the WebContent\WEB-INF folder).  The Test.jsp works as  "http://localhost:8080/HelloWorld/Test.jsp" only when Test.jsp is in the WebContent folder and not when its in the WebContent\WEB-INF folder.
  <servlet>
   <servlet-name>jsp</servlet-name>
   <servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
   <init-param>
       <param-name>fork</param-name>
       <param-value>false</param-value>
   </init-param>
   <init-param>
       <param-name>xpoweredBy</param-name>
       <param-value>false</param-value>
   </init-param>
   <init-param>
        <param-name>logVerbosityLevel</param-name>
        <param-value>WARNING</param-value>
   </init-param>
   <load-on-startup>3</load-on-startup>

   <servlet-mapping>
    <servlet-name>jsp</servlet-name>
    <url-pattern>*.jsp</url-pattern>
   </servlet-mapping>

A: Files in /WEB-INF are not publicly accessible. That folder is intented for configuration files, template files, tag files, include files, MVC view files, etcetera. Basically everything which is not supposed to be directly accessible by the enduser without invoking some main JSP file or a front controller servlet first.
Just put them outside the /WEB-INF folder, in the public webcontent.
See also:

*

*Moving resources under WEB-INF

Don't forget to remove the unnecessary copy of the JspServlet from your web.xml. It didn't solve the concrete problem at all. Even more, it really doesn't belong there in your webapp's web.xml. It is already definied in servletcontainer's own web.xml (in case of Tomcat you can find it in its /conf folder. Registering the JspServlet in your webapp's web.xml would only make your webapp unportable. It wouldn't be able to run on a servletcontainer of a different make than Tomcat.


text: Q: Woocommerce match cart items with order items I am using woocommerce's session variables to store extra meta data using cart items ID's.  However I now need to access the data when the order is processed and the cart object is destroyed.  Is there a way to match the Cart items with the newly generated order items?


text:
Q: function parameters are returning undefined I'm having a problem with my function syntax, when I call the function and give its two parameters strings the output is always undefined. I don't understand why its doing this, I was also wondering if this could go on the code review part of stack exchange since its bug free. Any answers would be greatly appreciated!

function sm(name, location){
  console.log("Hello " + this.name + " from " + this.location);
}

sm("josh", "hawaii");

A: The function parameters are not properties of the function so you can't access them with this keyword.
And in your function this will refer to the global window object so the compiler will look for these properties inside the window object and will fire an exception if they weren't defined.
Just write:
console.log("Hello " + name + " from " + location);

Demo:

function sm(name, location){
  console.log("Hello " + name + " from " + location);
}

sm("josh", "hawaii");

A: No need using thisfor functional parameters.
function sm(name, location){
  console.log("Hello " + name + " from " + location);
}

sm("josh", "hawaii");

A:

function sm(name, location){
  console.log("Hello " + name + " from " + location);
}

sm("josh", "hawaii");

Hope it helps you

A: You don't need to use this here. Just name and location is enough to refer the variable passed as the function parameter.

function sm(name, location){
  console.log("Hello " + name + " from " + location);
}

sm("josh", "hawaii");


text:
Q: How to create babelish config file I'm using babelish command tool to create a .strings file from a doc file stored on google.
The command is simple:
 babelish csv2strings -i "Project Language" -L  English:en German:de French:fr --fetch
this works only if the data in doc is:
 key | englishString | germanString | franchString | ..etc where key is in the first column.
but if the key is not on the first column it doesn't work
i tried the config file .babelish.config and add the keys_column: myColumn but no success.
What i'm missing ?

A: With help from netbe i manage to fix it

*

*Issue is that the config file name .babelish.config i got some error so I rename it to .babelish

*Config settings
filename:"Project Language"
langs:
  English: "en"
fetch: true        # set to true to get file(filename) from google drive
comments_column: 3 # Position of column for comments if any
keys_column: 1     # Position of column for keys
 because my doc file have this structure Category | Key | English | Notes

*If you have a config file remove all arguments after csv2strings and call just babelish csv2strings


text:
Q: What is performance of label correcting algorithm? I have tried to find answer in Google but without any result. I guess, it should be like performance of Dijkstra algorithm - O(E*logV) - since this both algorithms are really similar to each other. Am I right?

A: No, it is O(V * E). A proof is in this article.


text:
Q: Linking C compiled static library to C++ Program I tried to link a static library (compiled with gcc) to a c++ program and I got 'undefined reference'. I used gcc and g++ version 4.6.3 on a ubuntu 12.04 server machine. For example, here is the simple library file for factorial method:
mylib.h
#ifndef __MYLIB_H_
#define __MYLIB_H_

int factorial(int n);

#endif

mylib.c
#include "mylib.h"

int factorial(int n)
{
    return ((n>=1)?(n*factorial(n-1)):1);
}

I created object for this mylib.c using gcc:
gcc -o mylib.o -c mylib.c

Again the static library was created from the object file using AR utility:
ar -cvq libfact.a mylib.o

I tested this library with a C program (test.c) and C++ program (test.cpp)
Both C and C++ program have the same body:
#include "mylib.h"
int main()
{
    int fact = factorial(5);
    return 0;
}

Assuming static library libfact.a is available in /home/test directory, I compiled my C program without any issues:
gcc test.c -L/home/test -lfact

However while testing C++ program, it threw a link error:
g++ test.cpp -L/home/test -lfact

test.cpp:(.text+0x2f): undefined reference to `factorial(int)'
collect2: ld returned 1 exit status

I even tried adding extern command in test.cpp:
extern int factorial(int n) //added just before the main () function

Still the same error.

*

*Can someone tell me what I am wrong here?

*Is there anything I missed while creating the static library?

*Do I have to add anything in my test.cpp to make it work?

A: The problem is that you haven't told your C++ program that factorial is written in C. You need to change your test.h header file. Like this
#ifndef __MYLIB_H_
#define __MYLIB_H_

#ifdef __cplusplus
extern "C" {
#endif

int factorial(int n);

#ifdef __cplusplus
}
#endif

#endif

Now your header file should work for both C and C++ programs. See here for details.
BTW names containing a double underscore are reserved for the compliler (so are names starting with an underscore and a capital letter) so #ifndef __MYLIB_H_ is illegal strictly speaking. I would change to #ifndef MYLIB_H #define MYLIB_H

A: While the accepted answer is absolutely correct, I thought I'd just add an observation. Some editors have trouble with the open / close brace, and will indent the entire extern "C" scope in the header. If mylib.h is a key header for a library, you might consider:
#if defined (__cplusplus)
#define _MYLIB_INIT_DECL extern "C" {
#define _MYLIB_FINI_DECL }
#else
#define _MYLIB_INIT_DECL
#define _MYLIB_FINI_DECL
#endif

All other headers in mylib library, e.g., mylib_aux.h, can be of the form:
#ifndef _MYLIB_AUX_H
#define _MYLIB_AUX_H

#include <mylib.h>

_MYLIB_INIT_DECL

... header content ...

_MYLIB_FINI_DECL

#endif /* _MYLIB_AUX_H */

Obviously, the names I'm using are arbitrary, but for multiple library headers, this approach has been useful to me.


text:
Q: How to textually indicate that there are no results in a SQL SELECT? I have the following SQL CASE statement that doesn't appear to be evaluating the conditional correctly. This table currently is empty (0  non-null rows) so I would assume the ELSE condition should be true and therefore output the text string below. However it doesn't populate anything in the results.
SELECT
CASE WHEN EC.INV_ITEM_ID <> '' THEN EC.INV_ITEM_ID
     ELSE 'NO ITEMS IN STAGING TABLES'
     END

FROM PS_MASTER_ITEM_EC EC
ORDER BY INV_ITEM_ID

A: IF ((SELECT COUNT(*) FROM PS_MASTER_ITEM_EC EC WHERE EC.INV_ITEM_ID <> '' AND EC.INV_ITEM_ID IS NOT NULL) > 0)
SELECT EC.INV_ITEM_ID FROM PS_MASTER_ITEM_EC EC WHERE EC.INV_ITEM_ID <> '' AND EC.INV_ITEM_ID IS NOT NULL
ELSE
SELECT 'NO ITEMS IN STAGING TABLES'

First line will calculate how many non empty rows there are in the table
second line will return a 1 column table with all the IDs that were not NULL or '' if any is found at all
4th row will return the default message if the table was actually empty

A: All values in a column must have the same data type. So if the INV_ITEM_ID column is being used for a string value of 'NO ITEMS IN STAGING TABLES' in the case where there aren't any records then the column must have a textual data type.
If this isn't the case, you'll need to convert the IDs to strings to match this in the case where there are records. Personally I'd advise against this as it's like mixing chalk and cheese - a string value doesn't really belong in a numeric ID column - and even if the IDs happen to be strings it's still questionable as semantically the "no results" string isn't an ID.
But if you really want to do it, something like the following SQL can achieve it:
SELECT 'NO ITEMS IN STAGING TABLES' AS INV_ITEM_ID
WHERE NOT EXISTS (SELECT * FROM PS_MASTER_ITEM_EC)
UNION ALL
SELECT CAST(INV_ITEM_ID AS VARCHAR(26))
FROM PS_MASTER_ITEM_EC EC
ORDER BY INV_ITEM_ID;

Rextester demo: https://rextester.com/FIRWF53864

A: You can't return records from an empty table. The case statement is being evaluated against every record in the table. When there are no records then there will be nothing to evaluate, thus the empty result set. There are a few ways to check for this condition. If the client is expecting a specific result set and will check a known field for the existence of data, (which seems hacky) then you can return similar shaped data from a derived result set with your messaging, however, I would encourage you to think about checking for this condition at the consumer as database queries are better suited for inserting/updating/deleting and getting data.
DECLARE @PS_MASTER_ITEM_EC TABLE(INV_ITEM_ID NVARCHAR(200))
--INSERT @PS_MASTER_ITEM_EC VALUES ('I''m Here')

IF(NOT EXISTS(SELECT EC.INV_ITEM_ID FROM @PS_MASTER_ITEM_EC EC))
    SELECT INV_ITEM_ID =  'NO ITEMS IN STAGING TABLES'
ELSE
SELECT
CASE WHEN EC.INV_ITEM_ID <> '' THEN EC.INV_ITEM_ID
     ELSE 'EC.INV_ITEM_ID has an empty string for a value'
     END AS INV_ITEM_ID

FROM @PS_MASTER_ITEM_EC EC
ORDER BY INV_ITEM_ID

A: Your problem is that your CASE is evaluated only for existant rows, if your table is empty you will get no record at all.
But, you want to get a record with a message even if the table is empty so you must create that row.
You can do it using UNION to add a new row to result set only when PS_MASTER_ITEM_EC is empty.
So, you can simply list all your records if there is any,
and show your message when PS_MASTER_ITEM_EC is empty.
SELECT EC.INV_ITEM_ID
FROM PS_MASTER_ITEM_EC EC
ORDER BY INV_ITEM_ID

UNION ALL

SELECT 'NO ITEMS IN STAGING TABLES'
WHERE NOT EXISTS(SELECT TOP 1 'X' X FROM PS_MASTER_ITEM_EC )

Pay attention, you need INV_ITEM_ID column to be of type char/varchar/nvarchar or you will get an error.
If your INV_ITEM_ID is a number you can use this workaround:
SELECT EC.INV_ITEM_ID, NULL Message
FROM PS_MASTER_ITEM_EC EC
ORDER BY INV_ITEM_ID

UNION ALL

SELECT NULL INV_ITEM_ID, 'NO ITEMS IN STAGING TABLES' Message
WHERE NOT EXISTS(SELECT TOP 1 'X' X FROM PS_MASTER_ITEM_EC )

A: SQL Server is a relational database. Relational databases works of off sets, which is basically a list of records. If there is no record, then your function / logic (CASE in this case) cannot be applied. If you need a record returned when your query returns zero record, then you need to provide a record from another source to be returned. One way of doing that is providing a record through UNION with a WHERE clause that guarantees a special record is returned when the result set is empty. When the result set is NOT empty, then WHERE clause makes sure this new record is not returned. The gotcha here is that, this special record has to have the same number of columns as the regular query result and with the same or compatible data types.
; WITH cte (
 ---- your complex query goes here
  select colString, colNumeric
   .............
)
SELECT colString, colNumeric FROM cte
UNION ALL
SELECT 'no result found' as colString, NULL as colNumeric  WHERE NOT EXISTS (SELECT * FROM cte) --- this returns true only if no record in cte

A: Using Common Table Expression (CTE), one for the main query (your query) and another one for the check whether the table that you are interested in is empty.
WITH MainQuery AS (
  SELECT
  CASE WHEN EC.INV_ITEM_ID <> '' THEN EC.INV_ITEM_ID
       END AS INV_ITEM_ID
  FROM PS_MASTER_ITEM_EC EC
),
EmptyTableMessage AS (
  SELECT
  CASE WHEN (SELECT COUNT(*) FROM MainQuery) > 0 THEN ''
       ELSE 'NO ITEMS IN STAGING TABLES'
       END AS EmptyMessage
)
SELECT
EmptyTableMessage.EmptyMessage,
MainQuery.*
FROM EmptyTableMessage
LEFT OUTER JOIN MainQuery ON 1 = 1
ORDER BY MainQuery.INV_ITEM_ID

Feel free to change the content inside the MainQuery with any query that you need and change the ORDER BY clause at the very end according to the content of the MainQuery.
The negative aspect of this is that you will always have an extra column containing (as a placeholder of) the message for the empty table/record/result.

A: It could be achieved by using LEFT JOIN:
SELECT IIF(EC.INV_ITEM_ID <> '', EC.INV_ITEM_ID, s.col)
FROM (SELECT 'NO ITEMS IN STAGING TABLES') s(col)
LEFT JOIN PS_MASTER_ITEM_EC EC ON 1=1
ORDER BY EC.INV_ITEM_ID;

db<>fiddle demo

Scenarios:
CREATE TABLE PS_MASTER_ITEM_EC(INV_ITEM_ID NVARCHAR(10));

-- case 1: empty value
INSERT INTO PS_MASTER_ITEM_EC VALUES ('');
-- NO ITEMS IN STAGING TABLES

-- case 2: empty table
TRUNCATE TABLE PS_MASTER_ITEM_EC
-- NO ITEMS IN STAGING TABLES

-- case 3: data in table
INSERT INTO PS_MASTER_ITEM_EC VALUES ('abc')
-- output: abc

A: If your question is just why you're getting no results, here's my answer to that:
A SQL query consists of different parts called "clauses". SELECT and FROM are two of those (probably the most important ones).
Whatever you write in the SELECT clause (i.e. after SELECT and before FROM) can only produce columns from rows that are the result of what you write in the FROM clause. The table PS_MASTER_ITEM_EC in your FROM clause doesn't contain any rows, so your FROM clause can't produce any rows. Hence the SELECT clause doesn't have any rows that it can create columns for.
There's one exception though: If you omit the FROM clause, SELECT can produce a result with one single row as in
SELECT 'no result found' as Dummy
-- Will generate a result with one row, one column "Dummy" containing 'no result found'


text:
Q: Accessing fields from an model associated to a django user in template I have a model User_Details associated with each Django User. It has a field named mobile_number. I want to access the mobile_number in my template. I am trying request.user.User_Details.mobile_number but it's not working. Is it the right way? If not, then how should I go about it?

A: Try this (I am assuming index.html as template, which is properly set in urls.py):
from django.contrib.auth.models import User

def index(request):
    template = loader.get_template('index.html')
    user_details = User_Details.objects.get(user=User.objects.get(username=request.user.username))

    context = RequestContext(request, {'mobile_no':user_details.mobile_number,}
    return HttpResponse(template.render(context))

Works if you have a user object (django.contrib.auth.models) in your User_Details Model
class User_Details(models.Model):
    user = models.OneToOneField(User)
    mobile_number = models.CharField(...

Then in your index.html or whatever template use
{{mobile_no}}

to display the information

A: Its defficult to tell without looking at your model but I guess you can use related_name in the OneToOneField and access it directly.
class User_Details(models.Model):
   user = models.OneToOneField(User, related_name="detail")
   mobile_number = models.CharField(...

then
request.user.detail.mobile_number to access it.
Hope it helps


text:
Q: insert data in a wordpress database I'm developing a WordPress plugin which is responsible for getting data from an external HTML form and then inserts it in the database. My form code is:
    <html>
   <body>
    <form action = "http://wp.istic.online/wp-content/plugins/news-apps/index.php" method = "POST">
         Name: <input type = "text" name = "name" />

         <input type = "submit" />
      </form>

   </body>
</html>

My plugin code is:
    <?php

register($_POST['name']);
    register($_POST['name']);
function register($name) {

    global $wpdb;
$wpdb->insert(
    'gcm_tokens',
    array(
        'token' => $name
    ),
    array(
        '%s'
    )
);

}

The data is not inserted however when I try to echo the $name variable it works perfectly. But when I try to echo it after the insert function it's not working.
Any help please?

A: Use wp_nonce_field() like below
<form>
/*
Your code
*/
<input type="hidden" name="action" value="new_post" />
<?php wp_nonce_field( 'new-post' ); ?>

</form>

A: First, make sure you have correct db prefix, correct table name and you can get $POST variable correctly.
I tried your code by call register('Test'); and It works.


text:
Q: Somatoria acumulando colunas em uma matrix no R Eu tenho a seguinte situação :
Em uma matrix numerica tipo :
Temp <- matrix(runif(25, 10, 100),nrow=5,ncol=5)

V1    V2    V3    V4    V5

11    34    45    54    55
16    21    45    75    61
88    49    85    21    22
12    13    12    11    10
69    45    75    78    89

Como transformar essa matrix em uma matrix que seja a somatoria acumulada das colunas ? O resultado seria o seguinte
V1    V2    V3    V4    V5

11    45    90    144   199
16    37    82    157   218
88    137   222   243   265
12    25    37    48    58
69    114   189   267   356

Eu consegui o objetivo usando um for loop, mas acredito que deva existir uma maneira mais eficiente de fazer uma vez que estou trabalhando com uma matrix de 2580 linhas por 253 colunas e esta demorando um pouco para gerar o resultado
Temp <- matrix(runif(25, 10, 100),nrow=5,ncol=5)
Temp <- round(Temp,0)
sum_matrix <- matrix(0,nrow=nrow(Temp),ncol=ncol(Temp))
sum_matrix[,1] <- Temp[,1]
    for (n in 2:nrow(Temp)) {
        sum_matrix[,n] <- sum_matrix[,n-1] + Temp[,n]
}

A: Você pode usar a função cumsum para obter a cumulative sum dos elementos da sua matrix. E o apply, somado ao t (transpose) pode ser usado para obter o resultado que você precisa:
temp <- t(matrix(c(11, 34, 45, 54, 55,
                   16, 21, 45, 75, 61,
                   88, 49, 85, 21, 22,
                   12, 13, 12, 11, 10,
                   69, 45, 75, 78, 89)
    ,nrow=5,ncol=5))
temp2 <- t(apply(temp, 1, cumsum))
temp2

     [,1] [,2] [,3] [,4] [,5]
[1,]   11   45   90  144  199
[2,]   16   37   82  157  218
[3,]   88  137  222  243  265
[4,]   12   25   37   48   58
[5,]   69  114  189  267  356

A: Uma forma usando os pacotes dplyr e tidyr seria a seguinte:
> library(tidyr)
> library(dplyr)
>
> temp <- matrix(1:25, 5, 5)
> temp <- data.frame(id = 1:5, temp)
> temp
  id X1 X2 X3 X4 X5
1  1  1  6 11 16 21
2  2  2  7 12 17 22
3  3  3  8 13 18 23
4  4  4  9 14 19 24
5  5  5 10 15 20 25
> temp %>%
+   gather(variavel, valor, -id) %>%
+   group_by(id) %>%
+   arrange(variavel) %>%
+   mutate(valor = cumsum(valor)) %>%
+   spread(variavel, valor)
Source: local data frame [5 x 6]

     id    X1    X2    X3    X4    X5
  (int) (int) (int) (int) (int) (int)
1     1     1     7    18    34    55
2     2     2     9    21    38    60
3     3     3    11    24    42    65
4     4     4    13    27    46    70
5     5     5    15    30    50    75

Para usar esse formato, seus dados devem estar armazenados em um data.frame.
Note que se esse tipo de manipulação faz sentido no seu banco de dados quer dizer que ele não está no formato tidy. Para entender mais o porque do formato tidy ser ideal para usar no R, vale muito a pena ler esse artigo do Hadley.


text:
Q: what is the right query for this question? How to Identify the 3 most important (highest revenue) cities and show a break down of 3 top level categories against these cities.
I work on adventureworkslt2014.
this is my query, but I got the best three sales from the same city:
select top 3 sum(TotalDue) as bestrevenue,city,pc.Name
from SalesLT.ProductCategory as pc
join SalesLT.Product p
on pc.ProductCategoryID =p.ProductCategoryID
join SalesLT.SalesOrderDetail as sod
on sod.ProductID=p.ProductID
join SalesLT.SalesOrderHeader as soh
on soh.SalesOrderID = soh.SalesOrderID
join SalesLT.[Address] addr
on addr.AddressID = soh.BillToAddressID
group by city,pc.Name
order by bestrevenue desc`

the expected result I should get 9 rows, every three rows have same city with it's highest sales also from which categories came this highest sale.

A: Try this:
select t.*
from(select city, pc.Name, sum(TotalDue) as bestrevenue,
            row_number() OVER(partition by city,Name ORDER BY sum(TotalDue) desc) as RN
     from SalesLT.ProductCategory as pc join
          SalesLT.Product p
          on pc.ProductCategoryID =p.ProductCategoryID join
          SalesLT.SalesOrderDetail as sod
          on sod.ProductID=p.ProductID join
          SalesLT.SalesOrderHeader as soh
          on soh.SalesOrderID = soh.SalesOrderID join
          SalesLT.[Address] addr
          on addr.AddressID = soh.BillToAddressID
     group by city,pc.Name
    ) t
where RN <= 3;


text:
Q: Trigger jquery tab active by data-tab I've checked around in here, but not found my answer. I have my code below:

Day 1

23 May 2016

Day 2

24 May 2016

Content here

Content here

Jquery code:
// script for session tab item
    $('.gdlr-session-item-head-info').click(function(){
    if( $(this).hasClass('gdlr-active') ) return;
    $(this).siblings().removeClass('gdlr-active');
    $(this).addClass('gdlr-active');

    var selected_tab = $(this).attr('data-tab');
    $(this).parent('.gdlr-session-item-head').siblings('.gdlr-session-item-tab-content').hide();
    $(this).parent('.gdlr-session-item-head').siblings('.' + selected_tab).fadeIn();
});

In the default, The day 1 will active and show the content from class: gdlr-tab-1.
I need help to active the day 2 instead day 1. Thank so much for all help!
Live demo: http://goodlayers.tienloc.net/keynote/.

A: Check if below code helps.
You can hide all the content div first and then can show (fade in) the required div using the data attr, same applies to add and remove active class.
$('.gdlr-session-item-head-info').click(function(){
  if( $(this).hasClass('gdlr-active') ) return;
  $('.gdlr-active').removeClass('gdlr-active');
  $(this).addClass('gdlr-active');

  var selected_tab = $(this).attr('data-tab');
  $(".gdlr-session-item-tab-content").hide();
  $("."+selected_tab).addClass('gdlr-active');
  $("."+selected_tab).fadeIn();
});


text:
Q: Resizing a panel after constructing it with BoxSizer I have a situation where I have to create a panel with content in the panel, and then after creating the panel, I need to resize it.
The size of the panel depends on the child content, and when you create the child content, you need to specify the parent panel; like a chicken and the egg problem.
So, I have a need to create the panel and its content, then based on the content, resize the panel...
So, I made a mock up code example, where the panel starts out at 50 x 50, and after constructing it at that size, I want it to instead be 400 x 400.
But, when you run this on your computer, you just see it as 50 x 50. The SetSize((400, 400)) has no effect!
How can I fix this and make SetSize take effect after applying the sizer?
Any help is appreiciated...
import wx

class MainFrame(wx.Frame):

    def __init__(self):

        wx.Frame.__init__(self, None, id = -1, title = 'Hello, World!', size = (500, 500))

        self.__myPanel = wx.Panel(self, size = (50, 50), style = wx.SIMPLE_BORDER)

    def test(self):

        self.__myPanel.SetSize((400, 400))

        vertBoxSizer = wx.BoxSizer(wx.VERTICAL)

        vertBoxSizer.AddSpacer((0, 10))
        vertBoxSizer.Add(self.__myPanel, 0, wx.ALL, 0)

        self.SetSizer(vertBoxSizer)

        self.Layout()

if __name__ == '__main__':
    app = wx.App()

    frame = MainFrame()
    frame.test()

    frame.Show(True)
    app.MainLoop()

    print 'Exiting...'

A: There's no chicken and egg because windows and sizers are not parent/children related. Sizers are a very good tool (they are not windows!) used to size windows.
If your panel is the only child of a frame then no sizer is needed: The panel will be sized to fit the client area of its parent frame.
If you want that the window who set the sizer changes its size when the sizer needs it (perhaps due to yo did use SetSize() in a panel whose size is managed by that sizer) just call Fit(), self.Fit() in your test() function.
I recomend reading official docs for window sizing

A: class MainFrame(wx.Frame):
def __init__(self):

    wx.Frame.__init__(self, None, id = -1, title = 'Hello, World!', size = (500, 500))

    self.__myPanel = wx.Panel(self, size = (50, 50), style = wx.SIMPLE_BORDER)

def test(self):

    self.__myPanel.SetSize((400, 400))

    vertBoxSizer = wx.BoxSizer(wx.VERTICAL)

    vertBoxSizer.AddSpacer((0, 10))
    vertBoxSizer.Add(self.__myPanel, 0, wx.ALL, 0)

    self.SetSizer(vertBoxSizer)

    self.Layout()

self.Fit()


text:
Q: Best way to plan programming for small teams? I am the Director of a small startup organisation. We currently have two programmers (one experienced, one less experienced) who are building a web application platform.
One of the greatest challenges so far is the planning process. The programmers usually are in charge of planning their own work, but we keep exceeding their self-imposed deadlines. For instance, a task that they estimate will take 2 days, ends up taking 8 days.
For me it is hard to support them in planning, as I lack the technical know-how to precisely estimate how long a certain task will last.
Do you have any idea:

*

*What is the reason for this, is this common for programmers?

*What I can do to support them in planning? Are there any methods or tools that are useful to programmers in small teams?

A: You wouldn't be the first by a long shot to try to figure out the best way to plan development time.  This is in part due to the fact that it is difficult to quantify something you cannot actually see being built, and partly due to the mythical man-month, which is a direct contrast to the intuitive idea that if you have 2 programmers, you should be able to develop twice as fast than if you had 1 programmer.
As you've probably realized already, it is a lot more complicated than that.  One approach to estimating development time as rounding a group of highly qualified individuals for what concerns software development and ask them to estimate the amount of time it would take to finish a project (explaining as detailed as possible).  You take the highest of all the estimates and you double it.  Yes, you read correctly.  You double the highest estimate and you shall have a reasonably accurate estimate.  I know, because with time, this is how I've been able to accurately tell my bosses how long it takes me to do something.  I gather the opinions of my fellow programmers and my own and double the highest estimate.  If this seems like too high of a value, consider that testing new functionality is crucial and consider potential bug fixes afterwards, and it will seem like a more reasonable figure.
In my own personal experience as a programmer, I can tell you that it helps to break down projects into milestones.  How long does it take to reach milestone 1, then from milestone 1 to milestone 2, then milestone 2 to milestone 3, etc.?  When broken down like this, the answer is usually far more accurate than trying to estimate the entire project in its entirety.  Strangely enough, if you sum up the estimates of all these milestones, it will usually be larger than the original estimate on the entire project (if the programmer is being honest with himself anyway), which only leads me to think that detail is the key here.
Perhaps you lack the technical know-how, but you should still try to follow on a more general level.  Programmers have no problems with repetition.  It's the twists and turns that occupy all the time in developing a program.  So most likely, the more functionality that you wish to include, the more complicated the program is going to become, and assuming this new functionality has no influence on previously implemented sections of the code, development will be linear according to the amount of work to be done.  Most likely, new functionality heavily influences previously implemented sections and thus development involves not just implementing the new functionality but fixing the old code, making development time exponential.
My advice to you would be to, without telling the programmers how to do their job, try to get a handle of how the program works at a general level and you should soon be able to see how new functionality would modify that behavior and thus provide a reasonable estimate on how long it would take to do it.  Combine this with their estimates (double the highest), and you start getting a better idea of how to estimate development time.
I hope that helps!

A: One of the reasons estimates are often way off is because estimation is actually quite hard and requires experience and knowledge about the system to be changed. Most often it is helpful to break big steps up into smaller ones.
Now you have many possibilities of those I will mention two:

*

*Planning Poker

*PERT (Program Evaluation and Review Technique)
Planning Poker
This works quite well in small agile teams.
Excerpt from wikipedia:

*

*A Moderator, who will not play, chairs the meeting.

*The Product Manager provides a short overview. The team is given an opportunity to ask questions and discuss to clarify assumptions and risks. A summary of the discussion is recorded by the Project Manager.

*Each individual lays a card face down representing their estimate. Units used vary - they can be days duration, ideal days or story points. During discussion, numbers must not be mentioned at all in relation to feature size to avoid anchoring.

*Everyone calls their cards simultaneously by turning them over.

*People with high estimates and low estimates are given a soap box to offer their justification for their estimate and then discussion continues.

*Repeat the estimation process until a consensus is reached. The developer who was likely to own the deliverable has a large portion of the "consensus vote", although the Moderator can negotiate the consensus.

*An egg timer is used to ensure that discussion is structured; the Moderator or the Project Manager may at any point turn over the egg timer and when it runs out all discussion must cease and another round of poker is played. The structure in the conversation is re-introduced by the soap boxes.

The important bits here are clarification, discussion, simultaneously calling the estimate, so as no bias is introduced, and consensus.
PERT
It is often hard to give one exact estimate. What is easier is to give a likelihood. PERT uses 3 values for the estimate:

*

*most optimistic time to finish (if less problems arise than expected)

*most pessimistic time to finish (if everything goes wrong - excluding major catastrophes)

*most likely time to finish (if everything goes as expected) <- this is what your developers most likely estimate right now

By weighting those three estimates you get a more reliable estimate.
t_expected = (t_opt + 4 * t_likely + t_pes) / 6

And / or you are able to use these three values to construct a probability distribution that may reflect the uncertainty of the real world even more. Beta distribution and Triangular distribution are prominent choices. Using this you can now apply statistics like "how likely is it to finish at date x given current estimates" or "if i want 95% certainty, at what point in time will it be finished".
Actually PERT consists of more than these aspects mentioned here, that I omitted for the sake of brevity.

A:
What is the reason for [their estimate of 2 days taking 8 days], is this common for programmers?

It is, if:

*

*It isn't actually clear what they're supposed to do, so they take more time getting it right (and they should then say so, not guess about how long it will take)

*They're unfamiliar with the task at hand (then they should mention that and include research in the estimate)

*The integration of the finished task with the larger product takes longer than anticipated (which might mean the product's architecture is inferior)

*The developer likes to reinvent the wheel, and doing so stumbles over problems that have been solved by others, freely available in a library

*Changes are introduced by the product owner while the task is being implemented, requiring a different approach and the redo of work already done

*The developers don't work in a productive environment (so when at home they guess it would take two days, but at work they'll require eight to compensate for all the distractions)

To name a few things.
Perhaps it's best to ask your developers why they think their estimates are way off. :-)

A: It is a fact that if you aren't keeping historical metrics then you can't even come close to giving reasonable estimates with a reasonable degree of accuracy. And asking some other company/person how long it wil take them doesn't help either. The problem is that each company and developer has their own way of doing things. Thus, every company will have different lengths of time for doing the exact same task. Each developer will have different lengths of time for doing the exact same task.
Your best course of action is to start keeping track of time and somehow figure out how to categorize the degree of difficulty for the task.  Some companies use lines of code, some use features, some just go by gut feel. Additionally, you also have to take into account if this is similar to something the developers have already built or something new, like new technology, new feature never built before by the team etc... Also, if it is an embedded or real-time system then complexity generally goes up quite a bit.
Unless you collect real data, no matter how many times your developers give you estimates they will really just be pulling numbers from their behind each time you ask them. Yes, collecting real data is a pain and at first it doesn't provide a lot of useful info, but over time it really does begin to provide reasonably accurate estimates.
I would also like to point out that estimates are generally only good over the big picture and not for short term measurements. For example, the developer estimates 2 days but it takes 8. Well the developer didn't account for having to setup a test environment and developing a simulator or that there was an entirely new technology they had to learn or they got stuck on a bug they couldn't figure out or the functionality required a refactoring of the existing system. You can't always predict those kinds of things for small tasks. However, over the course of an entire project those extra 6 days may get washed out by other tasks taking 6 days less duration.

A: The general techniques are somewhat common-sense, the important thing to know is that they don't require much technical expertise.
The starting point with planning is to identify the exact problem that needs to be solved and have a clear and unambiguous requirement. If you don't have that, your estimates will be incorrect. Having this documented in some kind of feature specification before anyone starts writing code will mean that any questions that need to be asked will have been asked before coding begins. This is a surprisingly effective timesaver. Going back and clarifying requirements breaks up one's flow as a programmer and waiting for responses can block progress.
Once you have identified the requirement you need to identify the work tasks involved in resolving it. This is a classic divide and conquer exercise - any task that can be broken down further needs to be broken down further.
In a larger team  you can use estimation poker to get an estimate based on the experience of everyone involved. That doesn't work as well in a smaller team, but it is still useful to get an independent estimate from both your developers and maybe to include one from yourself too- your lack of specific expertise can be helpful here because in explaining to you what the task involves from their perspective, the development team will probably grasp the problem better.
With a smaller team it can help to get a best/expected/worst case estimate for each task, that gives you a range of values, but if you are getting a lot of overrun estimates, you can incline towards the worst case until your devs learn to estimate more accurately.
In a small shop, developers often end up doubling as sysadmins, support team and even testers ( although of all the things they could be doing, testing is the one you should try to avoid at all costs ) so you need to account for that. Figure out how much of their time your developers actually spend working on new features and factor that into your estimates. If a task is estimated at 2 days but your devs are only able to work on new development 60% of the time, then you are going to need 4 days for it to be finished. You might be able to help with this as well by controlling the pipeline of other tasks they need to handle so that non-urgent admin or support tasks can be batched together somewhat rather than being handled on an ad-hoc basis. A lot of programmers ( certainly including myself on this one ) are not great time managers, so anything you can do to lend a hand in that respect will help. Single-tasking is always easier for programmers than multi-tasking. Blocking out time during the day can also help with this.
Keep a record - each time you have a planning session, record the estimates and actuals. You can then use this a) as a guide for how much to inflate their estimates by during planning and b) to help them refine their estimation skills. At the end of each iteration ( or whatever equivalent you have ) the whole team should review the work that was done and figure out why it took longer than expected so that this can be incorporated in future estimates. This needs to be a blameless task - you seem to have the right attitude here but this answer may be around a while so I'll make the observation. If someone says "I made a mistake here" you can turn that into "what could you have done better", but telling people they were too slow or got things wrong will only make matters worse.
I am aware of no silver bullet for this type of problem but the biggest factor is communication- which is actually easier with a smaller team -  and using feedback to refine your collective skills.

A: I have been a sole developer on a few small projects off my own and have some industrial experience working with a large team. I have noticed that the techniques that a big company uses does not necessarily work for a small team. At one point I was doing more planning and documentation rather than writing code. I suggest that you try to find a good way of working first by trying different techniques (the other answers provide some great insight) and tools, this will cost you some time and effort but you will benefit from it later on. Some tools/ techniques I found to be useful were:
-Pivotal Tracker - Great program for keeping track of stories and encourages breaking down -tasks, it is lightening quick at entering stories and automatically deduces velocity. https://www.pivotaltracker.com/.
-Gdocs for documentation as it is easy to have multiple users editing and discussing at the same time.
-At a company I used to work for we used to have a meeting for each and every story that we initiated, this meeting had to include a senior programmer since he would be better at judging how long a task would take. He would also be better at judging what the difficult part might be in a task.
In summary I believe that the key to working in small teams is to have a solid planning regime that is fast and fluid. Also any difficulties with the story can be identified early so that planning a task will keep that in mind (this could lead to building something differently).
Hope this helps


text:
Q: How to download instagram story without login in php I'm going to download Instagram story and highlights without login in Laravel.
have you any idea?
tnx for helping

A: You could use the Instagram-API (composer require mgp25/Instagram-API) if you want to build something from scratch, or you could use an existing project like:

*

*instagramStoryDownloader is using Instagram-API

*insta-story seems to do exactly what you need (without using Instagram-API library).

Example (based on Insta-story)
Gets the story of the user you select in the form (i.e. $_POST['username']) and will echo it out.
<?php
require_once 'class.instagram.php';
if (isset($_POST['submit'])) {
    $story = new instagram_story();
    $story->getStory($_POST['username']);
}
?>
<div id="center" style="text-align: center; margin-top: 300px;">
    <form action="" method="post">
        <input name="username">
        <input type="submit" name="submit">
    </form>
</div>

A: I don't think Instagram will allow that without an account
https://www.instagram.com/developer/authentication/
If you have found some documentation stating otherwise let me know a maybe I can suggest how to integrate that into laravel


text:
Q: DIV with  new line text in my project i have an xmlhttpresponse object with some node, and i need to print element of one (serps) in a div obj but formatted.
Node is like this:

now i have to create a div where store serps info like response.serps1.headline+""+response.serps1.url+""+response.serps2.headline+""+response.serps2.url ecc ecc and in my code i have tried like this:
//Data
    var divSerp3 = createElement('div', 'divSerp3', 'divSerp3css');
    if (typeof(response.serps) === 'undefined' || response.serps === null) {
        tse3 = document.createTextNode("NO DATA");
    } else {
              tse3 = document.createTextNode(response.serps[1].headline+"
"+response.serps[1].url+"

"+response.serps[2].headline+"
"+response.serps[2].url+"

"+response.serps[3].headline+"
"+response.serps[3].url+"

"+response.serps[4].headline+"
"+response.serps[4].url+"

"+response.serps[5].headline+"
"+response.serps[5].url);
    }
 divSerp3.appendChild(tse3);

but the result is like:

How can i cycle my entire serps node and insert data in a formatted mode into my div??

A: Html won't be rendered correctly in a TextNode.. as the element's name says by itself, its content is basically textual.
I suggest you to append
 separately and I would not use createTextNode().. I'd append as many childs as you need using the appropriate html elements (like spans, paragraphs, etc..) and filling their content with $.html('your content') function if you are using jQuery library or element.innerHtml if you are working with pure javascript.
Hope it helps ;)

A: You're creating a TextNode which will take all of your html and parse it as text. You want to document.createElement('br') and append those instead of doing +"

"

A: HTML won't render when inside a text node. See Is it possible to get the the createTextNode method to render html tags?
You could create
 elements and append them.
Or you could use newlines instead of
 and use CSS white-space: pre-wrap;

A: Instead of creating a text node, create an element and use innerHTML.
var divSerp3 = createElement('div', 'divSerp3', 'divSerp3css');
if (typeof(response.serps) === 'undefined' || response.serps === null) {
    tse3 = document.createTextNode("NO DATA");
} else {
    tse3 = document.createElement('span');
    tse3.innerHTML = response.serps[1].headline+"
"+response.serps[1].url+"

"+response.serps[2].headline+"
"+response.serps[2].url+"

"+response.serps[3].headline+"
"+response.serps[3].url+"

"+response.serps[4].headline+"
"+response.serps[4].url+"

"+response.serps[5].headline+"
"+response.serps[5].url);
}
divSerp3.appendChild(tse3);


text:
Q: Set yaml.schema "kubernetes" for autocompletion with nvim-lspconfig i try to get kubernetes auto completion going in nvim. I am using neovim nightly (0.5.) with 'neovim-lspconfig' and 'nvim-lua/completion-nvim'.
I installed the yaml-language-sever and it is working fine (i know it is working because it is showing errors inside yaml files in nvim).
I am fairly new to lua and nvim-lsp, it might just be a syntax error. I try to configure the server with this lua code:
local lspconfig = require'lspconfig'
lspconfig.yamlls.setup{
    on_attach = require'completion'.on_attach,
    settings = {
        yaml.schemas = { kubernetes = "globPattern" },
    }
}

I tried thousand different ways to write it but i always get Errors like:

Error loading lua [string ":lua"]:5: '}' expected (to close '{' at
line 4) near '='

The documentation just says to add server configs via the settings key. But i am not quite sure how.
Anybody got this going? Thanks a lot.

A: You should change it to
lspconfig.yamlls.setup{
    settings = {
        yaml = {
           schemas = { kubernetes = "globPattern" },
      }
}


text:
Q: Door in an infinite wall algorithm Question:

Door in a wall
You are facing a wall that stretches infinitely in both directions. There is a door in the wall, but you know neither how far away nor in which direction. You can see the door only when you are right next to it. Design an algorithm that enables you to reach the door by walking at most O(n) steps where n is the (unknown to you) number of steps between your initial position and the door.

Answer in book:

The key idea here is to walk intermittently right and left going each time exponentially farther from the initial position. A simple implementation of this idea is to do the following until the door is reached: For i=0,1,..., make 2i steps to the right, return to the initial position, make 2i steps to the left, and return to the initial position again. Let 2(k−1) < n ≤ 2k. The number of steps this algorithm will need to find the door can be estimated above as follows:

Hence the number of steps made by the algorithm is in O(n). (Note: It is not difficult to improve the multiplicative constant with a better algorithm.

Where I get lost:
I get lost when it gets to the sum. Can someone please explain to me how the sum works?? Like why did they multiply the 2k and 2i by 4 and 3? Why are they comparing it to < 7·2k? How did it equal 14·2(k-1) which is compared to < 14n. I think I get the fact that n = 2(k-1) which would explain the last past of the sum but so many questions.

A: The 4 is meant to calculate the number of full steps that represent a full search. So let's says we're at i = 1.
We start at x = 0. We go to 2 ^ 1 = 2. That's 2 steps. Then back to 0. Another 2 steps. Then to -2, then back to 0. A total of 8 steps, or 4 x 2 ^ 1
4 x 2 ^ i = number of steps in an unsuccessful search where we return to the origin to commence a larger search, since we can only traverse left and right, and not teleport
the kth iteration is when we find our door. The worst case is when the door is at n to the left where n = 2^k steps.
So what happens when we get into this iteration?
We start at x = 0, we go to 2^k to the right, then back to 0, then to the left to -2^k. A total traversal of 3 x 2 ^ k steps.
As to why it's compared to 7 * 2 ^ k, we know that the ith search term is 2 ^ (k - 1) or everything before. We can substitute 7*2^k with 7n based on our previous definition regarding k - 1 vs k
And we can also use the fact that 2^k = 2 x 2^(k-1) in our abstractions.
Per @AbcAeffchen 2^(k−1) < n is supposed, so you can substitute 2^(k−1) by n and get 14*2^(k−1) < 14n

A: In addition for @Compass's answer, we need to substitute 2^(k-1) by n, not the 2^k, since the question asks to reach/find the door, the door could be everywhere in the left when walking from initial point in kth iteration. So we have 2^(k-1)


text:
Q: only one out of 3 datanodes gets started in Hadoop? I have one master and three slave cluster. NO Virtual environment. Its all in in network.
after I do start-dfs.sh in Namenode, I see that NameNode and one of the datanode starts properly.
But other two datanodes gives the following exception (except for change in the ip address in the log). Only one out of three datanodes work at any time.
After stopping and starting clusters, I see that at any given time, only one slave (datanode) is running. but what is running seem random. sometime I have slave 1, sometime slave 2 and sometime slave 3 running.
I am not totally clear what is wrong here. but I see an unregisteredNodeException coming up in the log files of the datanodoes that fail to start
Here is the error message:
2014-06-26 13:00:54,866 INFO org.mortbay.log: Started SelectChannelConnector@0.0.0.0:50075
2014-06-26 13:00:54,870 INFO org.apache.hadoop.metrics2.impl.MetricsSourceAdapter: MBean for source jvm registered.
2014-06-26 13:00:54,871 INFO org.apache.hadoop.metrics2.impl.MetricsSourceAdapter: MBean for source DataNode registered.
2014-06-26 13:00:54,893 INFO org.apache.hadoop.ipc.Server: Starting SocketReader
2014-06-26 13:00:54,894 INFO org.apache.hadoop.metrics2.impl.MetricsSourceAdapter: MBean for source RpcDetailedActivityForPort50020 registered.
2014-06-26 13:00:54,894 INFO org.apache.hadoop.metrics2.impl.MetricsSourceAdapter: MBean for source RpcActivityForPort50020 registered.
2014-06-26 13:00:54,896 INFO org.apache.hadoop.hdfs.server.datanode.DataNode: dnRegistration = DatanodeRegistration(dig14.baker:50010, storageID=DS-1161815082-172.16.30.208-50010-1403746077641, infoPort=50075, ipcPort=50020)
2014-06-26 13:00:54,906 INFO org.apache.hadoop.hdfs.server.datanode.DataNode: Finished generating blocks being written report for 1 volumes in 0 seconds
2014-06-26 13:00:54,910 ERROR org.apache.hadoop.hdfs.server.datanode.DataNode: org.apache.hadoop.ipc.RemoteException: org.apache.hadoop.hdfs.protocol.UnregisteredDatanodeException: Data node 172.16.130.214:50010 is attempting to report storage ID DS-1161815082-172.16.30.208-50010-1403746077641. Node 172.16.130.213:50010 is expected to serve this storage.
        at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.getDatanode(FSNamesystem.java:5049)
        at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.processBlocksBeingWrittenReport(FSNamesystem.java:3869)
        at org.apache.hadoop.hdfs.server.namenode.NameNode.blocksBeingWrittenReport(NameNode.java:1109)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:616)
        at org.apache.hadoop.ipc.RPC$Server.call(RPC.java:587)
        at org.apache.hadoop.ipc.Server$Handler$1.run(Server.java:1432)
        at org.apache.hadoop.ipc.Server$Handler$1.run(Server.java:1428)
        at java.security.AccessController.doPrivileged(Native Method)
        at javax.security.auth.Subject.doAs(Subject.java:416)
        at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1190)
        at org.apache.hadoop.ipc.Server$Handler.run(Server.java:1426)

Here is my core-site.xml:
<configuration>
<property>
<name>fs.default.name</name>
 <value>hdfs://dig11:10001</value>
<!-- <value>hdfs://localhost:10001</value> -->
</property>
<property>
<name>hadoop.tmp.dir</name>
<value>/scratch/USERS/sridhar/hadoop</value>
</property>
</configuration>

A: The data on one datanode is being presented by another datanode and namenode is refusing it.
If it is a test environment and you are willing to lose any existing data in hdfs, you could cleanup the datanode directories and namenode directories and reformat DFS.
Remove all existing data in the dfs.name.dir, dfs.namenode.name.dir.
Finally reformat DFS with hdfs namenode -format


text:
Q: QGIS Atlas filter with category I want to create a QGIS Atlas on a point of interest dataset with categorical attribute poi_type.
The atlas should have a page for each type (e.g. stadium, hospital, etc.).
I can't find the right filter to set in the filter with field. QGIS keeps cycling over each feature, as opposed to cycling over each unique value of poi_type. Any tip?

A: You have to make a separate table with one entry per poi_type.  Then you can use that as coveragelayer to loop through.  More info on this post: https://gis.stackexchange.com/a/287540/7849


text:
Q: WPF: How to get value of ListView element on which i called context menu? I have listview in "gridview style" with 2 columns. I wonder how to get first column value of item on which i called context menu (CM has one button only where i want to handle value)?
Here is XAML:
        <ListView.Resources>
            <ContextMenu x:Key="ContextMenu">
                <MenuItem Header="Run test with parameters" x:Name="runTestWithParams" Click="runTestWithParams_Click" />
            </ContextMenu>
        </ListView.Resources>
        <ListView.ItemContainerStyle>
            <Style TargetType="ListViewItem">
                <Setter Property="ContextMenu" Value="{StaticResource ContextMenu}"/>
            </Style>
        </ListView.ItemContainerStyle>

And here is contextMenu button handeler:
    private void runTestWithParams_Click(object sender, RoutedEventArgs e)
    {
        string valueOfFirstColumn = // something like ItemThatWasClicked["ID"].ToString();
    }

If you have any ideas please help me.
SOLUTION FOUND
It was necessary to create handler of RightMouseUp event and get value I need from its sender,
because of Context_Menu_button_Click's sender does not contain info about item it was clicked on, but contains info about ContextMenu.
So... I handled it like this:
Handler:
    private void HandleMouseRightButtonUp(object sender, MouseButtonEventArgs e)
    {
        ListViewItem selected = sender as ListViewItem;
        String valueINeed = (selected.Content as TestIdentification).Id;
    }

XAML:
<Style TargetType="ListViewItem">
                <EventSetter Event="MouseRightButtonUp" Handler="HandleMouseRightButtonUp" />
</Style>

Thanks for all!

A: Another solution is to handle the ContextMenuOpening event on the ListView. From there, you can access the ContextMenuEventArgs.OriginalSource property in order to get the element from which the event originates.

A: Your problem is a common one... the ContextMenu is not part of the main visual tree that the rest of your controls are in and so it does not have the correct DataContext by default. However, you'll be glad to hear that it is relatively simple to fix this. I generally use the Tag property to pass the DataContext to the ContextMenu:
<ListView.Resources>
    <ContextMenu x:Key="ContextMenu" DataContext="{Binding PlacementTarget.Tag,
        RelativeSource={RelativeSource Self}}">
        <MenuItem Header="Run test with parameters" x:Name="runTestWithParams"
            Click="runTestWithParams_Click" />
    </ContextMenu>
</ListView.Resources>
<ListView.ItemTemplate>
    <DataTemplate DataType="{x:Type YourNamespace:YourDataType}">
        <Grid Tag="{Binding DataContext, RelativeSource={RelativeSource Self}}"
            ContextMenu="{StaticResource ContextMenu}">
            <!--Define what your data objects look like here or just use this-->
            <TextBlock Text="{Binding}" />
        </Grid>
    </DataTemplate>
</ListView.ItemTemplate>

Now, I've not done this quite in this way before, so we might have some problems to work through, but give this a go anyway. When the user clicks on the MenuItem, you should now have access to the data object using the sender.DataContext property. Let me know how it goes.


text:
Q: Eclipse RCP, translate the dependency plugins When I am developing an Eclipse RCP application, what is the easiest way to translate those strings in the plugins required by my application into Chinese? As I know, these plugins already have a Chinese version at Babel project. How can I use the existing Babel translations?

A: Install Babel from its update site. Then restart eclipse, it will use the language corresponding to your system locale, or launch eclipse with -nl <locale> option


text:
Q: I assigned str("exit") to break a while loop and its throwing a conversion error? I am trying to break a while loop with user input "exit" in a try-except block where the input is converted to float.
My code currently looks like this:
def checkGrade():
while True:
    try:
        floatGrade = float(input("Enter student grade: "))
        if floatGrade == 100:
            return("A+")
        # I go down the list of grades to F after this if.
    except:
        if floatGrade == "exit":
    # This is where I want the code to break, but it gives me an error when I print the function def checkGrade()
            break
        else:
            continue

I get an error

could not convert string to float: "exit"

Any thoughts? Thanks in advance for your help!

A: I would restructure the code to collect the input first and try to convert it to a float in the try/except, so if it fails the original input value is kept.
def checkGrade():
    while True:
        floatGrade = input("Enter student grade: ")
        try:
            floatGrade = float(floatGrade)
        except ValueError:
            if floatGrade == "exit":
                break
        else:
            if floatGrade == 100:
                return("A+")

A: There is no point of putting continue in except block as the loop will automatically continue.
def checkGrade():
       while True:
           try:
                floatGrade = input("Enter student grade: ")
                if float(floatGrade) == 100.0:
                     return("A+")
                # I go down the list of grades to F after this if.

           except:
                if floatGrade == "exit":
                     print('breaking the loop with code exit')
                     break
                else:
                     print('please enter only float values...')

 res=checkGrade()

 #added here
 if res:
    print(res)
 else:
    print('You chose the exit command !!')

Suggestion :
for checking the value between 2 value, you may use

if number >= 10000 and number <= 30000:

But we can optimize it further with

if 10000 <= number <= 30000

for more


text:
Q: Запуск терминала без видоядра Пытаюсь собрать максимально дешёвый сервер, столкнулся с вопросом - нужно ли видеоядро (или видеокарта) для терминала линукса?

A: Если делать на домашнем железе, то скорее всего нужно. Многие прошивки BIOS не запустятся без видео. Самому линуксу видеоядро не нужно.


text:
Q: Elasticsearch: search and show results to users, Scroll API I am new to Elasticsearch. I am confused by the Scroll API at
http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-scroll.html

Scrolling is not intended for real time user requests, but rather for
  processing large amounts of data, e.g. in order to reindex the
  contents of one index into a new index with a different configuration.

What I need is:

*

*A user types a search phrase and clicks the search button

*The program searches Elasticsearch for the first page of results

*Show the first page of results to the user, and if he clicks "next page" or jumps to another later page, the program displays the results for that page.

The following are two ways that I find:
SearchResponse scrollResp = client.prepareSearch("book")
        .setTypes("children")
        .setQuery(query)
        .setSize(20).execute().actionGet();

SearchResponse scrollResp = client.prepareSearch("book")
        .setTypes("children")
        .setSearchType(SearchType.SCAN)
        .setScroll(new TimeValue(60000))
        .setQuery(query)
        .setSize(20).execute().actionGet();

Which should I use?
Thanks and regards!

A: You should use from and size parameters to control pagination, from is the start index, and size is the items per page.
SearchResponse scrollResp = client.prepareSearch("book")
    .setTypes("children")
    .setQuery(query)
    .setFrom(20)
    .setSize(20).execute().actionGet();

http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-from-size.html


text:
Q: Getting the Field Alias from a layer, from within a Map document I've got a very simple script, that loops through all the layers in a mxd and loops through the fields, and prints out the Alias Name for the field, but I am having some problems, it seems to be printing the field alias of the feature class (in SDE) not the value I have changed it to  in the map document...
Here's the script
import os, arcpy

myMxdFolder = r"D:\Maps"
count = 0

for mxd in os.listdir(myMxdFolder):
    #print mxd
    if mxd.endswith(".mxd"):
        #if mxd.startswith("COMPASS") or mxd.startswith("COLGIS"):
        if mxd.startswith("COLGIS_City_Occupiers.mxd"):
            mxdoc = arcpy.mapping.MapDocument(myMxdFolder + os.sep + mxd)
            filePath =  mxdoc.filePath
            print filePath
            for lyr in arcpy.mapping.ListLayers(mxdoc):
                desc = arcpy.Describe(lyr)
                print lyr.name
                fields = desc.fields
                for field in fields:
                    print field.aliasName

The output is
OBJECTID
UPRN
ADDRESS
OCCUPIER
SHAPE

but the Aliases in the map document i have set it to are:
OBJECTID
HIGHLIGHT::UPRN
Address
Occupier
SHAPE

and that is what I was expecting, have a missed a trick somewhere in the code?

A: Unfortunately, I think your answer can be found from this excerpt from this ESRI  Help Document on Layer

Not all layer properties are accessible through the Layer object.
  There are many properties available in the ArcMap Layer Properties
  dialog box that are not exposed to the arcpy scripting environment
  (e.g., scale ranges, display properties, field aliases, symbology, and
  so on). The UpdateLayer function allows you to replace all layer
  properties available in ArcMap's Layer Properties dialog box using a
  layer (.lyr) file that contains the customizations.

It specifically references field aliases and the Layer Properties dialog.
This might be something worth submitting an idea to the ArcGIS Ideas site.


text:
Q: Debugging Program, looking for data spike So my program, is looking for a spike of 100(psi) so when it prints at data point 0, it should be 100 higher then -1. Although Ive been working with it all day and for the life of my I cannot get it to capture the spike. Ive added conditionals, taken them away, and no matter what I can perfect it. Can someone look at my code and find a good way to capture the spike?
My code so far:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>

#define MAX_CHANGE      100
#define ARRAY_SIZE      21

typedef struct data_slice
{
        int t;          // -> Time
        float tp;       // -> Valve pressure
    float tf;       // -> Sodium flow
    float tt;       // -> Sodium temp in Celsius
} data_slice;

// Function Declarations
void get_values(float * pressure, float * flow, float * temp);
void printIt(data_slice * data);
void initializeArray(data_slice * data);
bool spikeValueRecorded(data_slice * data, int outputIndex);

int main()
{
    srand((unsigned int)time(NULL));
    data_slice data[ARRAY_SIZE];
    int index = -1;

    while (1)
    {
        // Initialize the entire array
        initializeArray(data);

                    // If there's a spike.....
        if (spikeValueRecorded(data, index))
        {
            // Set the previous "time" in array to negatives
                int temp = index;
            if (index < MAX_CHANGE)
            //index = index + ARRAY_SIZE;
            for (int i = 0; i >= -10; --i)
            {
                data[temp].t = i;
                temp = temp - 1;
                if (temp < 0)
                    temp = temp + ARRAY_SIZE;
            }

                // Record for 10 more seconds
            for (int i = 0; i <= 10; ++i)
            {
                data[index].t = i;
                index = (index + 1) % ARRAY_SIZE; //         Increment the index of the circular array
                get_values(&data[index].tp, &data[index].tf,    &data[index].tt);       // "Record" the values
            }
            break;
        }
    }
    // Print the finished recording
    printIt(data);
}

// Return: void
// in - Values of the data_slice struct
//
// Description: The three values of the struct (data_slice) to be filled in
void get_values(float * pressure, float * flow, float * temp)
{
    *pressure   = (float)(rand() % (700 - 500 + 1) + 500);  //    Range: 500 - 700
    *flow       = (float)(rand() % (20 - 10 + 1) + 10);     //   Range: 10 - 20
    *temp       = (float)(rand() % (200 - 100 + 1) + 100);  //  Range: 100 - 200
}

// Return: void
// in - The array of data_slice
//
// Description: Prints the entire array being passed in
void printIt(data_slice * data)
{
    // Find the indice holding the time value of -10
     int indice = 0;
    for (int i = 0; i < ARRAY_SIZE; ++i)
    {
        if (data[i].t == -10)
        {
            indice = i;
            break;
        }
    }

    for (int i = 0; i < ARRAY_SIZE; ++i)
    {
        printf("%i\t %f\t %f\t %f\n", data[indice].t, data[indice].tp,    data[indice].tf, data[indice].tt);
        indice = (indice + 1) % ARRAY_SIZE;
    }
}

// Return: void
// in - The array of data_slice
//
// Description: Initializes the entire array to random values and their   times to 0
void initializeArray(data_slice * data)
{
    for (int i = 0; i < ARRAY_SIZE; ++i)
    {
        data[i].t = 0;
        get_values(&data[i].tp, &data[i].tf, &data[i].tt);
    }
}

// Return: boolean
// in - The array of data_slice
// out - Indice of the pressure spike
//
// Description: Returns true if a positive spike in pressure has been   recorded.
//      outputIndex will hold the 0-indice of the pressure spike, else -1
bool spikeValueRecorded(data_slice * data, int outputIndex)
{
    float oldValue = data[0].tp;
    for (int i = 0; i < ARRAY_SIZE; ++i)
    {
        if (data[i].tp - oldValue < MAX_CHANGE)
        {
            outputIndex = i;
            return true;
        }
    }
    outputIndex = -1;
    return false;
}

A: You can't do output through a pass-by-value parameter.
Try changing
 bool spikeValueRecorded(data_slice * data, int outputIndex)

to
 bool spikeValueRecorded(data_slice * data, int *outputIndex)

and then update the assignments to *outputIndex = i; and *outputIndex = -1;, respectively.
Finally, at the call site, pass index by reference.  I.e.,
if (spikeValueRecorded(data, &index))


text:
Q: Corange and Range Proof
Prove that if $\{\mathbb{v_1},\ \cdots,\ \mathbb{v_r}\}$ are a basis of $\rm{col}(A^\mathrm{T})$ then their images
  $\{Av_1,\ \cdots,\ Av_r\}$ are a basis for $\rm{col}(A)$.

How will I be able to prove this and what do they mean by image? Does it mean projections?

A: This follows from a very fundamental fact of linear algebra.
Let me give you a sketch on how to proceed. Let $A$ be an $m\times n$ matrix.

*

*Prove that the nullspace and the rowspace are orthogonal complements.

*Conclude that $\mathbb{R}^m = \rm{col}(A^\mathrm{T}) \oplus \ker(A)$

*Form a basis of $\mathbb{R}^m$ as a union of the basis of the rowspace and the nullspace. Suppose that we have $\mathcal{B}\cup\mathcal{C}$ where
$$\mathcal{B}=\{\mathbb{v_1},\ \cdots,\ \mathbb{v_r}\},\ \ \ \ \ \mathcal{C}=\{\mathbb{u_1},\ \cdots,\ \mathbb{u_{m-r}}\}$$
such that $\mathcal{B}$ is a basis for the rowspace and $\mathcal{C}$ is a basis for the nullspace.

*Show that the set $\{A\mathbb{v_1},\ \cdots,\ A\mathbb{v_r}\}$ spans the image of $A$.

*Show that the same set above is linearly independent.

Edit: A bit of elaboration on the different definitions.
When we say the image of a matrix, we really mean the set of outputs of that matrix as a linear mapping. To be specific, the image of an $m\times n$ real matrix $A$ is the set
$$\rm{Im}(A) = \{\mathbf{x} \in \mathbb{R}^n\mid \mathbf{x} = A\mathbf{y}\ \text{for some }\mathbf{y}\in\mathbb{R}^m\}$$
This is sometimes called the range, although image seems more common in my experience. In either case, in this context range and image (and sometimes co-domain) are all taken as synonyms. You can show that the image of $A$ is just the columnspace of $A$, so the columnspace is sometimes taken as another synonym.
Image is sometimes also used for a single vector. We sometimes say the image of $\mathbf{x}$ under $A$ and what this term means is that we are considering the vector that $\mathbf{x}$ is mapped to using $A$; this is the $A\mathbf{x}$.


text:
Q: Image Similarity on Swift + CoreML I Built a Similarity Image Model with Turi create and am experiencing problems for its implementation on CoreML.
Once exported the template with the CreateML format how can I get the distance from a certain input image.
The official documentation speaks only about the implementation of the request but not about how to make it.
Following I included the code that I used for the test (the turi create documentation tells me to use the main CoreML Classification example to work with similarity, but the result variable results empty after the request)
override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
    do {
        let request = try getRequest()

        guard let cgImage = UIImage.init(named: "test-image")?.cgImage else {
            return
        }

        let handler = VNImageRequestHandler(cgImage: cgImage, orientation: .up)

        try handler.perform([request])
    } catch {
        debugPrint("Ho incontrato un errore non previsto \(error)")
    }

}

private func getRequest() throws -> VNCoreMLRequest {
    let model = try VNCoreMLModel(for: containerChecker.init(configuration: MLModelConfiguration()).model)

    let request = VNCoreMLRequest(model: model, completionHandler: requestDidComplete)
    request.imageCropAndScaleOption = .centerCrop
    return request
}

private func requestDidComplete(request: VNRequest, error: Error?) {
    print(request)
}

func processQuery(for request: VNRequest, error: Error?, k: Int = 5) {
    DispatchQueue.main.async {
        guard let results = request.results else {
            self.referenceRanking.text = "Unable to rank image.\n\(error!.localizedDescription)"
            return
        }

        let queryResults = results as! [VNCoreMLFeatureValueObservation]
        let distances = queryResults.first!.featureValue.multiArrayValue!

        // Create an array of distances to sort
        let numReferenceImages = distances.shape[0].intValue
        var distanceArray = [Double]()
        for r in 0..<numReferenceImages {
            distanceArray.append(Double(truncating: distances[r]))
        }

        let sorted = distanceArray.enumerated().sorted(by: {$0.element < $1.element})
        let knn = sorted[..<min(k, numReferenceImages)]

        self.referenceRanking.text = String(describing: knn)
    }
}

Anyone has some advices? Thanks in advance.


text:
Q: Map Pandas Series Containing key/value pairs to a new columns with data I have a dataframe containing a pandas series (column 2) as below:

column 1
column 2
column 3

1123
Requested By = John Doe 1\n     Requested On = 12 October 2021\n Comments = This is a generic request
INC29192

1251
NaN
INC18217

1918
Requested By = John Doe 2\n     Requested On = 2 September 2021\n Comments = This is another generic request
INC19281

I'm struggling to extract, split and map column 2 data to a series of new column names with the appropriate data for that record (where possible, that is where there is data available as I have NaNs).
The Desired output is something like (where Ive dropped the column 3 data for legibility):

column 1
column 3
Requested By
Requested On
Comments

1123
INC29192
John Doe 1
12 October 2021
This is a generic request

1251
INC18217
NaN
NaN
NaN

1918
INC19281
John Doe 2
2 September 2021
This is another generic request

I have spent quite some time, trying various approaches, from lambda functions to comprehensions to explode methods but havent quite found a solution that provides the desired output.

A: First I would convert column 2 values to dictionaries and then convert them to Dataframes and join them to your df:
df['column 2'] = df['column 2'].apply(lambda x:
                                       {y.split(' = ',1)[0]:y.split(' = ',1)[1]
                                       for y in x.split(r'\n ')}
                                       if not pd.isna(x) else {})
df = df.join(pd.DataFrame(df['column 2'].values.tolist())).drop('column 2', axis=1)
print(df)

Output:
   column 1  column 3 Requested By      Requested On                         Comments
0      1123  INC29192   John Doe 1   12 October 2021        This is a generic request
1      1251  INC18217          NaN               NaN                              NaN
2      1918  INC19281   John Doe 2  2 September 2021  This is another generic request


text:
Q: Stripping server side comments in Python In JSP:
<%-- Comments removed in server --%>

What is the equivalent when I run in Python/Django ?!?
I don't want the HTML comments visible in the client side...

A: {% comment %}

add your comment here :-)

{% endcomment %}

A: You can use Django template comment block http://docs.djangoproject.com/en/dev/ref/templates/builtins/#comment
They won't be displayed on the client side, but you will see it when editing templates.


text:
Q: regex select a block of html code? I need to select a block of code so I can remove it using TextSoap.
How can I select everything from the opening "< !DOCTYPE" to the first "< h1>"?
Thanks.

A: A general regex could look like '^<!DOCTYPE(.|\n)*?<h1>' but like the commenters said correctly, what language are you using? Languages may have different ways of dealing with regexes. You can also try this: http://regexpal.com/


text:
Q: Error creating token via softhsm2 as non-root user "Could not initialize the library" Whilst initializing a token via softhsm2-util as a non-root user I receive the following error:
$ softhsm2-util --init-token --slot 0  --label "test" --so-pin 5462 --pin 8764329

ERROR: Could not initialize the library.

How can I fix this?

A: Whilst initializing token as a non-root user, we invariably try to access the default /etc/softhsm/softhsm2.conf which points tokens to be staged under /var/lib/softhsm/tokens whose ownership/permission is limited to be used by root and its associated groups.
Changing ownership/permission of /var/lib/softhsm/tokens doesn't solve the problem as we cannot access /etc/softhsm/softhsm2.conf in the first place given the access limitation, so we should be doing this instead:
cd $HOME
mkdir -p $HOME/lib/softhsm/tokens
cd $HOME/lib/softhsm/
echo "directories.tokendir = $PWD/tokens" > softhsm2.conf
export SOFTHSM2_CONF=$HOME/lib/softhsm/softhsm2.conf

$ softhsm2-util --init-token --slot 0 --label "test" --so-pin 5462 --pin 8764329
The token has been initialized.


text:
Q: Exact area using limits and Riemann sum the i need to find the exact area under tha curve of the function $f(x)=4+3x-x^2$ on the interval $[-1,3]$ using limits and a Riemann Sum. I have nothing started, because I am confused on where to start, and where I would need to go from there, I need help with the entire problem. I hope someone can help me! Thanks

A: Some ideas for you to understand, prove and develop:
$$f(x)=-x^2+3x+4$$
and since this is a continuous and thus integrable function in any finite interval, we can choose now  partitions of the interval $\,[-1,3]\;$ and choose conveniently the points within each subinterval in each partition, say:
$$\forall\,n\in\Bbb N\;;\;\;P_n:=\left\{x_0:=-1\,,\,x_1:=-1+\frac4n\,,\,x_2:=-1+\frac8n\,,\ldots\,,\,x_n=-1+\frac{4n}n=3\right\}$$
and we choose conveniently in each subinterval
$$c_k=\left(-1+\frac{4k}n\right)\in [x_{k-1},x_k]\;,\;k=1,2,\ldots,n$$
so we get the Riemann sum
$$\sum_{k=1}^nf(c_k)(x_k-x_{k-1})=\frac4n\sum_{k=1}^n\left[-\left(-1+\frac{4k}n\right)^2+3\left(-1+\frac{4k}n\right)+4\right]=$$
$$=\frac4n\sum_{k=1}^n\left[-\frac{16k^2}{n^2}+\frac{20k}n\right]=\frac{16}{n^3}\sum_{k=1}^n\left(-4k^2+5nk\right)=$$
$$\frac{16}{n^3}\left(-4\frac{n(n+1)(2n+1)}6+5n\frac{n(n+1)}2\right)=$$
$$=-\frac{32}3\frac{n(n+1)(2n+1)}{n^3}+40\frac{n^2(n+1)}{n^3}\xrightarrow[n\to\infty]{}\ldots?$$


text:
Q: How to compute Frechet Derivatives that involve matrices. Suppose I have a linear operator which maps $S^n\to\mathbb R^{n \times n}$. It is represented as $LX:= XA^T + AX.$ How can I find the Frechet derivative of $f(X) = XA^T + AX.$

A: I will give the same proof included in https://math.stackexchange.com/a/3956281/864940.
The definition of Frechet derivative is the following
$\boldsymbol{Definition:}$ Let $\boldsymbol{V}$, $\boldsymbol{W}$ be vector spaces with norms $||.||_V, ||.||_W$. A function $f:\boldsymbol{V} \rightarrow \boldsymbol{W}$ is called Frechet differentiable at $\hat{x} \in \boldsymbol{int\ dom}f$, if $\exists$ a bounded linear operator $Df(\hat{x}): \boldsymbol{V} \rightarrow \boldsymbol{W}$ s.t.,
$$\lim_{x\rightarrow \hat{x}\\x \in \boldsymbol{int\ dom}f\\x \neq \hat{x}} \frac{||f(x) - f(\hat{x}) - Df(\hat{x})(x-\hat{x})||_W}{||x - \hat{x}||_V} = 0$$
If $f:\boldsymbol{V} \rightarrow \boldsymbol{W}$ is Frechet differentiable at $\hat{x}$, then $Df(\hat{x})$ is called the Frechet derivative of $f$ at $\hat{x}$.
$\boldsymbol{Claim}:$ Let $f:\boldsymbol{S}^n \rightarrow \boldsymbol{R}^{n \times n}$ be the given function such that $f(X) = AX +XA^T$. Then, Frechet derivative $Df(\hat{X})$ of $f$ is the linear operator given by $Df(\hat{X}) = f$, i.e., $$ Df(\hat{X})(X) = AX + XA^T$$
$\boldsymbol{Proof}:$ Let $ Df(\hat{X})(X) = AX + XA^T$, and consider the following limit,
$$\lim_{X\rightarrow \hat{X}\\X \in \boldsymbol{int\ dom}f\\X \neq \hat{X}} \frac{||f(X) - f(\hat{X}) - Df(\hat{X})(X-\hat{X})||}{||X - \hat{X}||} = \lim_{X\rightarrow \hat{X}\\X \in \boldsymbol{int\ dom}f\\X \neq \hat{X}} \frac{||(AX + XA^T) - (A\hat{X} + \hat{X}A^T) - Df(\hat{X})(X-\hat{X})||}{||X - \hat{X}||} = $$
$$\lim_{X\rightarrow \hat{X}\\X \in \boldsymbol{int\ dom}f\\X \neq \hat{X}} \frac{||[A(X-\hat{X}) + (X-\hat{X})A^T] - [A(X-\hat{X}) + (X-\hat{X})A^T]||}{||X - \hat{X}||} = \lim_{X\rightarrow \hat{X}\\X \in \boldsymbol{int\ dom}f\\X \neq \hat{X}} \frac{||0||}{||X - \hat{X}||} = 0$$
Since the above limit goes to zero with the given operator, it is the Frechet derivative of the function $f$ at $\hat{X}$, i.e., $Df(\hat{X}):\boldsymbol{S}^n \rightarrow \boldsymbol{R}^{n \times n}$ such that $Df(\hat{X})(X) = AX + XA^T$. $\blacksquare$

A: The best linear approximation to a function that is already linear is the function itself. So $DL(X) = L$.