text:
Q: getIntent error, doesnt get recognized getIntent does not get recognized, what I am doing wrong?
I get this error:

error: cannot find symbol variable getIntent

PS: at first I got this error cannot find symbol method getIntent.
My code:
package com.example.r.app;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import java.util.List;

public class MyAdapter extends ArrayAdapter<String> {

    int i=0;

    public MyAdapter(Context context, int resource, List<String> objects) {
        super(context, resource, objects);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = super.getView(position, convertView, parent);
        TextView textView = (TextView) view.findViewById(android.R.id.text1);

        Intent intent = getIntent;
        int[] barva = intent.getIntArrayExtra("barva");

        int[] bar = {1, 2, 3};

        if (position == i) {
            if (barva == bar){
                textView.setTextColor(0xffcc80);
            }
            else if (barva == bar){
                textView.setTextColor(0xa5d6a7);
            }
            else if (barva == bar){
                textView.setTextColor(0x80deea);
            }

        }
         return view;
    }

}

A: getIntent is a method. Inside an activity try:
Intent intent = getIntent();

Edit:
I didnt really noticed you're inside an Adapter. If your context relates to the activity, you have to do it slightly different:
Intent intent = ((Activity) context).getIntent();

A:
error: cannot find symbol variable getIntent

First,getIntent is method instead of variable so call it as:
Intent intent = getIntent();

Second, getIntent() method is from Activity class instead of ArrayAdapter class so this method is not available in class which is extending ArrayAdapter.
Call getIntent() method from Activity in which creating object of  MyAdapter and pass intent as parameter to constructor.

A: Or you can write in your class declaration:
public class nameofyourclass extends AppCompatActivity {


text:
Q: Serial ports on Windows or Ubuntu VBox to talk to Arduino from Python I have an Arduino microcontroller listening on COM3. Using the arduino IDE and the Serial monitor works fine to send and receive data.
I would like to send and receive data from Python, but it's not immediately obvious how to do so. (I'd also be fine doing it in C# if it was substantially easier.)
I found arduino_serial.py, but it only works for Unix. Fortunately, I have a Ubuntu 10.10 VBox set up. However, I have no idea if that VM can access serial ports or if special steps are required to do so.
I also found pySerial, which looks pretty legitimate. However, I'm also unsure how to use it. It wants serial port names. How do I find out what valid values for these are?
For example, pySerial mentions that you can "Open named port at "19200,8,N,1", 1s timeout" with the following command:
>>> ser = serial.Serial('/dev/ttyS1', 19200, timeout=1)

But I have no idea how you would know that /dev/ttyS1 was a valid port name.
Is there good documentation for getting started on this?
Update: I'm using Ubuntu with arduino_serial, but still having trouble.
This program is running on the Arduino:
void setup() {
  Serial.begin(9600);
}

void loop() {
  if (Serial.available()) {
    Serial.print((char)Serial.read());
  }
}

I see that a port called tty0 is available:
foo@bar:~/baz$ dmesg | grep tty
[    0.000000] console [tty0] enabled

I then try to connect with arduino_serial:
foo@bar:~/baz$ sudo python
[sudo] password for foo:
Python 2.6.6 (r266:84292, Sep 15 2010, 15:52:39)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import arduino_serial
>>> sp = arduino_serial.SerialPort("/dev/tty0", 9600)
>>> sp.write("foo")
>>> sp.read_until("\n")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "arduino_serial.py", line 107, in read_until
    n = os.read(self.fd, 1)
OSError: [Errno 11] Resource temporarily unavailable

Why am I getting this error? What am I doing wrong?

A: pySerial may or may not be built in to Python. Regardless, if it's not, pySerial is the library to download and install.
And since you already know the Arduino is on COM3, just use this:
import serial
ser = serial.Serial("COM3", 19200, timeout=1)
ser.write("Whatever")

For a Linux box, it's relatively easy to find out what serial port your Arduino is using:
dmesg | grep tty

This will give you some output similar to this: [    7.944654] usb 1-1.6: FTDI USB Serial Device converter now attached to ttyUSB0
So my Arduino is on ttyUSB0. This means you can use the following code to talk to the Arduino on a Linux box:
import serial
ser = serial.Serial("/dev/ttyUSB0", 19200, timeout=1)
ser.write("Whatever")

Note: If you use a baud rate of 9600 on the Arduino, as most people do, you can simply use serial.Serial("COM3") or serial.Serial("/dev/ttyUSB0") without any other parameters.
EDIT:
You should also keep in mind that in the real world, it may take a second to actually open the port and get it ready for transmitting data. This means that performing a write IMMEDIATELY after the serial.Serial() call may not actually do anything. So the code I would use is as follows:
import serial
import time
ser = serial.Serial("/dev/ttyUSB0", 19200, timeout=1)
time.sleep(1.5)
ser.write("Whatever")

Kind of a hack, but it's the only way I know how to get it to work on my system.

A: The serial ports are named COM1 onwards on Windows, /dev/ttyS0->COM1. I wrote some code in Python for our Quadcopter controller which works both on Windows and Linux (given you supply the port name properly) using Pyserial.
Try passing COM3 to Pyserial on Windows. On the VM you will have to first pass the USB-to-serial adapter to the VM or set up the serial ports section (I use VirtualBox). If you go the USB route the serial devices are enumerated under /dev/ttyUSBxx.

A: I have a project called Yaam on CodePlex that uses C# to send data through the serial port.  Check that out for an example.  On the C# side (see Yaam\Yaam.xaml.cs), simply use the SerialPort class in the System.IO.Ports namespace.  Once you instantiate the object and set the properties (baud rate, com port, etc), simply call.Open() .  There are also plenty of other examples on the web.  Take a look at these:

*

*http://jtoee.com/2009/02/talking-to-an-arduino-from-net-c/

*http://www.instructables.com/id/Interfacing-your-arduino-with-a-C-program/

A: "But I have no idea how you would know that /dev/ttyS1 was a valid port name."
PySerial's serial port initialiser accepts a number instead of a name as an argument. These numbers will correspond to "normal" serial ports (/dev/ttySX on Linux, COMX on Windows). You can then get the name from the created object. There's no way to know in advance what numbers to try, though, so as you'll see in the following code, you just have to try and fail.
This won't always discover simulated ports (created using socat or com0com), or USB ports though, so for those you need to use the glob module (I don't think it makes a huge difference whether you use globbing or indices for the dev/ttySX device nodes). This is what pySerial's own examples do. The following code is adapted from those examples:
import glob, os

import serial

USB_SERIAL_GLOB = "/dev/ttyUSB*"

def try_open(port, args = (), kwargs = {}):
    try:
        port = serial.Serial(port, *args, **kwargs)
    except serial.SerialException:
        return None
    else:
        return port

def serial_scan(max_range = 32, args = (), kwargs = {}):
    for i in range(max_range):
        port = try_open(i, args, kwargs)
        if port is not None:
            yield port

    # Look for USB serial ports:
    if os.name == 'posix':
        for fn in glob.glob(USB_SERIAL_GLOB):
            port = try_open(fn)
            if port is not None:
                yield port

if __name__ == "__main__":
    for port in serial_scan(kwargs = {'baudrate':9600, 'timeout':0.5}):
        port.close()
        print "Found: %s" % port.name

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why does logging an array to console before and after an operation on it show the same output in each case For example, I start with:
        var currentHistory = ['t1', 't2', 't3', 't4', 't5'];
        console.log(currentHistory);

I then swap an element and log again:
        var tmp = currentHistory[2];
        currentHistory[2] = currentHistory[0];
        currentHistory[0] = tmp;

        console.log(currentHistory);

Only to see that the output is the same in each case.
        Array[5] 't3', 't2', 't1', 't4', 't5'

        Array[5] 't3', 't2', 't1', 't4', 't5'

This inconsistency in space and time sent me quite mad last night and an answer would be appreciated.

A: Good question! Try this:
console.log(currentHistory.slice(0));

Notice now the big ball of wibbly-wobbly, timey-wimey stuff has resolved into a simple line from A to B?
This is actually an issue with how the console works. When you log an object, some browsers (particularly Chrome) log a reference to the object so you can browse it freely. However, if the object changes... it doesn't work as expected.

A: according to THIS your code works fine.
im using chrome Version 34.0.1847.131 m


text:
Q: The phrase "Tasks are thread-less" causing a brain feeze In this presentation, when Stephen Clearly describing following slide (~12 minutes in the video)  states that two tasks created in this code are thread-less. This sentence confuses me a lot.

Here are my questions.

*

*He said that task calling a Delay is thread-less and its represents a timer. However that timer must be running waiting for 2 seconds to be over. Wouldn't that timer code counting the the timer to be elapsed has to run on some thread?

*He then said that the task for calling the GetStringAsync API represents a network call but again whatever piece of code that's waiting on that network call to finish must be hosted somewhere. Where does that code live?
What am I missing understanding concept of task been thread-less in Async world when my thinking always been that a code always "run" under a thread.


text:
Q: Executing Scala via TextMate I am going through the Scala book i bought and am trying to get TextMate to cooperate

I got the point where:

*

*Fails

*Works

*Fails (understandably why) main is missing

*What is it?

*What is it?

*What is it?

What the difference between :

*

*Run Script

*Run as script

What are options 4,5,6?

A: Don't know why it gives you two run script options, but scala REPL is an interactive scala console. You can execute any scala statements on the fly with it. Option 4 will just start a console, option 5 I suppose with preload everything you have in your file, so you don't have to import everything yourself. 6 will start a console and let you execute whatever you selected.
Here's more about REPL: http://www.scala-lang.org/node/2097


text:
Q: Windows 8 boot failure, crashed after update My laptop - ASUS N53SM
I recently upgraded to windows 8. Everything worked just fine. But when windows updated to one of the updates (cant say exact one), it suddenly crashed. Just after installing updates my computer restarted, and when it should already show my account picture to log on - black screen. Nothing happens. I tried automatic repair, and also windows 8 recovery drive flash disk, where no restore was available, also i didn't have no saved image. Tried some CMD commands in recovery, but with no success. Can you please advise me for this. Im out of luck, cant get my boot work.

A: Just out of amusement, try power cycling the monitor.  That worked for me on Windows 7 when it hung up like that.  No guarantees however on that one.
Having just come though a Win 7 / 64 bit system ... performing all the possible recovery steps possible AND although having backup but finding them useless during the recovery process (missing a disk driver)....
my only recourse was to reinstall.
One thing of interest, it will basically establish a new c:\windows directory and move your old c:\windows directory to c:\windows.old.  Generally, it will not disturb other things on the disk.  This little feature saved me as I could copy some of my registry settings from the c:\windows.old area to use in the new area.  And data not directly involved with Windows remained untouched.
Good luck...I feel your pain!

A: Did you try F8 during boot, then Last Known Good Configuration? That usually helps after a bad update. It restores the system to the state it was in during the last successful log on. Either that or you can try using system restore in safe mode as the PC should have created a restore point before it installed the updates, assuming you don't get a black screen when you try to get into safe mode as well.


text:
Q: How to override widget in the Plone control panel LinguaPlone uses the MultiSelect widget for selecting multiple languages. Something like an InOut widget or even a MultiCheckBox widget will be a better user interface as it is hard to see all the  selected languages from a long list.
I tried to override the FormFields using:
form_fields['available_languages'].custom_widget = MultiCheckBoxWidget

as suggested in the zope.formlib docs, but am getting a traceback as follows:
Traceback (innermost last):
  Module ZPublisher.Publish, line 128, in publish
  Module ZPublisher.mapply, line 77, in mapply
  Module ZPublisher.Publish, line 48, in call_object
  Module zope.formlib.form, line 795, in __call__
  Module five.formlib.formbase, line 50, in update
  Module zope.formlib.form, line 758, in update
  Module plone.fieldsets.form, line 30, in setUpWidgets
  Module zope.formlib.form, line 402, in setUpEditWidgets
  Module zope.formlib.form, line 334, in _createWidget
TypeError: __init__() takes exactly 4 arguments (3 given)

How can I override the default widget?

A: What you need is:
from zope.formlib.widgets import OrderedMultiSelectWidget
from Products.LinguaPlone.browser.controlpanel import LanguageControlPanel

def MyMultiCheckBoxWidget(field, request):
    return OrderedMultiSelectWidget(field, field.value_type.vocabulary, request)

LanguageControlPanel.form_fields["available_languages"].custom_widget = MyMultiCheckBoxWidget


text:
Q: "than been married" vs "than being married" I am having problem with how to use been and being properly in essays. I came across following sentence and would like to learn through this example about the difference.

*

*It can be seen commonly in every part of the world that women tend to be alone than being married.

*It can be seen commonly in every part of the world that women tend to be alone than been married.

A: than been married is completely ungrammatical, but than being married is. Whenever been is used, the verb to have is involved one way or the other. To put it in simple terms, every time you want to use been, you must precede it with one of the forms of the verb to have. Here is the list of all possible combinations:

have been
  has been
  having been
  had been

That's why than been married is not correct. Does this make sense?


text:
Q: Creating a plist with multiple strings I have a multiple strings I would like to write to one plist using objective c. Can anyone please tell me exactly how to do this? I appreciate it

A: As H2CO3 hinted, you could use NSArray's writeToFile:atomically: method.
For example:
NSArray *arr = @[
    @"my first string",
    @"my second string",
    @"and the last one"
];
[arr writeToFile:@"./out.plist" atomically:NO]; // Or YES depending on your needs

A: Here's one possibility:
// Create the path that you want to write your plist to.
NSError *error = nil;
NSURL *documentsURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:YES error:&error];
if (documentsURL == nil) {
    NSLog(@"Error finding user documents in directory: %@", [error localizedDescription]);
    return nil;
}
NSString *path = [[documentsURL path] stringByAppendingPathComponent:@"YourFile.plist"];

// Populate your strings and save to the plist specified in the above path.
NSString *kRoot = @"kRoot";
NSMutableDictionary *tempDict = [NSMutableDictionary dictionary];
tempDict[kRoot] = [NSMutableArray array];
[tempDict[kRoot] addObject:@"String 1"];
[tempDict[kRoot] addObject:@"String 2"];
[tempDict[kRoot] addObject:@"String 3"];
// Etc, add all your strings
if (![tempDict writeToFile:path atomically:YES])
{
    NSLog(@"Error writing data to path %@", path);
}


text:
Q: Does Paypal has an OpenApi specs? need something like swagger.json or yaml Don't won't write api calls by myself. The best way - generate it by some tool. So i looking for some OpenAPI specs for PayPal Rest API
Already tried export this specs from theirs Postman collection, but it is not valid specs.

A: At the time of this writing there are no specs.
The Postman collection has samples which may be useful, but they are simply examples (not complete specs)


text:
Q: How to build Boost 1.44 using VS 2015 I am working on legacy projects upgrade from VS2010 to VS2015. for that boost1.44 should be recompiled using VS2015 and i tried to rebuild it. I got following errors:
1) libs\regex\build\has_icu_test.cpp(12) : fatal error C1083: Cannot open include file: 'unicode/uversion.h': No such file or directory
2)error C2280: 'boost::shared_ptr<boost::signals::detail::basic_connection>::shared_ptr(const boost::shared_ptr<boost::signals::detail::basic_connection> &)': attempting to reference a deleted function
3) error C2874: using-declaration causes a multiple declaration of 'boost::fusion::tuple'
4) warning:Unknown compiler version - please run the configure tests and report the results
How to resolve these issues without upgrading boost? or is it mandatory to upgrade boost to higher version to compile using VS2015?

A: boost 1.44 was released long before VS 2015 so this compiler is not supported. Besides many bugs were fixed in boost since that time. You should update boost to the latest version.
Also the error #1 seems to be caused by missing ICU library.


text:
Q: Hessian of a Matrix through Chain Rule Given
$f= \rho u^2$
$W_1 = \begin{pmatrix}
        \rho\\
        \rho u\\
        \end{pmatrix} $
,
$W_{1p} = \begin{pmatrix}
        \rho\\
        u\\
        \end{pmatrix} $
I want to find the Hessian of $f$ with respect to $W_1$. The actual Hessian is easily found by taking one derivative after another. However, I would like to use the product rule and chain rule to avoid the following.
$\dfrac{\partial W_1}{\partial W_{1p}} =    \begin{bmatrix}
        1 & 0 \\
        u & \rho \\
        \end{bmatrix} $
,
$\dfrac{\partial W_{1p}}{\partial W_{1}}
= \left(\dfrac{\partial W_1}{\partial W_{1p}}\right)^{-1}
=  \begin{bmatrix}
        1 & 0 \\
        -u/\rho & 1/\rho \\
        \end{bmatrix} $
$\dfrac{\partial f}{\partial W_{1}}
=\dfrac{\partial f}{\partial W_{1p}}\dfrac{\partial W_{1p}}{\partial W_{1}}
=\begin{bmatrix}
        u^2 & 2 \rho u \\
        \end{bmatrix}
\begin{bmatrix}
        1 & 0 \\
        -u/\rho & 1/\rho \\
        \end{bmatrix}
=
\begin{bmatrix}
        -u^2 & 2u \\
        \end{bmatrix} $
So far, so good, the first derivative is easily achieved. Now repeat.
$\dfrac{\partial^2 f}{\partial W_{1}^2}
=\dfrac{\partial}{\partial W_{1}}
\left(
\dfrac{\partial f}{\partial W_{1p}}\dfrac{\partial W_{1p}}{\partial W_{1}}
\right)
=\dfrac{\partial\left(
\begin{bmatrix}
        -u^2 & 2u \\
        \end{bmatrix}
\right)}{\partial W_{1}}
=\dfrac
{
\partial\left(
\begin{bmatrix}
        -u^2 & 2u \\
        \end{bmatrix}
\right)
}
{\partial W_{1p}}
\dfrac{\partial W_{1p}}{\partial W_{1}}$
$
\dfrac{\partial^2 f}{\partial W_{1}^2}=
\begin{bmatrix}
        0 & -2u \\
        0 & 2 \\
        \end{bmatrix}
\begin{bmatrix}
        1 & 0 \\
        -u/\rho & 1/\rho \\
        \end{bmatrix}
=
\begin{bmatrix}
        \dfrac{2u^2}{\rho} & -\dfrac{2u}{\rho} \\
        -\dfrac{2u}{\rho} & \dfrac{2}{\rho} \\
        \end{bmatrix}
$
Here is my real issue. My equations are in fact much more complicated and the first derivative $\left(
\dfrac{\partial f}{\partial W_{1p}}\dfrac{\partial W_{1p}}{\partial W_{1}}
\right)$ is insanely long. Each term by itself is relatively manageable so I would like to use the product rule in this way:
$\dfrac{\partial}{\partial W_{1p}}
\left(
\dfrac{\partial f}{\partial W_{1p}}\dfrac{\partial W_{1p}}{\partial W_{1}}
\right)
\dfrac{\partial W_{1p}}{\partial W_{1}}
=
\left(
\dfrac{\partial^2 f}{\partial W_{1p}^2}
\dfrac{\partial W_{1p}}{\partial W_{1}}
+
\dfrac{\partial f}{\partial W_{1p}}
\left(
\dfrac{\partial}{\partial W_{1p}}
\left(
\dfrac{\partial W_{1p}}{\partial W_{1}}
\right)
\right)
\right)
\dfrac{\partial W_{1p}}{\partial W_{1}}
$
Of course the above does not work (or I wouldn't be posting here).
Why am I not allowed to use the product rule?
If I am allowed, how could I do it properly?


text:
Q: Point location in tetrahedron meshes Are there any proven data structures for point location in tetrahedron meshes where the tetrahedra are all disjoint but are "touching" each other? I.e. most faces are faces of exactly two tetrahedra.
By locationI mean that I want to find out in which of the tetrahedrons a given point is located, or if it is not located in any.
So far, I have tried:

*

*A simple KD-Tree. This was way too slow for my needs, as the average tree depth was very high and I still had a lot of individual tetrahedrons to test in each leaf.

*A grid which contained all the intersecting tetrahedra for each cell. This seems to work a lot better, but was still not fast enough. First, the grid contained a lot of empty cells because my overall mesh is not very "boxy". Second, most cells that actually did contain tetrahedra, did contain a lot of them (10+). I suppose this is because a lot of tetrahedra share every vertex, and as soon as a vertex is in a cell, all its adjacent tetrahedra are too.
Some further information on the input data: The mesh is usually not convex and may have holes or inclusions. Though the last two are somewhat unlikely, i have to deal with them, which makes "walking" impossible without (expensive and complicated?) preprocessing.

A: If you are dealing with a 3D triangulation composed of tetrahedrons with adjacency information, you can just use walking. This is a standard technique for point location and uses 3D orientation tests.
For more information see the paper Walking in a triangulation by Olivier Devillers et al. (Google it and you will find a PDF of it.)

A: Some quick thoughts: an octree will be similar to your grid approach, but allow you to quickly ignore empty grids, and to subdivide grids which are too full.
Also, you don't mention how you're testing if a point lies inside of a tetrahedron. It's been a while since I've looked at it, but perhaps barycentric coordinates could speed up your point-in-tetrahedron tests? Or a sweep-line algorithm to quickly exclude tetrahedra based on tetrahedron vertices which are clearly on the wrong side of the sweep line to contain the point.

A: This is admittedly a little brainstormy.
Perhaps a custom of a kdTree that uses face-aligned planes instead of axis-aligned ones.
If a point is on the "correct" side of all four planes of a tetrahedron, then it must be inside the tetrahedron.  (Right?)  And if you're on the wrong side of any plane, then you can not only rule out the current tet, but also any others on that side of the plane.
It seems you should be able to build a tree where each node is a single plane, and a leaf node means you're in one specific tet (assuming the tets never intersect).  The tree may be deep, but since each test is only against a plane (rather than a more expensive triangle test) and since a leaf node gives you exactly one answer, it seems like it should be fast.
Building the tree efficiently may prove difficult.


text:
Q: Proving increasing and bounded Suppose {$a_n$} is a bounded sequence. For $b_n = \inf\{a_k: k \geq n\}$, prove that $\{b_n\}_{n=1}^{\infty}$ is increasing and bounded.
I was thinking of using the definition of lim inf where when  $b_n = \inf\{a_k: k \geq n\}$ then $\lim_{n \to \infty}\inf a_n = \lim_{n \to \infty}\inf b_n$ and since it has an infimum then it then by definition bounded.
For proving it increases, I was thinking about using induction.
Is this a good approach? If not how would I go about proving this.

A: For each $n\in\Bbb N$, write $$A_n=\{a_k:k\geq n\}.$$ Then, for each $n\in\Bbb N$, $$A_{n+1}\subset A_n.$$ Thus, for each $n\in\Bbb N$, we get (with the hint I posted in the comment)
$$b_n=\inf A_n\leq \inf A_{n+1}=b_{n+1}.$$
This proves that the sequence $\{b_n\}$ is increasing.
For boundedness of the sequence  $\{b_n\}$, let us observe the following:
Since $\{a_1,a_2,a_3,\dots\}$ is bounded, we can find two real numbers $m,M$ such that
$$m\leq a_i\leq M$$ for all $i\in\Bbb N$. This implies that for each $n\in\Bbb N$, we have $$m\leq b_n\leq M.$$

A: Hint: Suppose $A,B$ are bounded sets of real numbers. If $A \subset B$ then
$$\inf B \le \inf A.$$
Why? Suppose that this isn't true, i.e that
$$\inf B > \inf A.$$
Then, there exists $x \in A$ such that $x < b$ for all $b \in B$. But $A \subset B$ and so $x \in B$ (and $x$ is not strictly less than itself). This is a contradiction!


text:
Q: Converting world informations (PGW file - pixels) to geographical coordinates? I'm trying to load an image on a Leaflet map and to display it at the right place using the world information exported by QGIS.
For image overlays, Leaflet needs the coordinates of the upper left point and of the lower right point (boundaries):
var imageUrl = 'http://www.lib.utexas.edu/maps/historical/newark_nj_1922.jpg',
imageBounds = [[40.712216, -74.22655], [40.773941, -74.12544]]; L.imageOverlay(imageUrl, imageBounds).addTo(map);

In QGIS, when I export my image, I always use the 1:25000 scale and 72 DPI, which is a constant in my workflow.

It outputs a world file (PGW) that contains the information:
8.86711729729699094 //xscale
0 //yskew
0 //xskew
-8.86711729729699094 //yscale
491355.98836270271567628 //xpos
6600748.93414135184139013 //ypos

Knowing all that information, is there a way to convert the world file information into geographical coordinates I could use in Leaflet?

A: I found out !  No need to check DPIs or map scale, all required informations are contained in the world file.
Here, I'm parsing a PGW file sent through a form.
I'm also using the proj4php library to handle projections.
public function get_overlay_bounds_from_pgw($pgwfile,$imagewidth,$imageheight){

    $filename = isset($pgwfile['name']) ? $pgwfile['name'] : null;
    if ( !$filename ) return new WP_Error('tdp_empty_pgw_file','Missing PGW file');

    $arr_file_type = wp_check_filetype( basename( $filename ) );
    if ( !$arr_file_type || ($arr_file_type['ext'] != 'pgw') ) return new WP_Error('tdp_invalid_pgw_file','Invalid PGW file');

    $content = file_get_contents($pgwfile['tmp_name']);
    $lines = explode(PHP_EOL, $content);
    if ( count($lines) < 6 ) return new WP_Error('tdp_invalid_pgw_file','Invalid PGW file');

    //https://en.wikipedia.org/wiki/World_file
    $world = array(
        'xscale'=>  $lines[0],
        'yskew'=>   $lines[1],
        'xskew'=>   $lines[2],
        'yscale'=>  $lines[3],
        'xpos'=>    $lines[4],
        'ypos'=>    $lines[5],
    );

    // Initialise Proj4
    $proj4 = new Proj4php();
    // Create two different projections.
    $projQgis    = new Proj('EPSG:3857', $proj4);
    $projLeaflet  = new Proj('EPSG:4326', $proj4);

    //
    $topleft = new Point($world['xpos'],$world['ypos'], $projQgis);
    $topleft = $proj4->transform($projLeaflet, $topleft);

    $xmeters = $imagewidth * $world['xscale'];
    $ymeters = $imageheight * $world['yscale'];

    $bottomright = new Point($world['xpos'] + $xmeters,$world['ypos'] + $ymeters, $projQgis);
    $bottomright = $proj4->transform($projLeaflet, $bottomright);

    $bounds = array(
        'north'=>   $topleft->x,
        'west'=>    $topleft->y,
        'south'=>   $bottomright->x,
        'east'=>    $bottomright->y,
    );

    return $bounds;
}


text:
Q: dataTables (jquery) search by two columns I want to search table by only two columns. E.g. Initial search searches in all columns, I just want to search by two columns.
When I use following code:
dataTable.columns([1,7])
    .search("some string")
    .draw();

the search text must be present in both columns to be displayed. I want to display it even if it exists in one of the columns. Can anyone help?
Thanks

A: SOLVED
I've changed searching to initial which searches all columns:
dataTable
    .search(this.value)
    .draw();

And set columns which I don't want to be search in initTable:
    "columnDefs": [
    {
        "targets": [2,5],
        "searchable": false
    }]


text:
Q: Is it possible to use different colors on the same line / spline chart series? I'm trying to simulate a 'get range' function on a spline / line chart in high charts. but cant seem to find any examples out there.
So i thought i could fake it by using a different color for 'selected' range and non selected range.
Lets say i click a button, the chart recolors from 1st data to 5th data, while any data onwards i colored in a different colors.
i saw a few of zoom selections, but thats not quite what im trying to achieve. any help is appreciated.
i see that thresholds+negativecolor achieve something similar to what i want, but i want to be able to customize the range of which its a different color:http://api.highcharts.com/highcharts/plotOptions.series.negativeColor
example show in the image here:


text:
Q: Creating complementary graph from GIS data (e.g., shapefiles) I am new to GIS.
I have some data about shapes, e.g., voting-districts, in several formats such as WMS, JSON, SHP. I want to create a graph (e.g., graphML) such that each district corresponds to a node, and edges indicate that two districts share a border. The nodes should be located in the "mass-point" of a district and edges should be associated with the distance between the nodes. Something like the red graph below.

Nodes should further store some properties, e.g., longitude, latitude, custom-data.
What are efficient ways to achieve this?
Let me know the pros and cons of your suggestions.


text:
Q: Select onchange to Controller's Action in .net-core I have a list of objects classified by type, so I have a "type" select on my view
<form asp-action="Index" asp-route-type=" ? selectedTypeId ? ">
    <select asp-items="ViewBag.Types" onchange="this.form.submit()"></select>
</form>

my controller's action is
public async Task<IActionResult> Index([FromQuery(Name = "type")] int type) {
   // filter the object list by type
}

How do I correctly reload the view by using the select?
I saw Ajax solution are proposed and it would be a great solution, however my problem is that when I change the product type, not only the product list changes, but also the product characteristics (columns), also the create button should create only that type of products, so, it changes all the view behavior. I'll rather reload all the view than a part of it.

A:
How do I correcly reload the view by using the select?

It seems that you want to filter data based on the DropDownList selected value, in my opinion, I prefer to use Partial View to display the filtered data and use JQuery Ajax to update the content. Please refer the following sample:
Create a ProductViewModel view model:
public class ProductViewModel
{
    public int ProductId { get; set; }
    public string ProductName { get; set; }
    public string ProductType { get; set; }
}

Controller method:
    //ProductIndex Page
    public IActionResult ProductIndex()
    {
        //get all the initial data from the repository
        var productlist = _repo.GetProductViewModels();

        //set select items for the DropDownList
        ViewBag.Types = _repo.GetProductViewModels().Select(c=>c.ProductType).Distinct().ToList().Select(c => new SelectListItem { Text = c, Value = c }).ToList();
        return View(productlist);
    }

    //based on the type filter data and return partial view.
    public IActionResult ShowProduct(string type)
    {
        var productlist = _repo.GetProductViewModels().ToList();

        //based on the type to filter data.
        if (!string.IsNullOrEmpty(type) && type != "all")
        {
            productlist = productlist.Where(c => c.ProductType == type).ToList();
        }

        //required using Microsoft.AspNetCore.Mvc.Rendering;
        ViewBag.Types = _repo.GetProductViewModels().Select(c => new SelectListItem { Text = c.ProductType, Value = c.ProductType }).Distinct().ToList();
        return PartialView("_ShowProductPartialView", productlist );
    }

Create a _ShowProductPartialView.cshtml partial view to display the product list:
@model IEnumerable<netcore5.Models.ProductViewModel>

                @Html.DisplayNameFor(model => model.ProductId)

                @Html.DisplayNameFor(model => model.ProductName)

                @Html.DisplayNameFor(model => model.ProductType)

@foreach (var item in Model) {

                @Html.DisplayFor(modelItem => item.ProductId)

                @Html.DisplayFor(modelItem => item.ProductName)

                @Html.DisplayFor(modelItem => item.ProductType)

                @Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
                @Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
                @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })

}

Code in the ProductIndex Page:
@model IEnumerable<netcore5.Models.ProductViewModel>

@{
    ViewData["Title"] = "ProductIndex";
}

ProductIndex

<form asp-action="ProductIndex">
    <select id="ddltype" name="type" asp-items="ViewBag.Types" >
        <option value="all">All Type</option>
    </select>

        <partial name="_ShowProductPartialView.cshtml" model="@Model" />

</form>

@section Scripts{

}

Then, the result like this:

[Note] By using the above method, the main page will not update, just refresh the partial view.
If you want to use the <select> element onchange event, you could add a Submit button in the Form, and in the onchange event, click the Submit button, it will submit the form. Then, you can filter data based on the type.
Change the above code as below: In the ProductIndex.cshtml page, remove the JQuery script and add a Submit button, add name attribute for the select element, then, in the select onchange event, click the Submit button:
@model IEnumerable<netcore5.Models.ProductViewModel>

@{
    ViewData["Title"] = "ProductIndex";
}

ProductIndex

<form asp-action="ProductIndex">
    <select id="ddltype" name="type" asp-items="ViewBag.Types" onchange="document.getElementById('btnSubmit').click();" >
        <option value="all">All Type</option>
    </select>

        <partial name="_ShowProductPartialView.cshtml" model="@Model" />

    <input id="btnSubmit" hidden type="submit" value="submit" />
</form>

Code in the Controller:
    public IActionResult ProductIndex(string type)
    {
        //get all the initial data from the repository
        var productlist = _repo.GetProductViewModels();

        //based on the type to filter data.
        if (!string.IsNullOrEmpty(type) && type != "all")
        {
            productlist = productlist.Where(c => c.ProductType == type).ToList();
        }

        //set select items for the DropDownList
        ViewBag.Types = _repo.GetProductViewModels().Select(c=>c.ProductType).Distinct().ToList().Select(c => new SelectListItem { Text = c, Value = c }).ToList();
        return View(productlist);
    }

The result like this:

As we can see that, the Main page will refresh. So, I prefer to use JQuery Ajax to load the partial view.


text:
Q: What are the optimization networks? Where can I find info? So, i recently found this term related somehow to neural networks, but I don't find anymore info on this topic, and it seems interesting.
Does anybody know where I can find more info for starters on this?
thanks in advance

A: Even though I'm not sure what you mean by optimization networks, I'm suggesting you Stuart Russel and Peter Norvig's "Artificial Intelligence: A Modern Approach", which is sort of a standard book in AI.
I can't find the most recent version(2009) on Amazon though - they are only listing the rather old but not outdated 2nd edition.

A: Machine learning algorithms/techniques can be used to optimize solutions to given problems.
Is that what you are looking for?

I recommend you to buy the book Programming Collective Intelligence: Building Smart Web 2.0 Applications.

You won't regret it ;-)


text:
Q: Something like scanner for binary data Is there anything like scanner for binary data? I'd like for example to use delimiter like "\r\n" and get byte[] every time I invoke some method. Can u supply me with class which can do miracles like that?

A: Consider using DataInputStream and DataOutputStream:
File file = new File("binaryFile.dat");
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
DataOutputStream dos = new DataOutputStream(bos);

byte[] array1 = ...
byte[] array2 = ...
byte[] array3 = ...

dos.writeInt(array1.length);
for(byte b : array1) dos.wrtieByte(b);

dos.writeInt(array2.length);
for(byte b : array2) dos.wrtieByte(b);

dos.writeInt(array3.length);
for(byte b : array3) dos.wrtieByte(b);

and read it like:
File file = new File("binaryFile.dat");
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
DataInputStream dis = new DataInputStream(bis);

byte[] array1 = new byte[dis.readInt()];
for(int i = 0; i < array1.length; i++) array1[i] = dis.readByte();

byte[] array2 = new byte[dis.readInt()];
for(int i = 0; i < array2.length; i++) array2[i] = dis.readByte();

byte[] array3 = new byte[dis.readInt()];
for(int i = 0; i < array3.length; i++) array3[i] = dis.readByte();

A: Jakarta commons has a library you can use. Just download the .jar from jakarta and download their .jar and add that to your build path via add external jars. IOUtils.toByteArray(InputStream input)

A: You can use the java.io.InputStream class:
InputStream is = new FileInputStream("your_file");
byte[] b = new byte[is.available()];  //reads how much bytes are readable from file
is.read(b);//reads the file and save all read bytes into b

Hope this helps


text:
Q: How to exit from outer loop if inner loop is getting failed using Batch script How can I terminate the whole main program if inner loop has any issue using batch command? Below is my code.
Here I need to exit from main outer loop if value found in inner loop is X, but currently my code is getting exit from inner loop only.
For %%A in (alpha beta gamma) DO (
   Echo Outer loop %%A
   Call :inner
)
Goto :eof

:inner
For %%B in (U V W X Y Z) DO (
   if %%B==X ( exit /b 2 )
   Echo    Inner loop    Outer=%%A Inner=%%B

)
exit /b 1

Output : it should be like below only.
Outer loop alpha
   Inner loop    Outer=alpha Inner=U
   Inner loop    Outer=alpha Inner=V
   Inner loop    Outer=alpha Inner=W

A: You already set an exit code (errorlevel). Just react on it:
setlocal enabledelayedexpansion
For %%A in (alpha beta gamma) DO (
   Echo Outer loop %%A
   Call :inner
   if !errorlevel! equ 2 (echo inner loop failed & exit /b 2)
)
Goto :eof

:inner
For %%B in (U V W X Y Z) DO (
   if %%B==X ( exit /b 2 )
   Echo    Inner loop    Outer=%%A Inner=%%B

)
exit /b 1

Aschipfl suggested "Just insert if ErrorLevel 2 goto :EOF after the call command line"
That might be a good idea (and avoids delayed expansion), but be aware that if errorlevel 2 actually means "if errorlevel is 2 or higher". If your inner loop only ever returns 0 or 2, that's definitively the better solution. When it may return more possible errorlevels, you have to use extreme care handling them with if errorlevel. (That's the reason, I chose if !errorlevel! instead)


text:
Q: How to inject Parent class in other classes so that It picks the child class based on passed model? I have the following classes in Java
class A which is inherited by class A1 and A2

A has method run and both A1, A2 are overriding this method

Another model class B

B has JSON subtypes B1 and B2 (child classes)

What I want to achieve now is if I run
InstanceOfA.run(B) where B is a reference to B1 subtype, it should execute A1's run method

and If I run InstanceOfA.run(B) where B is a reference to B2 subtype, It should execute A2's run method.

InstanceOfA is an instance of A.
If this is possible, I can inject A using @Inject annotation in all other classes (where it is required) and don't need to pass actual implementations.
Any other solution to do is also welcome.


text:
Q: Haproxy 1.5.3 / OpenSSL - Creating PEM I have an HAProxy Server set up with the line:
bind *:443 ssl crt /etc/ssl/domain.com/domain.com.pem
I have the following files:
/etc/ssl/domain.com/domain.com.key
/etc/ssl/domain.com/domain.com.csr
I have purchased a certificate from Geotrust which gives me a Primary Intermediate Certificate, Secondary Intermediate Certificate and End Entity Certificate
I have concatenated the files, in PIC, SID, EEC, KEY order in to /etc/ssl/domain.com/domain.com.pem which passes openssl verify /etc/ssl/domain.com/domain.com.pem and openssl verify -CAfile /etc/ssl/domain.com/domain.com.pem /etc/ssl/domain.com/domain.com.pem
I have also verified this file using http://www.sslshopper.com/certificate-decoder.html
When I run haproxy -f /etc/haproxy/haproxy.cfg -c I get
'bind *:443 : inconsistencies between private key and certificate loaded from PEM file '/etc/ssl/domain.com/domain.com.pem'
Proxy 'http-in': no SSL certificate specified for bind '*:443' at [/etc/haproxy/haproxy.cfg] (use 'crt')
I am new to SSL Certificates and I'm stuck where to go. Googling for answers has had me run a merry mile and I'm no further forward.
Have I done something wrong in creating the .pem file this way and how can I resolve this?

A: Resolved.
I needed to create the PEM in order KEY, EEC, SID, PID instead of PID, SID, EEC, KEY


text:
Q: How to Create dynamic table with json object using jquery I have json like below.I have to generate dynamic th with json key. and generate tr and td with its value.How to achive this.
let jsonObj= {
       "No of cells":[
          "65",
          "65",
       ],
       "Current density":{
          "Unit":"A/cm2",
          "Values":[
             "0.2",
             "0.4",
          ]
       }

    }

I need table like

No of cells
Current density

65
0.2

65
0.4

I Have tried like this:
var idx =0;
for(let key in jsonObj){
console.log(key)
// for(let key in jsonObj){
    var row = "
";
  row += "" + jsonObj[key] + "	";
  row += "" + jsonObj[key][idx] + "	";
  row += "" + jsonObj[key][idx] + "	";
  row += "
";
idx++;
$("#data").append(row);

// }

}

But this not working.Please Help me

A: Assuming that the two Keys in the JSON Object has same number of values. You can use the following solution to fulfill your task.

let jsonObj = {
  "No of cells": [
    "65",
    "65",
  ],
  "Current density": {
    "Unit": "A/cm2",
    "Values": [
      "0.2",
      "0.4",
    ]
  }

}
var row = "";
for (let key in jsonObj){
  row += `<th>${key}</th>`;
}

$("#data").append(row);

row = "";

for (let idx in jsonObj["No of cells"]) {
  var row = "
";
  row += "" + jsonObj["No of cells"][idx] + "	";
  row += "" + jsonObj["Current density"]["Values"][idx] + "	";
  row += "
";

  $("#data").append(row);
}


text:
Q: Is using Object class to represent all kind of Json payload a good idea I am currently working in a code base where for every REST API response they use a java class like below
{
Object payload;
List<Error> errors;
String responseStatus;
}

The problem is, when we refer to the swagger documentation of the REST APIs it shows a json structure like below.
{
   "payload":{},
   "errors": [
   {
    "errMsg":"",
    "errCode": ""
   }
  ],
  "responseStatus":""

}

So the response will have payload if response is success, error list in case of errors and response status set to success or failure respectively.

*

*Is it a good practice to use same json structure for error and success?

*Is there any way to improve swagger documentation, so that I can show what the response payload json will look like for a particular API response.

EDIT: I just want to mention that I cannot change the response payload to any thing else, as it is being used in more than 1000 APIs and is distributed into different services.
Is there any way to improve at least the swagger documentation, without changing the Response Object in java, because that ship has sailed a long time ago.

A: *

*It is not a good practice to use the same json structure for error and success responses.

*Yes, if you have control over the Swagger definitions, you can specify different responses per response code.

Here is an example from the Swagger documentation
paths:
  /users/{id}:
    get:
      summary: Gets a user by ID.
      response:
        '200':
          description: OK
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          $ref: '#/components/responses/NotFound'

# Descriptions of common components
components:
  responses:
    NotFound:
      description: The specified resource was not found
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
    Unauthorized:
      description: Unauthorized
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'

  schemas:
    # Schema for error response body
    Error:
      type: object
      properties:
        code:
          type: string
        message:
          type: string
      required:
        - code
        - message

    # Schema for the User response
    User:
      type: object
        properties:
          # Add properties for the User object
          # ...

A: you can use ResponseEntity<? extends Response> return type in your methods. so that if response is success, both of them returned, as well as response is error.
public ResponseEntity<? extends ResponseDto> foo(RequestDto request){
if(success){
return new ResponseEntity<>(new SuccessResponse(Enum.SuccessResponse.getMessage,200,dto),HttpStatus.OK);
}
return new ResponseEntity<>(new ErrorResponse(Enum.ErrorResponse.getMessage,400),HttpStatus.BAD_REQUEST);
}


text:
Q: Find multi-line text & replace it, using regex, in shell script I am trying to find a pattern of two consecutive lines, where the first line is a fixed string and the second has a part substring I like to replace.
This is to be done in sh or bash on macOS.
If I had a regex tool at hand that would operate on the entire text, this would be easy for me. However, all I find is bash's simple text replacement - which doesn't work with regex, and sed, which is line oriented.
I suspect that I can use sed in a way where it first finds a matching first line, and only then looks to replace the following line if its pattern also matches, but I cannot figure this out.
Or are there other tools present on macOS that would let me do a regex-based search-and-replace over an entire file or a string? Maybe with Python (v2.7 and v3 is installed)?
Here's a sample text and how I like it modified:
  keyA
  value:474
  keyB
  value:474    <-- only this shall be replaced (follows "keyB")
  keyC
  value:474
  keyB
  value:474

Now, I want to find all occurances where the first line is "keyB" and the following one is "value:474", and then replace that second line with another value, e.g. "value:888".
As a regex that ignores line separators, I'd write this:

*

*Search: (\bkeyB\n\s*value):474

*Replace: $1:888
So, basically, I find the pattern before the 474, and then replace it with the same pattern plus the new number 888, thereby preserving the original indentation (which is variable).

A: You can use
sed -e '/keyB$/{n' -e 's/\(.*\):[0-9]*/\1:888/' -e '}' file
# Or, to replace the contents of the file inline in FreeBSD sed:
sed -i '' -e '/keyB$/{n' -e 's/\(.*\):[0-9]*/\1:888/' -e '}' file

Details:

*

*/keyB$/ - finds all lines that end with keyB

*n - empties the current pattern space and reads the next line into it

*s/\(.*\):[0-9]*/\1:888/ - find any text up to the last : + zero or  more digits capturing that text into Group 1, and replaces with the contents of the group and :888.

The {...} create a block that is executed only once the /keyB$/ condition is met.
See an online sed demo.

A: Use a perl one-liner with -0777 to scan over multiple lines:
$ # inline edit:
$ perl -0777 -i -pe 's/\bkeyB\s*value):\d*/$1:888/' file.txt
$ # to stdout:
$ cat file.txt | perl -0777 -pe 's/\bkeyB\s*value):\d*/$1:888/'

A: In plain bash:
#!/bin/bash

keypattern='^[[:blank:]]*keyB$'
valpattern='(.*):'
replacement=888

while read -r; do
    printf '%s\n' "$REPLY"
    if [[ $REPLY =~ $keypattern ]]; then
        read -r
        if [[ $REPLY =~ $valpattern ]]; then
            printf '%s%s\n' "${BASH_REMATCH[0]}" "$replacement"
        else
            printf '%s\n' "$REPLY"
        fi
    fi
done < file


text:
Q: biblatex not working in WinEdt I'm trying to cite with biblatex on WinEdt. Unfortunately, it doesn't work. Here's the code:
\documentclass{article}
\usepackage[backend=biber, bibencoding=latin1]{biblatex}
\addbibresource{C:/citations/library.bib}
\begin{document}
fsdfsd \textcite{Organski1958}

\printbibliography
\end{document}

Output:

fsdfsd Organski1958

There is no reference list and the citation has no separation between author name and year.
I'm not sure why this is and would appreciate your help very much!


text:
Q: Spacy - python - for loop to process several sentences Python / spacy question
I am trying to figure out how to allow to use a for loop to get spacy to:

*

*Go through a data frame of sentences (called "sentences"),row by row. (Each row contains a sentence as a string)

*For each sentence, analyze what the part of speech is of each token in the sentence

*Store each part of speech in a column in a data frame (i.e text1 is the part of speech of the first token, text2 is the second one, etc)

Is there an easier way to get everything into a data frame (or straight to an excel file)?
I need to analyze 100 sentences, so I don't want to analyze each sentence with a new line of code. I thought a for loop could make this automate this.
This is my code:
import pandas as pd

df = pd.DataFrame(columns = ["text1", "text2", "text3", "text4", "text5", "text6", "text7", "text8", "text9",
                            "text10", "text11", "text12", "text13", "text14", "text15", "text16",
                            "text17", "text18", "text19", "text20"])

max = len(sentences)
j = 0
for i in range(1, max):
    doc = nlp(sentence_list[i])
    for token in doc:
        pos = token.pos_
        df[i,j]= pos
        j = j + 1

I get this error message:
PerformanceWarning: DataFrame is highly fragmented.  This is usually the result of calling `frame.insert` many times, which has poor performance.  Consider joining all columns at once using pd.concat(axis=1) instead. To get a de-fragmented frame, use `newframe = frame.copy()`

A: Keep in mind that each text will vary in word count, and so the number of "sub-columns" will be dynamic. I suggest using the following code as starting point, and then improve column POS_Analysis appearance, via Pandas opperations.
import spacy
import pandas as pd

# Building my own `df1`, it should look similar to yours
texts = ["text1", "text2", "more texts", "text 100"]
df1 = pd.DataFrame(texts, columns =['texts'])

# Loading spaCy model
model_to_use = "en_core_web_lg"  # Or use the path to your own model
nlp = spacy.load(model_to_use)

# 'STARTING POINT' CODE
pos_list = []
for doc in nlp.pipe(df1['texts']):
    token_pos = []
    for token in doc:
        token_pos.append(
            {
                "Token text": token.text,
                "Universal POS tag set": token.pos_,
                "Fine-grained POS": token.tag_,
                # # Include the rest if you want them...
                # "Lemma": token.lemma_,
                # "Syntactic dependency relation": token.dep_,
                # "Orthographic features": token.shape_,
                # "consist of alphabetic characters": token.is_alpha,
                # "belongs to stop list": token.is_stop
            }
        )
    pos_list.append(token_pos)

df1['POS_Analysis'] = pos_list

print(df1.head())

An example output looks like:
text                                       POS_Analysis
0  Net income was $9.4 million compared to the pr...  [{'Token text': 'Net', 'Universal POS tag set'...
1  Revenue exceeded twelve billion dollars, with ...  [{'Token text': 'Revenue', 'Universal POS tag ...
2                      I don't have any entity in me  [{'Token text': 'I', 'Universal POS tag set': ...

I think I can update this answer, but as requested on the comments to your original post, you will need to clarify your request a bit more.


text:
Q: uwsgi Import Error: No module named 'encodings' I'm trying to setup flask with uwsgi.  This is my directory structure:
/srv/http/www/myapp
|
+-- env -> virtualenv
|
+-- mpd -> the project directory
  |
  +-- main.py -> main application

And I'm using this command:
uwsgi -s 127.0.0.1:3002 --chdir webmpd --uid 33 --gid 33 --plugin python -H env --module main --callable app
And I get this error:
*** Starting uWSGI 1.9.19 (32bit) on [Sat Nov 30 22:37:33 2013] ***
compiled with version: 4.7.2 on 13 November 2013 15:40:36
os: Linux-3.10.19-3-ARCH #1 PREEMPT Thu Nov 21 20:33:10 CST 2013
nodename: raspy
machine: armv6l
clock source: unix
pcre jit disabled
detected number of CPU cores: 1
current working directory: /srv/http/www/mpd
detected binary path: /usr/bin/uwsgi
uWSGI running as root, you can use --uid/--gid/--chroot options
setgid() to 33
setuid() to 33
*** WARNING: you are running uWSGI without its master process manager ***
your processes number limit is 1321
your memory page size is 4096 bytes
detected max file descriptor number: 1024
lock engine: pthread robust mutexes
thunder lock: disabled (you can enable it with --thunder-lock)
uwsgi socket 0 bound to TCP address 127.0.0.1:3002 fd 3
Python version: 3.3.3 (default, Nov 29 2013, 11:19:14)  [GCC 4.7.2]
Set PythonHome to env
Fatal Python error: Py_Initialize: Unable to get the locale encoding
ImportError: No module named 'encodings'
Aborted

I have looked around a lot and this problem seems to be stemming from mismatched python version between uwsgi and the system, but in my case, both are running python 3.3.  I don't know what else could be wrong.
Any help is appreciated.

A: I don't know if you solved your problem since (I hope for you), but the problem comes from that your python environment is not correctly found.
So you should use an absolute path for your python environment that you setted at "env"
The short way :
use this command line
uwsgi -s 127.0.0.1:3002 --chdir webmpd --uid 33 --gid 33 --plugin python -H /srv/http/www/myapp/env --module main --callable app

Please be sure, that the user running uwsgi is authorized to access to this path.
I hope it helps !


text:
Q: HttpContext.Current.Session Always Null I know this topic has come up a lot, but I haven't found one that works for my problem..
I have a GuestTokenValidationAttribute Class that derives from ActionFilterAttribute, in there I receive a token from the header and I use it as a String token. Then I want to add that token to a session, but no matter what I do the Session is always null.
Please guys any guidance or help will be much appreciated,
Code Example below:
public class GuestTokenValidationAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
         string token;
        try
        {
           token =  actionContext.Request.Headers.GetValues("Authorization-Token").First();
        }
        catch (Exception)
        {
            actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized)
            {
                Content = new StringContent("Unauthorized User")
            };
            return;
        }

        if(string.IsNullOrEmpty(token))
        {
          actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized)
            {
                Content = new StringContent("Unauthorized User")
            };
            return;
        }

        try
        {
            var repository = DependencyResolver.Current.GetService<IRepository<Guest>>();
            var guest = repository.GetAll().FirstOrDefault(x => x.Token == token);
            if(guest == null)
            {
                actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized)
                {
                    Content = new StringContent("Unauthorized User")
                };
                return;
            }

        }
        catch (Exception)
        {
            actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized)
            {
                Content = new StringContent("Unauthorized User")
            };
            return;
        }

       HttpContext.Current.Session.Add("guesttoken" ,token);

        base.OnActionExecuting(actionContext);

    }

A: MVC ported to asp.net to solve problems such as Session and ViewState which were a true opposition against the nature of the web. As you know, in MVC, all actions and responses should be considered as stateless requests which nothing should be left before and after processing the request and assumed GC will collect all data in ViewBags, Session, Variables, etc.
So, as highly recommended, the common way of handling such thing is using native facilities delivered through pure web such as cookies, html-forms, html-inputs, url parameters, etc.


text:
Q: Duplicate class in two offcial android libs, gradle fails I'm using a library that requires activate render script support mode. Like this
defaultConfig {

 minSdkVersion 14
 targetSdkVersion 23
 renderscriptTargetApi 20
 renderscriptSupportModeEnabled true
}

But when I try to run the app, I have this:
Error:Execution failed for task ':app:packageAllDebugClassesForMultiDex'.
java.util.zip.ZipException: duplicate entry: android/support/annotation
/Keep.class

Keep.class is in annotation-support lib and in rendserscript lib too, both from Google, so I don't know what to do exactly.

A: This error occurred in latest(23) SDK version only. Can you try to change the build version to 22 or 21, change the dependencies also.
For example
android {
       compileSdkVersion 21
        buildToolsVersion "21.1.2"
}
dependencies {

    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:21.0.3'
    compile 'com.android.support:support-v4:21.0.3'
}

A: I made the following modifications to my build.gradle file, and it is now working:
renderScriptTargetApi 23
and added
configurations { all*.exclude group: 'com.android.support', module: 'support-annotations' }
I believe it's the second line that did the trick.


text:
Q: JavaScript linking arrays I want to connect two different arrays into one. For example  we have two arrays
var x = [1,2,3,4,5,6,7,8,9];
y = [5,4,8,5,5,5,5,5,5];

I'm interested into get array
var xyAr = [[1, 5], [2, 4], [3, 8]...];

A: This function is called zip in other languages and can be done in js like this:
function zip(a, b) {
    return a.map(function(x, i) {
        return [x, b[i]];
    });
}

http://jsfiddle.net/kQuuz/
Here's a version that accepts a variable number of parameters:
function zip() {
    var args = [].slice.call(arguments, 0);
    return args[0].map(function(_, i) {
        return args.map(function(a) { return a[i] })
    });
}

Use it like this:
zip(array1, array2, array3)


text:
Q: Rouche's theorem Application right half plane Show that there are two roots of $(z^4+2)e^z+z+1=0$ which lies in the right half plane (that is, Rez > 0).
I have been stuck in this problem for a week, and I  only know that $|e^z|$>1
Can somebody give me some hints? Thanks a lot!

A: Along the imaginary axis, $|(z^4 + 2)e^z| > |z+1|$ (note that $z^4$ is real and positive in this case), while on a large enough semicircle centered at the origin going into the right half-plane, we clearly have $|(z^4 + 2)e^z| > |z+1|$. Using that semicircle together with its diameter, Rouche's theorem implies that $(z^4 + 2)e^z + z + 1$ has as many zeroes within this semicircle as does $(z^4 + 2)e^z$, which clearly has two. Since we can choose the semicircle to be as large as we want, there can be only two zeroes in the right half-plane.


text:
Q: Can AWS RA3 clusters read from DC2? Excuse me if my question doesn't even make sense at all.  I'm new to AWS.
There is a Redshift cluster that I have read permissions for but it is owned by another team.  It might be a dc2 node.
If I create a RA3 cluster, will it be able to read that Redshift cluster?
Or does it have to be the exact same type of node?
Thanks


text:
Q: When ASPNETCORE_ENVIRONMENT changed to anything but "Development" - Blazor app doesn't see resources from razor class libraries when debugged in VS Maybe just try the example:
https://github.com/HTD/BlazorProfiles
This is a demo Blazor application (default).
I created 2 custom application profiles: Development and Production.
Both should be debuggable just with pressing F5 key in Visual Studio.
Then I created a dummy Razor Component Library and named it RCL.
I made it a dependency for the main project.
Inside my dummy RCL, within wwwroot directory I added extra.css file.
The role of that file is to change the background color to light green.
If it happens - it means the file has been loaded. If the background remains gray / white, it is not loaded.
Here's the _Host.cshtml fragment loading the CSS:
<link href="_content/RCL/extra.css" rel="stylesheet" />

Try to run it. It works. However on one condition:
ASPNETCORE_ENVIRONMENT environment variable MUST be set to "Development".
If you test the Production profile (or change the environment variable to "Production") and then run the application - the extra.css file will not be loaded.

The background doesn't change to green, so something is wrong.
Why does it happen? Is it a bug in Visual Studio?
If you wonder why do I need to set this environment variable: it allows loading of additional
appsettings.[ASPNETCORE_ENVIRONMENT].json
file. So I can have different configurations for my app. I need to test my app with different configurations. Now I can only debug it in Visual Studio with "Development" configuration. When I change configuration to anything else I can't run my app because it can't load necessary JavaScript files required by components from the library.
So, expected behavior: no matter what I put into "ASPNETCORE_ENVIRONMENT" - the files from RCL should always load. Why shouldn't they?
Actual behavior: using different configurations (profiles) breaks Razor Component Library loading.

A: Found it in the ASP.NET core github issues. It's actually mentioned in the docs.
You need to enable static web assets in the webhost:
    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder => {
                webBuilder.UseStaticWebAssets(); // <----
                webBuilder.UseStartup<Startup>();
            });

edit: note the comment in the Docs

Calling UseStaticWebAssets isn't required when running an app from published output (dotnet publish).

A: This had me baffled for a few hours today til I came across the accepted answer, which led me to the docs. For a NET 6.0 app things have changed slightly:

...static web assets are enabled by default in the Development
environment. To support assets in other environments when running from
build output, call UseStaticWebAssets on the host builder in
Program.cs:

builder.WebHost.UseWebRoot("wwwroot");
builder.WebHost.UseStaticWebAssets();

You then also need to call
app.UseStaticFiles();

further down after the app has been built from var app = builder.Build();


text:
Q: " scriptProcessor could not be found in  application configuration" when accessing PHP script in subfolder
Possible Duplicate:
"<handler> scriptProcessor could not be found in <fastCGI> application configuration" when accessing PHP script in subfolder

I have a configuration problem with php on IIS 7.5.
It is a practically fresh install made with the MS Web PI on Win7.
I created a simple php testpage. It works in the root level http://localhost/test.php and in the first sub-level http://localhost/site/test.php, but not in http://localhost/site/subfolder/test.php, there I get HTTP 500 error:
<handler> scriptProcessor could not be found in <fastCGI> application configuration
Everything seems to be configured as specified in http://www.iis.net/ConfigReference/system.webServer/fastCgi/application
Could there be some kind of filter that disables processing at specific folder-level / or enable it just in the first 2 levels?
What should I check?

A: Turns out I copied the files that I had on the previous setup. And the subfolder that was not working had web.config where a different php-cgi.exe was specified.
Basically I now have 64-bit system and the php executable is in C:\Program Files (x86)\PHP\v5.3\php-cgi.exe, I discovered it in the IIS Manager by going to the non-working folder and opening Handler Mappings and checking the value for PHP_via_FastCGI, that's when I noticed the old executable in C:\Program Files\PHP...
Thanks for your attention :) hope this helps someone.


text:
Q: Does the user_register change in multisite? I've created a function that automatically creates a new post for people when they register. It works great on a standard site but in multisite it stops working. I've spent hours trying to debug it. Is there a better hook to use than user_register in multisite?

A: There is the action hook wpmu_new_user.
/*
 * Create a user.
 *
 * This function runs when a user self-registers as well as when
 * a Super Admin creates a new user. Hook to 'wpmu_new_user' for events
 * that should affect all new users, but only on Multisite (otherwise
 * use 'user_register').


text:
Q: How to define an ECR Lifecycle Policy with CloudFormation In order to limit the number of images in a repository, I'd like to define a Lifecycle policy. Since all the stack is defined with CloudFormation, I'd like to define this policy too.
For example, my policy could be "keep only the most recent 8 images, no matter if tagged or not".

A: The solution was pretty easy, but since I could not find any example or similar questions (ECR is not mainstream, I know), let me post here the easy solution that I found, which simply requires to insert the policy as JSON into the CloudFormation definition:
MyRepository:
  Type: AWS::ECR::Repository
  Properties:
    LifecyclePolicy:
      LifecyclePolicyText: |
        {
          "rules": [
          {
            "rulePriority": 1,
            "description": "Only keep 8 images",
            "selection": {
              "tagStatus": "any",
              "countType": "imageCountMoreThan",
              "countNumber": 8
            },
            "action": { "type": "expire" }
          }]
        }

Of course this is very simplistic, but it's the starting point that I was looking for

A: You can also define a reference to your PolicyText and later on your parameters.json stringify your policy.
It would look like something like this:
template.yml
Parameters:
  lifecyclePolicyText:
    Description: Lifecycle policy content (JSON), the policy content the pre-fixes for the microservices and the kind of policy (CountMoreThan).
    Type: String
  repositoryName:
    Description: ECR Repository Name to which we will apply the lifecycle policies.
    Type: String
  registryId:
    Description: AWS account identification number (12 digits)
    Type: String
    Default: xxxxx
Resources:
  Repository:
    Type: AWS::ECR::Repository
    Properties:
      LifecyclePolicy:
        LifecyclePolicyText: !Ref lifecyclePolicyText
        RegistryId: !Ref registryId
      RepositoryName: !Ref repositoryName
Outputs:
  Arn:
    Value: !GetAtt Repository.Arn

parameters.json
[
    {
      "ParameterKey": "lifecyclePolicyText",
      "ParameterValue": "{'rules':[{'rulePriority':1,'description':'Only keep 8 images','selection':{'tagStatus':'any','countType':'imageCountMoreThan','countNumber':8},'action':{'type':'expire'}}]}"
    },
    {
      "ParameterKey": "repositoryName",
      "ParameterValue": "xxxx"
    }
  ]

A: | will allow you to add text inline.
AWSTemplateFormatVersion: "2010-09-09"
Resources:
    ECRRepo:
      Type: AWS::ECR::Repository
      Properties:
        RepositoryName: "images"
        LifecyclePolicy:
          LifecyclePolicyText: |
            {
                "rules": [
                    {
                        "rulePriority": 2,
                        "description": "Keep only one untagged image, expire all others",
                        "selection": {
                            "tagStatus": "untagged",
                            "countType": "imageCountMoreThan",
                            "countNumber": 1
                        },
                        "action": {
                            "type": "expire"
                        }
                    }
                ]
            }


text:
Q: Changing IP address of Apache server using PHP statically I want to statically assign the IP address of my Arch linux using php. I want to change the IP by using netmask,interface,broadcast,address & gateway. The user puts up the values into a html page. The html page posts the data to the PHP page. I want to change the ip using this data. ho to do this?? please help me on this.
Can Files be used?
I was thinking of writing directly into the rc.conf using files!!...will this work and how??.. I have my arch linux up with apache & php..any of the help is appreciate.

A: If you want to change IP permanently you need to modify values in rc.conf. After that modification you need to restart network service. You can do that in two ways:
/etc/rc.d/network restart

or
rc.d restart network

To modify rc.conf and restart service you need root privileges. As running apache as root isn't good idea I would recommend creating some wrapper that is started using sudo for restarting services and modifying rc.conf.
PHP script -> start shell script sudo ./modify-network IP NETMASK GW
Sudo entry for this should be in format:
www ALL=(root) NOPASSWD: /path/to/modify-network

Remember to filter your input in PHP script. Check if IP number is real IP not rc.conf-injection ;) like 192.168.0.100"\nDAEMONS=(!apache).
And remember to redirect user to new address after you change it (when user press "Change IP" button, post data, do some javascript sleep 1 and window.location.href = 'http://NEW_IP/';
You could also use SELinux to add more security to this solution...


text:
Q: How to import data from a different workbook, with a button. getSheetById(id) doesn't work I want to import data from 3 sheets in a different workbook, in the same drive, to a newer workbook, with the press of a button.
Each workbooks has a sheet called 'Log Wizard' with 2 boxes. The bottom box displays the current spreadsheet key. The top box is an input field to paste an existing sheet key into.
https://docs.google.com/spreadsheets/d/1833-5CnOurssETuZFtohiHRRBx1V3_95_L0S-f9vPLk/edit#gid=187106606
enter image description here
enter image description here
So far, I cannot figure out how to make a script that does the following:

*

*When the button is pressed, get the source sheet id which is provided by the user in cell M11 of the current sheet, and use that to access the referenced spreadsheet

*And then copy 3 different ranges from three different sheets (2 of which are hidden) to empty sheets of the same names in the newer workbook (vehicle configuration, budget log and log).
I know that getSheetById has issues with permissions of some sort. I am not very familiar with google scripting so any help is appreciated.
//variables
var id = "123456789abcdefg";
var sheet = "LOG WIZARD";
var cells = "M11:AB13";
var range = SpreadsheetApp.openById(id).getSheetByName(sheet).getRange(cells);
var id = range.getSheet().getParent().getId();

//custom function to import logs
function importlogs() {

//Source sheet from which to import from
var is = SpreadsheetApp.openById(id)
var sheet1i = is.getSheetByName("BUDGET LOG");
var sheet2i = is.getSheetByName("LOG");

//Current sheet from which to export to
var xs = SpreadsheetApp.getActiveSpreadsheet();
var sheet1x = xs.getSheetByName("BUDGET LOG");
var sheet2x = xs.getSheetByName("LOG");

//Copy and paste contents of import Budget Log sheet to export Budget Log sheet
sheet1i.getRange("A3:AO").copyTo(sheet1x.getRange(sheet1x.getLastRow()+1,1,1,7), {contentsOnly:true});

//Copy and paste contents of import Log sheet to export Log sheet
sheet2i.getRange("A3:O").copyTo(sheet2x.getRange(sheet2x.getLastRow()+1,1,1,7), {contentsOnly:true});

}

I am unsure if it is actually passing the key correctly or at all. I tend to get the error Exception: Unexpected error while getting the method or property openById on object SpreadsheetApp. or Exception: You do not have permission to call SpreadsheetApp.openById. Required permissions: https://www.googleapis.com/auth/spreadsheets (line 5).
I assume this is because of some type of permission that doesn't allow a custom function to call another spreadsheet?
I have tried various suggestions here:
You do not have permission to call openById
and here:
How to use an installable trigger to get SpreadsheetApp.openById(id) to work, by calling it from a cell
but so far nothing I have found works.

A: The //variables section is in the global scope of the script project, so those definitions get evaluated every time any function runs, just before the function executes.
The problem is that those definitions are not compatible with the custom functions you are using. A custom function runs in a limited context where methods that require authorization are not available. When SpreadsheetApp.openById(id) gets called in that context, the custom function errors out, even though the problematic line of code is not within the function itself.
The importlogs() function is run through a button. It will run in an authorized context where SpreadsheetApp.openById(id) is available normally.
To solve the problem, delete the //variables section. The same declarations are repeated within importlogs(), so that should be enough. If you want to improve the importlogs() function, use the code given to you in your previous question.
You may want to add this code to easily call the importLogs_() function through a button:
/**
* Call this function through a button.
* https://developers.google.com/apps-script/guides/menus#clickable_images_and_drawings_in_google_sheets
*/
function runImportLogs() {
  const sourceSsId = SpreadsheetApp.getActive()
    .getRange('LOG WIZARD!M11')
    .getDisplayValue();
  importLogs_(sourceSsId);
}


text:
Q: Troubled with how and where to implement if/else statements I am almost finished creating a hangman game in Java, although I am having difficulty with one last part. I want to make it so the program checks if all the letters of the word have been guessed correctly and if so, the game prints a message saying they have won, the game ends and the program goes to the do while loop in the main class asking if they would like to play again. If not however, the game continues until this point or if all 5 guesses have been used - to which again, it is sent to the do while loop in order to restart the game and not simply terminate the program.
The problem is I am unsure how and where exactly to structure the if and else statements in order to do so.
Any help would be greatly appreciated, if I can provide further information to help narrow anything down please ask too, thank you in advance.
Instantiable Class
public class Hangman {

    private char letterGuess;
    private int numberLives;
    private String outputWord, endMessage;
    private final String hiddenWord;
    private final StringBuffer swapBuffer = new StringBuffer();

    public Hangman() {
        letterGuess = ' ';
        numberLives = 5;
        hiddenWord = "java";
        outputWord = "";
        endMessage = "";
        for (int i = 0; i < hiddenWord.length(); i++) {
            swapBuffer.append("*");
        }
    }

    public void setLetterGuess(char letterGuess) {
        this.letterGuess = letterGuess;
    }

    public void compute() {
        boolean letterFound = false;
        for (int i = 0; i < hiddenWord.length(); i++) {
            if (letterGuess == hiddenWord.charAt(i)) {
                swapBuffer.setCharAt(i, letterGuess);
                letterFound = true;
            }
        }

        if (!letterFound) numberLives--;
        outputWord = swapBuffer.toString();
    }

    public int getNumberLives() {
        return numberLives;
    }

    public String getHiddenWord() {
        return hiddenWord;
    }

    public String getOutputWord() {
        return outputWord;
    }

    public String getEndMessage() {
        return endMessage;
    }
}

Main Class
import javax.swing.*;
public class HangmanApp {

    public static void main(String[] args) {

        char letterGuess;
        int numberLives;
        String hiddenWord, outputWord, endMessage, restartGame;

        do {
            Hangman myHangman = new Hangman();

            JOptionPane.showMessageDialog(null, "Welcome to Java Hangman!");
            JOptionPane.showMessageDialog(null, "In this game, a word will be printed to you in asterisks - each letter will be revealed upon a correct guess!");
            JOptionPane.showMessageDialog(null, "You have 5 lives for the game, the game will end if you make too many incorrect guesses!");

            for (int i = 0; i < 10; i++) {
                hiddenWord = myHangman.getHiddenWord();
                numberLives = myHangman.getNumberLives();
                JOptionPane.showMessageDialog(null, "You currently have " +numberLives+ " lives!");
                letterGuess = JOptionPane.showInputDialog(null, "Now, please enter a letter : ").charAt(0);
                myHangman.setLetterGuess(letterGuess);

                myHangman.compute();

                outputWord = myHangman.getOutputWord();
                JOptionPane.showMessageDialog(null, "The word so far is  :  " +outputWord);
            }

            numberLives = myHangman.getNumberLives();
            JOptionPane.showMessageDialog(null, "You have finished the game with :  " +numberLives+ " lives!");
            restartGame = JOptionPane.showInputDialog(null, "Would you like to play again?");

        }

        while (restartGame.equalsIgnoreCase("Yes"));

    }
}

A: Here's the way I see it.  After you call myHangman.compute();, you want to check to see if the player has either won the game or run out of lives.  Each of these is a separate test using an if expression.  There is no else part because if the test fails, the game just goes on.
If one of these conditions is recognized, then you want to display a message, and then you want to exit the current game loop so the user will be asked if they want to play another game.  The way to do this is with the break statement.
One issue you have is that you don't have a way in your main game loop to ask the Hangman class if the user has guessed the whole word.  To be able to do this, you can add this method to the bottom of your Hangman class:
public boolean getAllLettersFound() {
    return outputWord.indexOf('*') < 0;
}

This method checks to see if there are any * in outputWord.  If not, then the user has guessed all the letters.  So with this method added, the main loop can query the Hangman object to find out if the player has won.
To put this all together, you need to add the two condition checks to your main game loop, right after you call myHangman.compute();.  Here are those two if blocks:
if (myHangman.getAllLettersFound()) {
    JOptionPane.showMessageDialog(null, "You Won!!!!");
    break;
}

if (myHangman.getNumberLives() == 0) {
    JOptionPane.showMessageDialog(null, "You Ran Out Of Guesses");
    break;
}

That should do it.  Happy coding!


text:
Q: Unsupported major.minor version 52.0 with Apache POI 3.9 and Java JDK 1.7 I'm try to create an easy program which generates a xls file, so I'm using APACHE POI 3.9. When I run that project, I have an excepcion:

Exception in thread "main" java.lang.UnsupportedClassVersionError: GenerarExcel/PruebaGenerarExcel : Unsupported major.minor version 52.0

I know that the reason why it doesn't work is because I must update my JDK (in fact, I did the same with JDK 1.8 and it works correctly), but one of the requirements of the program is that it must work with JDK 1.7.
I tried with JExcel API and I had the same problem.
Do you know which JAVA API I can use to generate that excel .xls document?


text:
Q: Сортировка первой строки двумерного массива по возрастанию Не могу найти в интернете как отсортировать первую строку двухмерного массива по возрастанию, используя функцию sort().
#include <iostream>
#include <algorithm>
#include <time.h>
#include <stdlib.h>
using namespace std;

int main()
{
    long n = 10;

    int A[n][n];
    int i, j, sum = 0, k = 0;

    cout << "Enter the matrix\n";

    for(i = 0; i < n; i++){
        for(j = 0; j < n; j++){
            A[i][j]=rand()%10;
            cout << A[i][j] << " ";}
        cout << endl;
    }

    for(i = 0; i < n; i++)
        for(j = 0; j < n; j++){
            if(i == j)
            {
                sum += A[i][i];
            }
        }
    cout<< endl << "Sum= " << sum;
    return 0;
}

A: sort(A[0], A[0]+n); и в C++ нельзя задавать размер массива неконстантной переменной. n должно быть const или constexpr

A: #include <iostream>
#include <algorithm>
#include <time.h>
#include <stdlib.h>
using namespace std;

int main()
{
    long n = 10;

    int A[n][n];
    int i, j, sum = 0, k = 0;

    cout << "Enter the matrix\n";

    for(i = 0; i < n; i++){
        for(j = 0; j < n; j++){
            A[i][j]=rand()%10;
            cout << A[i][j] << " ";}
        cout << endl;
    }
    sort(A[0], A[0] + n);
    cout<<"Отсортированная первая строка двухмерного массива:\n";
    for(i = 0; i < n; i++)
      cout<<A[0][i]<<' ';
    return 0;
}

Тут мы в качестве параметра функции sort передаем указатель на первый элемент первой строки и на конец первой строки


text:
Q: How to use printf to separate multiple decimal numbers and round all those numbers to 2 decimal places I want to use printf to organize my results of a code. The result of my code will have four decimal numbers. All those numbers has to be rounded to 2 decimal places and are organized on the same line.
I do not know much about how to use printf, I just know that %.2f can round my answer to 2 decimal places, and I do not know how to do the rest.
import java.util.Scanner;
import java.text.DecimalFormat;
import java.io.PrintWriter;
public class CirclePoints
{
    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);

        System.out.println("Please enter the radius of your circle: ");
        double radius = in.nextDouble();

        double x = 1.0;
        double z = x;
        double absY;
        double y1D;
        double y2D;
        double y1;
        double y2;

        System.out.println("Point on a circle with radius: " + radius);

        //System.out.printf(); want to get something like (x   y1   x   y2) as the reult that can match the bottom
        while(x >= -(z))
        {
            y1D = Math.sqrt((Math.pow(radius, 2) - Math.pow(x, 2)));
            y2D = -(Math.sqrt((Math.pow(radius, 2) - Math.pow(x, 2))));
            System.out.printf ("%.2f",x, y1D, y2D );
            x = x-0.1;
        }
    }
}

The actual out put should be something like
x     y1     x     y2
1.00   0.00   1.00  0.00
0.90   0.44   0.90  -0.44
...
-0.90  0.44   0.90  -0.44
-1.00  0.00   -1.00  0.00

A: There are 4 different to build print methods in java. By default, Java.lang package has been imported to all java classes so System class is in it. Three of the print methods are preceded by System.out.. Those are System.out.print, System.out.println, System.out.printf. There is no difference between print and println apart from the fact that println(print line) goes to a new line after the execution. The printf is referred to as the print format which means we can use the % character to indicate special cases. Like %n indicates and %t new tab. %.2f mean float with two decimal points and it will be rounded to the nearest value.
As I mentioned above the fourth print method is used to represent error outcomes. The syntax should be System.err instead of System.out. There is no difference with normal out.print methods and these err.print methods but the output is in red.
For your code change,
System.out.printf ("%.2f",x, y1D, y2D ); to
System.out.printf ("%.2f %.2f %.2f %.2f %n",x, y1D, x, y2D );


text:
Q: JavaScript: Algorithm or method to bind an array of objects to a DOM display? The Good:
We send a JSON array of nested objects using JQuery and .ajax().  We use JQuery and Microsoft templates to render the content.  It sends 100 objects in 400 ms.  This is so much faster than our equivalent server rendering of 50 products in 10 seconds.
The Difficulty:
We need to bind a JavaScript object array to the DOM html elements it represents, i.e., changes to the html input will reflect back to the JavaScript object.  Our difficulty is that our objects are nested, and only contain selected options:
Product[].Department[].deptid;
// We only store the departments for which this product participates

We tried Microsoft data linking using JQuery, which requires both object properties and html elements to exist in order to bind them together.  That doesn't do well for the above situation.  We could do this:
Product[].Department[].Dept.id;
Product[].Department[].Dept.name;
Product[].Department[].Dept.selected;  // true if selected, false if not
// This requires all possible options in all needed products.  Yuck

Are there any examples out there on how best to handle binding a JavaScript nested object array to the HTML elements they represent?
We don't submit form elements back to the server.  Instead we collect them in to a JSON array and send that back to the server.  It works extremely fast, but assembly is tedious.

A: It's hard to know exactly what you're having trouble with from your description, but it seems like there are two things that might help:
1) You can store data on a dom element using jQuery's data() method http://api.jquery.com/data/
2) You can get the value of a form element using the change() event and the val() method. (You can also find those in the API docs.)
But it seems like you could be running into something more basic, like the question of how to know which Javascript object goes with with form element. Is that the case?


text:
Q: How to prevent any editor from adding new sheet in google sheets workbook How can I prevent any anonymous editor from adding a new sheet inside the workbook. I wish to allow them to edit just one single sheet, but some editors mistakenly mess up the workbook by inserting unwanted sheets. thanks in advance. i tried the script in this link below but it does not seem to work.
Prevent users from creating new sheets in a shared google spreadsheet
// Deletes any tab named "SheetN" where N is a number
function DeleteNewSheets() {
  var newSheetName = /^Sheet[\d]+$/
  var ssdoc = SpreadsheetApp.getActiveSpreadsheet();
  var sheets = ssdoc.getSheets();

  // is the change made by the owner ?
  if (Session.getActiveUser().getEmail() == ssdoc.getOwner().getEmail()) {
    return;
  }
  // if not the owner, delete all unauthorised sheets
  for (var i = 0; i < sheets.length; i++) {
    if (newSheetName.test(sheets[i].getName())) {
      ssdoc.deleteSheet(sheets[i])
    }
  }
}

I created this spreadsheet https://docs.google.com/spreadsheets/d/1EdF8I0tyfQagfw1cxHCWgsr2umXi6-vbu7GvM8SJQSM/edit#gid=0 with the code above and set the triggers, but anyone could still create a new sheet.

A: I believe your current situation and goal are as follows.

*

*There is a sheet in Google Spreadsheet.

*You don't want to make the anonymous users insert a new sheet.

Issue and workaround:
In the current stage, unfortunately, there is no method for clearly detecting the edit of an anonymous user. In your script, I thought that the script can be used for the special permitted users. In this case, the anonymous users cannot be included. I thought that this might be the reason for your issue. So in order to achieve your goal, it is required to prepare a workaround. In this answer, I would like to propose a workaround.
When the sheet insert is detected, OnChange trigger can be used. But, the identification of the user is a bit difficult. When a function installedOnChange(e) is executed by the OnChange trigger, the following condition can be obtained. And, in order to check the active user, Session.getActiveUser().getEmail() and Session.getEffectiveUser().getEmail() are used.

*

*When the owner inserts a new sheet,

*

*e of installedOnChange(e) has the property of "user":{"email":"### owner's email ###","nickname":"### owner name ###"}.

*Session.getActiveUser().getEmail() and Session.getEffectiveUser().getEmail() return the owner's email.

*When the special permitted user inserts a new sheet,

*

*e of installedOnChange(e) has the property of "user":{"email":"","nickname":""}. In this case, no email address and no name are returned.

*Session.getActiveUser().getEmail() returns empty, and Session.getEffectiveUser().getEmail() returns the owner's email.

*When the anonymous user inserts a new sheet,

*

*e of installedOnChange(e) has the property of "user":{"email":"### owner's email ###","nickname":"### owner name ###"}.

*Session.getActiveUser().getEmail() and Session.getEffectiveUser().getEmail() return the owner's email.

*In this case, the situation is the same with the owner. But, in order to identify this, here, the simple trigger is used. Because the anonymous user cannot use the simple trigger. For example, when the anonymous user edits a cell, the simple trigger is not run. This situation is used.

When these conditions are reflected in a sample script, it becomes as follows.
Usage:
1. Prepare sample script.
Please copy and paste the following script to the script editor of Spreadsheet. And, please directly run onOpen function with the script editor. By this, the initial sheet name is stored in PropertiesService. And also, when the Spreadsheet is opened, onOpen is run. By this, the initial condition can be saved.
function onOpen() {
  PropertiesService.getScriptProperties().setProperty("sheetName", JSON.stringify(SpreadsheetApp.getActiveSpreadsheet().getSheets().map(s => s.getSheetName())));
}

function onSelectionChange(e) {
  CacheService.getScriptCache().put("simpleTrigger", JSON.stringify(e), 30);
}

function deleteSheet(e) {
  if (e.changeType != "INSERT_GRID") return;
  const sheetNames = JSON.parse(PropertiesService.getScriptProperties().getProperty("sheetName"));
  e.source.getSheets().forEach(s => {
    if (!sheetNames.includes(s.getSheetName())) e.source.deleteSheet(s);
  });
}

function installedOnChange(e) {
  const lock = LockService.getDocumentLock();
  if (lock.tryLock(350000)) {
    try {
      Utilities.sleep(3000); // Please increase this wait time when the identification is not correct.
      const c = CacheService.getScriptCache();
      const simpleTrigger = c.get("simpleTrigger");
      const activeUser = Session.getActiveUser().getEmail();
      const effectiveUser = Session.getEffectiveUser().getEmail();
      if (activeUser && effectiveUser && simpleTrigger) {
        // Operation by owner.

        // do something.
        PropertiesService.getScriptProperties().setProperty("sheetName", JSON.stringify(SpreadsheetApp.getActiveSpreadsheet().getSheets().map(s => s.getSheetName())));

      } else if (!activeUser && effectiveUser && simpleTrigger) {
        // Operation by permitted user.

        // do something.
        deleteSheet(e); // If you want to make the permitted user not insert new sheet, please use this line.

      } else {
        // Operation by anonymous user.

        // do something.
        deleteSheet(e);
      }
      c.remove("simpleTrigger");
    } catch (e) {
      throw new Error(JSON.stringify(e));
    } finally {
      lock.releaseLock();
    }
  } else {
    throw new Error("timeout");
  }
}

*

*In this sample script, the owner, the special permitted user, and the anonymous user are identified. And, the owner can insert a new sheet. But, when the special permitted user and the anonymous user insert a new sheet, the inserted sheet is deleted. By this, as a workaround, your goal might be able to be achieved.

*In this script, onSelectionChange is used as a simple trigger for detecting the anonymous user.
3. Install OnChange trigger as an installable trigger.
Please install a trigger to the function installedOnChange as the OnChange installable trigger. Ref
3. Testing.
In order to test this script, please insert a new sheet by the special permitted user and the anonymous users. By this, the inserted sheet is deleted. And, when the owner inserts a new sheet, the inserted sheet is not deleted.
Note:

*

*In this sample script, in order to check whether the simple trigger is executed, Utilities.sleep(3000) is used. So, the time for identifying the user is a bit long. I thought that this might be a limitation.

*For example, if you are not required to identify the users who insert a new sheet, you can also use the following simple script. Before you use this script, please install OnChange trigger to installedOnChange and run onOpen with the script editor. In this sample script, all users cannot insert a new sheet.
  function onOpen() {
    PropertiesService.getScriptProperties().setProperty("sheetName", JSON.stringify(SpreadsheetApp.getActiveSpreadsheet().getSheets().map(s => s.getSheetName())));
  }

  function installedOnChange(e) {
    const lock = LockService.getDocumentLock();
    if (lock.tryLock(350000)) {
      try {
        if (e.changeType != "INSERT_GRID") return;
        const sheetNames = JSON.parse(PropertiesService.getScriptProperties().getProperty("sheetName"));
        e.source.getSheets().forEach(s => {
          if (!sheetNames.includes(s.getSheetName())) e.source.deleteSheet(s);
        });
      } catch (e) {
        throw new Error(JSON.stringify(e));
      } finally {
        lock.releaseLock();
      }
    } else {
      throw new Error("timeout");
    }
  }

References:

*

*Installable Triggers

*Simple Triggers

*getActiveUser()

*getEffectiveUser()


text:
Q: PHP cUrl and cookie GX_SESSION_ID I am stuck with this matter.
I am trying to automatize a query in a website form and handle the return response with PHP. My code actually works BUT ONLY when i add the following header:
$headers = [
    'Cookie: GX_SESSION_ID=zWfdnmlQgtodK0ax97epfsbma9J0tvVI%2B%2BelShsOIZo%3D; JSESSIONID=E1378A4864FFF03AF4B8BAA0CBB88D89;',
];
curl_setopt($cURLConnection, CURLOPT_HTTPHEADER, $headers);

The JSESSIONID var is not a problem, the script runs well without it. But if i dont declare the GX_SESSION_ID var with a valid gx session id (which i take from google chrome browsing the website) the script dont works.
When i browse the website with Google Chrome, as soon as i enter the website. The cookie is sent in the Request Headers.
I dont understand how this var is being created.
Can you help me recreate this into my cURL PHP code? Create a calid GX_SESSION_ID without needing to get it manually from a browser?
Thank you all

A: Use the curl to get cookie variables as array:
$ch = curl_init('http://www.google.com/');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// get headers too with this line
curl_setopt($ch, CURLOPT_HEADER, 1);
$result = curl_exec($ch);
// get cookie
// multi-cookie variant contributed by @Combuster in comments
preg_match_all('/^Set-Cookie:\s*([^;]*)/mi', $result, $matches);
$cookies = array();
foreach($matches[1] as $item) {
    parse_str($item, $cookie);
    $cookies = array_merge($cookies, $cookie);
}
var_dump($cookies);


text:
Q: How to get notification of change in database I want that Whenever there is any change in Specific table of database, I get notification at run time, so that I may be able to take action accordingly in my Java program.I am using tomcat as server. Is JMS help me in this case.Kindly guide me if there is any way to do so.
Thanks


text:
Q: Evaluate $\int \frac{1}{2+\sin x+\cos x}dx.$ $$\int \frac{1}{2+\sin x+\cos x}dx.$$
My attempts:

*

*Let $y = \sin x+\cos x.\implies \frac{dy}{dx}=\cos x-\sin x=y'.$
$$\int \frac{1}{2+\sin x+\cos x}dx=\int\frac{1}{2+y}\frac{dy}{y'}.$$
And I tried to use the fact $(\ln x)'=1/x,$ but $(\ln(2+y))'=\frac{y'}{2+y}$ : the form doesn't match. So I think I've failed at this moment.

*Let $u=\sin x.\implies du=\cos x\ dx=\sqrt{1-u^2}dx.$
$$\int \frac{1}{2+\sin x+\cos x}dx=\int\frac{1}{2+u+\sqrt{1-u^2}}\frac{du}{\sqrt{1-u^2}}.$$
And it looks more uncomputable.
Both of my attempts are at a dead end. How to evaluate this integral? Any help would be appreciated.

A: Hint: Use the so-called Weierstrass substitution
$$\sin(x)=\frac{2t}{1+t^2}$$
$$\cos(x)=\frac{1-t^2}{1+t^2}$$
$$dx=\frac{2}{1+t^2}dt$$
A possible solution is given by $$\sqrt {2}\arctan \left( 1/4\, \left( 2\,\tan \left( x/2 \right) +2
 \right) \sqrt {2} \right)
+C$$

A: Hint:
$$\text{Let }\begin{bmatrix}\sin x \\ \cos x \\ \mathrm dx\end{bmatrix}=\begin{bmatrix}\dfrac{2t}{1+t^2}\\ \dfrac{1-t^2}{1+t^2}\\ \dfrac{2\mathrm dt}{1+t^2}\end{bmatrix}$$
This transforms $R(\sin x, \cos x)$ to a rational function in $t$ and you can  proceed with Partial Fraction Decomposition.


text:
Q: Get type from enum I'm working on a struct:
struct memory {
    enum data_type {
        INT, DOUBLE, SHORT
    };
    data_type dtype;

    void* get_data_handle() {
        // ...
    }
};

With this struct, I can describe some data in memory including its type (with the enum dtype) and data pointer. I can't modify the design of this struct.
Now I want to handle the data, so I can first use the function get_data_handle to get a void pointer, and then convert the pointer to the corresponding type. For example, if I have an object memory m;, and I know in advance that m.dtype = memory::data_type::DOUBLE, so I can safely using reinterpret_cast<double*>(m.get_data_handle()> to get the data pointer with the right type.
Here is the question, is there any elegant method which can do this when I don't know the dtype in advance? Just like something like:
auto data_ptr = reinterperet_cast<get_type(m.dtype)>(m.get_data_handle());