text:
Q: T-SQL Grouping with LESS THAN {date} that breaks off on each occurrence of date I am struggling with creating a grouping using LESS THAN that breaks off on each date for the parent row. I have created a contrived example to explain the data and what I would like out as a result:
CREATE TABLE [dbo].[CustomerOrderPoints](
[CustomerID] [int] NOT NULL,
[OrderPoints] [int] NOT NULL,
[OrderPointsExpiry] [date] NOT NULL
) ON [PRIMARY]
GO

CREATE TABLE [dbo].[CustomerOrderPointsUsed](
[CustomerID] [int] NOT NULL,
[OrderPointsUsed] [int] NOT NULL,
[OrderPointsUseDate] [date] NOT NULL
) ON [PRIMARY]
GO

INSERT [dbo].[CustomerOrderPoints] ([CustomerID], [OrderPoints], [OrderPointsExpiry]) VALUES (10, 200, CAST(N'2018-03-18' AS Date))
GO
INSERT [dbo].[CustomerOrderPoints] ([CustomerID], [OrderPoints], [OrderPointsExpiry]) VALUES (10, 100, CAST(N'2018-04-18' AS Date))
GO
INSERT [dbo].[CustomerOrderPoints] ([CustomerID], [OrderPoints], [OrderPointsExpiry]) VALUES (20, 120, CAST(N'2018-05-10' AS Date))
GO
INSERT [dbo].[CustomerOrderPoints] ([CustomerID], [OrderPoints], [OrderPointsExpiry]) VALUES (30, 75, CAST(N'2018-02-10' AS Date))
GO
INSERT [dbo].[CustomerOrderPoints] ([CustomerID], [OrderPoints], [OrderPointsExpiry]) VALUES (30, 60, CAST(N'2018-04-24' AS Date))
GO
INSERT [dbo].[CustomerOrderPoints] ([CustomerID], [OrderPoints], [OrderPointsExpiry]) VALUES (30, 90, CAST(N'2018-06-25' AS Date))
GO
INSERT [dbo].[CustomerOrderPoints] ([CustomerID], [OrderPoints], [OrderPointsExpiry]) VALUES (40, 100, CAST(N'2018-06-13' AS Date))
GO
INSERT [dbo].[CustomerOrderPointsUsed] ([CustomerID], [OrderPointsUsed], [OrderPointsUseDate]) VALUES (10, 15, CAST(N'2018-02-10' AS Date))
GO
INSERT [dbo].[CustomerOrderPointsUsed] ([CustomerID], [OrderPointsUsed], [OrderPointsUseDate]) VALUES (10, 30, CAST(N'2018-02-17' AS Date))
GO
INSERT [dbo].[CustomerOrderPointsUsed] ([CustomerID], [OrderPointsUsed], [OrderPointsUseDate]) VALUES (10, 25, CAST(N'2018-03-16' AS Date))
GO
INSERT [dbo].[CustomerOrderPointsUsed] ([CustomerID], [OrderPointsUsed], [OrderPointsUseDate]) VALUES (10, 45, CAST(N'2018-04-10' AS Date))
GO
INSERT [dbo].[CustomerOrderPointsUsed] ([CustomerID], [OrderPointsUsed], [OrderPointsUseDate]) VALUES (20, 10, CAST(N'2018-02-08' AS Date))
GO
INSERT [dbo].[CustomerOrderPointsUsed] ([CustomerID], [OrderPointsUsed], [OrderPointsUseDate]) VALUES (20, 70, CAST(N'2018-04-29' AS Date))
GO
INSERT [dbo].[CustomerOrderPointsUsed] ([CustomerID], [OrderPointsUsed], [OrderPointsUseDate]) VALUES (20, 25, CAST(N'2018-05-29' AS Date))
GO
INSERT [dbo].[CustomerOrderPointsUsed] ([CustomerID], [OrderPointsUsed], [OrderPointsUseDate]) VALUES (30, 60, CAST(N'2018-02-05' AS Date))
GO
INSERT [dbo].[CustomerOrderPointsUsed] ([CustomerID], [OrderPointsUsed], [OrderPointsUseDate]) VALUES (30, 30, CAST(N'2018-03-13' AS Date))
GO
INSERT [dbo].[CustomerOrderPointsUsed] ([CustomerID], [OrderPointsUsed], [OrderPointsUseDate]) VALUES (40, 120, CAST(N'2018-06-10' AS Date))

Customers gain points, which have an expiry. We have a CustomerOrderPoints table which shows OrderPoints for customers together with the Expiry date for the points. A Customer may have many rows in this table.
We then also have the CustomerOrderPointsUsed table which shows the points that have been used and when they were used by a Customer.
I am trying to get a grouping of Customer data which will show OrderPoints used as a group against each customer but, separated on the ExpiryDate. The picture below shows an example of the Grouped Results that I would like to obtain.

We have bad, but working code that has been developed using a recursive method (RBAR), but it is very slow. I have tried a number of different SET Based grouping approaches, but cannot get the final Less Than grouping which takes into account the previous expiry dates.
This DB is on SQL Server 2008R2. Ideally I am looking for a solution that will work with SQL Server 2008R2, but will welcome options for later versions, as we may need to move this particular DB to solve this problem.
I have tried using a combination of RanK, DenseRank and RowNumber (for later versions) and LAG, but have not been able to get anything working that can be built upon.
Is there a way to use SET based T-SQL to achieve this?

A: First - this is ignoring the question I raised in the comments above, and just allocates all rows to the expiry date on or after the use by date. You would need to rethink this if you need to split one use among multiple expiry dates
First, allocate an expiry date to each PointsUsed row. This is done by joining to all OrderPoints rows with an expiry date on or after the UseDate, then taking the minimum date.
Then the second query reports all OrderPoints rows, joining to the first query by the allocated expiry date, which has all the data needed.
WITH allocatedPoints as
(
    Select U.CustomerID, U.OrderPointsUsed, MIN(P.OrderPointsExpiry) as OrderPointsExpiry
    from CustomerOrderPointsUsed U
    inner join CustomerOrderPoints P on P.CustomerID = U.CustomerID and P.OrderPointsExpiry >= U.OrderPointsUseDate
GROUP BY U.CustomerID, U.OrderPointsUseDate, U.OrderPointsUsed
)

Select P.CustomerID, P.OrderPoints, P.OrderPointsExpiry,
    ISNULL(SUM(AP.OrderPointsUsed), 0) as used,
    P.OrderPoints - ISNULL(SUM(AP.OrderPointsUsed), 0) as remaining
from CustomerOrderPoints P
left outer join allocatedPoints AP on AP.CustomerID = P.CustomerID and AP.OrderPointsExpiry = P.OrderPointsExpiry
GROUP BY P.CustomerID, P.OrderPoints, P.OrderPointsExpiry


text:
Q: Ckeditor security concerns in laravel I want to let my users post articles on my website but i have serious concerns about ckeditor security.
What i want to ask is:

*

*Can users upload any kind of codes that can put my site at risk through ckeditor?

*Is there any way to limit users of those kind of actions?

About my application:
I'm using laravel 5.6 and ckeditor last version.
Please share your thoughts and experiences.

A: CKEditor is not insecure on purpose. No sense in developing an insecure product (except for educational purposes). It doesn't allow uploading executable content (as a feature). However, it does have a history of publicly exploited vulnerabilities, mostly due to it's handling of wide variety of user input that will be stored in user accessible locations/paths.
Nonetheless, you can still mitigate it's risks substantially if you simply restrict the paths which allow web app execution (php, asp, etc...).
PHP example:
Create an .htaccess file in the dir where ckeditor places it's user generated/uploaded data. Inside that file place the following:
php_flag engine off

There are additional methods to achieve this, which depend on your specific environment. But the main idea remains - block execution abilities in the target dir for user content/uploads, and watch out for security updates for all your components.
One last note - the best practice to avoid users uploading executable content would be to store in a non-web-exposed location. I would even advise outside of the web served root dir. This also would help to prevent a big portion of path traversal vulnerabilities. But specifically for CKEditor type of plugin it makes the solution much more complicated, since that content needs to be accessed by web users (by design!).

redpajama_set_name: RedPajamaStackExchange


text:
Q: LWC - Styling the button Quick question for the styling in LWC. This is styling in JS.
function changeVisibility() {
  document.getElementById("imgbox").style.visibility = "none";
}

And I'm trying to do this in LWC and have something like this(which won't work)
changeVisibility() {
  var retake = this.template.querySelector('imgbox');
  retake.style.display = "none";
}

Any idea?

A: Your query selector is likely wrong. Try:
var retake = this.template.querySelector('.imgbox');

Or query by almost any other property. Querying by id tends to be problematic, as the runtime modifies the values to make sure they're globally unique.
Demo.


text:
Q: Unix script to download file in other server I have a scenario where I need to write a shell script which has to download a file in a remote directory.
Eg: I logged into Server A and from there my script needs to login to Server B and using wget command it has to download a file.
Any suggestions on this?

A: Instead of doing an SSH into Server B and then doing a wget, I would suggest that you first download the file onto Server A and then scp it to Server B at the path you want.


text:
Q: Can't get the temperature to change from Celsius to Fahrenheit in my local weather app
*

*User Story: I can see the weather in my current location.

*User Story: I can see a different icon or background image (e.g. snowy mountain, hot desert) depending on the weather.

*User Story: I can push a button to toggle between Fahrenheit and Celsius.

These are the user stories for the website. I have managed to complete 1 and 2 but I am completely stuck on 3, I have a good idea of how I would manage to do this but I can't manage to make it work with various methods(not just the one in my code) but I think I may of coded this badly but it is the only way I know because I am new. Someone suggested to me to use an if but it doesn't work as it would only be able to change the text on document load and not continuously. This is the example. Any advice on a better way about this would be greatly appreciated and sorry for the long post.
Html:

Weather!

      <input type="text" class="form-control" placeholder="City">

      <button type="button" class="btn btn-default" id="searchBtn">Search</button>

        <input type="checkbox" value="" id="fCheck">View in °F

Css:
html, body {
  margin: 0;
  padding: 0;
  font-family: 'Dosis', sans-serif;
  background-color: #3f3f3f;
}
.main{
  position: relative;
  margin: 10% auto auto auto;
  width: 75%;
  text-align: center;
  background-color: #8E9EBC;
  padding: 10px;
  border-width: 3px;
  border-style: solid;
  border-color: black;
  border-radius: 5px;
}
.main h1 h2 h3 h4{
  margin: 0;
}

.main img {
  width: 100px;
}
.title hr {
  border-width: 2px;
}

#degrees h4 {
  text-align: left;
}
#searchBtn {
  width: 100%;
}

Js:
$(document).ready(function() {
  var api = "secretAPIKey";

  $.getJSON("http://ip-api.com/json", function(json)  {
    var userCity;
    userCity = JSON.stringify(json.city);
    userCity = userCity.replace(/\"/g,"");
    makeElementsFromCity(userCity);
  });
  var celsius;
  var name;
  var faren;
function makeElementsFromCity(userCity) {
    $.getJSON("http://api.openweathermap.org/data/2.5/weather?q=" + userCity + "&units=metric&appid=" + api, function(json) {
        name = JSON.stringify(json.name + ", " + json.sys.country);
        celsius = JSON.stringify(json.main.temp);
        faren = celsius * 9 / 5 + 32;
        var icon = JSON.stringify(json.weather[0].icon);
        var type = JSON.stringify(json.weather[0].main);
        var humidity = JSON.stringify(json.main.humidity)
        var windS = JSON.stringify(json.wind.speed);
        var sunR = JSON.stringify(json.sys.sunrise);
        var sunS = JSON.stringify(json.sys.sunset);
        icon = icon.replace(/\"/g,"");
        type = type.replace(/\"/g,"");
        celsius = Math.round(celsius);
        faren = Math.round(faren);
        //get sunset and sunrise unix into time
      function formatSunR(date) {
        var date = new Date(date*1000);
        var hours = date.getHours();
        var minutes = "0" + date.getMinutes();
        var seconds = "0" + date.getSeconds();
        var formattedTime = hours + ':' + minutes.substr(-2);
        return formattedTime;
      };
        //update h2 with city, country and temperature and testing to see what weather.icon is but comes back as undefined
        //updates h3 with the type of weather & city is placeholder for testing the city variable
        $("#temp h3").text(type);
        //display image of weather type from https://openweathermap.org/weather-conditions
        $("#temp img").attr("src", "http://openweathermap.org/img/w/" + icon + ".png");
        $(".info #humidity").text("Humidity: " + humidity + "%");
        $(".info #windspeed").text("Wind Speed: " + windS + " MPH");
        $(".info #sunrise").text("Sunrise: " + formatSunR(sunR));
        $(".info #sunset").text("Sunset: " + formatSunR(sunS));

      if($("#fCheck").is(":checked")) {
        $("#temp h2").text("The temperature in " + name + " is " + faren + "°F");
      } else {
        $("#temp h2").text("The temperature in " + name + " is " + celsius + "°C");
        console.log(faren);
      }
      });

    };

});

A: You can try this HTML
temp

with this JS and adapt it to your situation.
        var temp = 25;
        var celsius = temp;
        var fahr = (1.8 * temp + 32);
        var switch_ = new Boolean(false);

        $("#toggle").on("click", function() {
            switch_ = !switch_;
            var temp = switch_ == true ? celsius + " °C" : fahr + " °F";
            $(this).text(temp);
        });


text:
Q: relative import does not work in Python I have a project structure like this...
app/
    main.py
    app/
        __init__.py
        boot.py
        server.py
        controllers/
            __init__.py
            home.py

The imports are...
# main.py
from app import server

# server.py
from . import boot

# boot.py
from . import controllers

# controllers/__init__.py
from . import home

# controllers/home.py
from .. import boot

Now all the imports are working except the last one. The error thrown is...
ImportError: cannot import name boot

What's the problem? (I am using Python 3.2)

A: You are importing boot which is importing controllers, which is then asked to import home, and home then tries to import boot, but it wasn't done importing yet. Don't do this, you are creating a circular dependency here.
Also see Circular import dependency in Python


text:
Q: match all query against elastic search index Looking at this, I am wondering, if it is also possible to search an index simply by a string, e.g.:
Hello World

and receive data not bound to an explicit entity. Some pseudo code:
 var searchResponse = client.Search(MatchAllQuery ...?, index=someIndex, q="Hello World")

A: You can try this out:
var searchResponse = client.Search<Document>(sd => sd
    .Index("index_name")
    .Type("type")
    .Size(10000)
    .Query(q => q
        .Match(m => m.Field("TextID").Query("Hello World")
        )));


text:
Q: Unable to install 'wrtc' package while trying to run the serverless-webrtc code : https://github.com/cjb/serverless-webrtc. The error log is below
10923 error Linux 3.16.0-41-generic 10924 error argv "node"
  "/usr/local/bin/npm" "install" 10925 error node v0.10.25 10926 error
  npm  v2.11.2 10927 error code ELIFECYCLE 10928 error wrtc@0.0.56
  install: node-pre-gyp install --fallback-to-build 10928 error Exit
  status 1 10929 error Failed at the wrtc@0.0.56 install script
  'node-pre-gyp install --fallback-to-build'. 10929 error This is most
  likely a problem with the wrtc package, 10929 error not with npm
  itself. 10929 error Tell the author that this fails on your system:
  10929 error     node-pre-gyp install --fallback-to-build 10929 error
  You can get their info via: 10929 error     npm owner ls wrtc 10929
  error There is likely additional logging output above.


text:
Q: Edit ASP.NET Core website in Docker container on Windows and run on Ubuntu VPN I want to create a ASP.NET Core 2.0 website in a docker container and host it on a Linux VPS docker system. I tried creating an ASP.NET Core 2.0 project in Visual Studio, and then publishing it to docker hub. Everything works great, until I want to run that docker image on my Linux environment. I then get an error saying that this image is created for windows or something equivalent. I know I need to create the asp.net project in the Linux environment, then start coding (obviously), but I want to do the coding in for example Visual Studio on my PC, not via PICO or some other ssh-connected editor.
Summarized:
- I wish to run ASP.NET Core 2.0 website on Linux Docker VPS environment.
- I (think I) need to create the project in the Linux environment (I run Windows locally).
- Wish to edit the code in the docker container locally on my Windows environment.

Anyone know how I can achieve this?

A: Before creating ASP.NET Core 2 website on your windows operating system, right click on the Docker icon in system tray and then click Switch to Linux containers. Once switched to Linux containers, create ASP.NET Core website that you can host on Linux.


text:
Q: Why does passing a state value pass a dictionary? I'm passing a state value to a component.
function MySubComponent(count) {
  console.log(count);
  return null;
}

export function MyComponent() {
  let [state, setState] = useState({count: 1});
  return <MySubComponent state={state.count} />;
}

I expect it to log 1, but instead it logs {state: 1}. Why?

A: In MyComponent.js,
In this line,
<MySubComponent state={state.count} />;

You are mentioning the props name as state which you could change it to count so that you can access the count value in MySubComponent .
So it would be like,
<MySubComponent count={state.count} />

In MySubComponent.js , while receiving props, you could use the normal and curly braces to receive the exact value. (count) will give you whole props whereas ({ count }) gives you the exact count value passed into props.
function MySubComponent({ count }) { ... }

Finally,
MyComponent.js
function MyComponent() {
  let [state, setState] = useState({ count: 1 });
  return <MySubComponent count={state.count} />;
}

export default MyComponent;

MySubComponent.js,
function MySubComponent({ count }) {
  console.log(count);
  return null;
}

Working Codesandbox

A: "count" in your subComponent is treating as props.
If you expecting the log output is "1", then you can change it into:
function MySubComponent({state}) {
  console.log(state);
  return null;
}

OR:
function MySubComponent(props) {
      console.log(props.state);
      return null;
    }


text:
Q: Categorifying the Reals via von Neumann Algebras? So one way to categorify the natural numbers is to replace them with vector spaces. Then the dimension of the vector space reproduces the natural number. More generally you can categorify integers to graded vector spaces. Also a linear monoidal category (assuming some finiteness conditions) will lead to an algebra defined over the natural numbers and so can be viewed as a categorification of the this algebra.
Now one thing that I found intriguing when I learned about factor von Neumann algebras is that the type II_1 factor has modules which have "dimensions" which land in the (positive) real numbers. Has anyone ever seen a categorification of some real number quantity by using these sorts of modules? It seems that graded modules (or complexes of modules) would then give all real numbers.
Is there some sort of categorification of real algebras to a monoidal category enriched over II_1-modules? Or some other type of categorification of the reals which I am not even guessing at?

A: One categorification of the reals that I know of is via groupoids; see Aleks Kissinger's comment on the groupoid question as well as the accompanying link.

A: In a sense we already have a great categorification of the complex numbers, and that's given by FdHilb, the *-category of finite-dimensional Hilbert spaces and continuous maps. Results like the Doplicher-Roberts theorem give us good reasons to believe this. So from this perspective, we don't need to go as far as looking at fancy von Neumann algebras to get what you want.
One point I'm implicitly making here is that categorification isn't necessarily the inverse process to taking isomorphism classes!


text:
Q: In my apache chemistry CMIS i got a conflict error while i am syncronize two document This is my CMIS Sync code.
    String documentName = null;
    StringBuilder contentBuilder= new StringBuilder();
    ByteArrayInputStream inputStream;
    byte[] buffer = null;

    session=getSession(sourceClientIbmNet);
    CmisObject cmisObjectSource = session.getObject(sourceId);
    if (BaseTypeId.CMIS_DOCUMENT.equals(cmisObjectSource.getBaseTypeId())) {
                Document document = (Document) cmisObjectSource;

        List<String> fileContent = getFileContent(document);

        for(String string: fileContent){
            contentBuilder= contentBuilder.append(string+"\n");
                            }
    }
    session = null;
    session=    getSession(destinatioClientIbmNet);

    CmisObject cmisObjectDestination=session.getObject(destinationId);

    if (BaseTypeId.CMIS_DOCUMENT.equals(cmisObjectDestination.getBaseTypeId())) {

        Document document = (Document) cmisObjectDestination;
        documentName = document.getName();

         if (((DocumentType) (document.getType())).isVersionable()) {
             document.refresh();
        Document pwc = (Document) session.getObject(document.checkOut());//Here i got exception
                String mimetype = "text/plain; UTF-8";
                String content = contentBuilder.toString();
                try {
                    buffer = content.getBytes("UTF-8");
                } catch (Exception e) {
                }

                inputStream = new ByteArrayInputStream(buffer);

                ContentStream contentStream = session.getObjectFactory()
                        .createContentStream(document.getName(), buffer.length,
                                mimetype, inputStream);
                try {
                    pwc.checkIn(true, null, contentStream, "minor version");
                } catch (CmisBaseException e) {
                    e.printStackTrace();
                    pwc.cancelCheckOut();
                }
                if (contentStream != null) {
                    List<String> newContent;
                    ContentStream contentStream11 = document.getContentStream();
                    newContent = getFileContent(document);
                }
                }
        }

This is Exception...
org.apache.chemistry.opencmis.commons.exceptions.CmisConstraintException: Conflict
    at org.apache.chemistry.opencmis.client.bindings.spi.atompub.AbstractAtomPubService.convertStatusCode(AbstractAtomPubService.java:499)
    at org.apache.chemistry.opencmis.client.bindings.spi.atompub.AbstractAtomPubService.post(AbstractAtomPubService.java:661)
    at org.apache.chemistry.opencmis.client.bindings.spi.atompub.VersioningServiceImpl.checkOut(VersioningServiceImpl.java:95)
    at org.apache.chemistry.opencmis.client.runtime.DocumentImpl.checkOut(DocumentImpl.java:237)
    at com.aegis.web.util.CmisClientIbmNet.updateContent(CmisClientIbmNet.java:304)
    at com.aegis.web.controller.RepositoryController.sourceToDestinationSYNC(RepositoryController.java:329)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)


text:
Q: How to get the only min area rectangle on a multiple contours image with cv2.minAreaRect(cnt)? I want to use only one rectangle to cover the circle in this image:

And get this result with cv2.minAreaRect(cnt):

This image seems to be divided into multiple parts. Maybe it's because there are some breakpoint on the edge of this image. can you tell me how to use only one rectangle to cover this circle of my image? Thank you very much!
This is my code:
def draw_min_rect_circle(img, cnts):  # conts = contours
    img = np.copy(img)

    for cnt in cnts:
        x, y, w, h = cv2.boundingRect(cnt)
        cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)  # blue

        min_rect = cv2.minAreaRect(cnt)  # min_area_rectangle
        min_rect = np.int0(cv2.boxPoints(min_rect))
        cv2.drawContours(img, [min_rect], 0, (0, 255, 0), 2)  # green

        (x, y), radius = cv2.minEnclosingCircle(cnt)
        center, radius = (int(x), int(y)), int(radius)  # center and radius of minimum enclosing circle
        img = cv2.circle(img, center, radius, (0, 0, 255), 2)  # red
return img

A: You probably searched for contours with the cv2.findContours() and iterated through them to draw the rectangle on the image. The problem is that your image doesn't have the circle made out of one connected line but many broken lines.
Contours are curves joining all the continuous points (along the boundary), having same color or intensity (OpenCV documentation).
So to get a better result you should first prepare your image before you search for contours. You can use various tools for preprocessing the image (you can search the OpenCV documentation). In this case I would try to perform the procedure called "closing" with a small kernel. Closing is dilation followed by erosion of pixels. It can help connect your small contours to a one big contour (circle). Then you can select the biggest one and draw a bounding rectangle.
Example:
Input image:

import cv2
import numpy as np

img = cv2.imread('test.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)
kernel = np.ones((3,3), dtype=np.uint8)
closing = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
_, contours, hierarchy = cv2.findContours(closing, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
cnt = max(contours, key=cv2.contourArea)
x,y,w,h = cv2.boundingRect(cnt)
cv2.rectangle(img, (x,y), (x+w, y+h), (255,255,0), 1)
cv2.imshow('img', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Result:

Image after performing the closing operation:

Hope it helps. Cheers!

A: It is possible to join all the contours into a single contour, as they are just numpy arrays of point coordinates describing the contour. You can use np.concatenate(contours) and it seems the cv2.minAreaRect function doesn't care that the points in the new array are not continuous. In my case this worked better than using the closing function, as I have more complex objects. If you want you can give it a try, it's simple. This is how your function should look like:
def draw_min_rect_circle(img, cnts):  # conts = contours
    img = np.copy(img)

    join_cnts = np.concatenate(cnts)

    x, y, w, h = cv2.boundingRect(join_cnts)
    cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)  # blue

    min_rect = cv2.minAreaRect(join_cnts)  # min_area_rectangle
    min_rect = np.int0(cv2.boxPoints(min_rect))
    cv2.drawContours(img, [min_rect], 0, (0, 255, 0), 2)  # green

    (x, y), radius = cv2.minEnclosingCircle(join_cnts)
    center, radius = (int(x), int(y)), int(radius)  # center and radius of minimum enclosing circle
    img = cv2.circle(img, center, radius, (0, 0, 255), 2)  # red

return img

A: What you need to do is that you need to somehow obtain only 1 contour from the image by merging the contours, that is a bit difficult to do, so if you only want an enclosing rect around all contours, you can do something as such
def draw_min_rect_circle(img, cnts):  # conts = contours
    img = np.copy(img)
    x1,y1 = np.inf
    x2,y2 = 0
    for cnt in cnts:
        x, y, w, h = cv2.boundingRect(cnt)
        if x > x1:
           x1=x
        if y > y1:
           y1=y
        if x2 < x+w
           x2 = x+w
        if y2 < y+h
           y2 = y+h
     w = x2 - x1
     h = y2 - y1
     r = math.sqrt((w*w) + (h*h)) / 2

     cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)
     cv2.circle(img, (x1+w/2,y1+h/2), r, (0, 0, 255), 2)


text:
Q: How to remove certain dictionaries from list? I have a list with dictionaries:
list_with_dicts = [{"nbr": 1, "id": 11}, {"nbr": 2, "id": 13}, {"nbr": 3, "id": 15}, ...]

I have a list that contains all the id:s I want to remove from the list with dictionaries:
ids = [11, 15, ...]

How can I do this effectively? I saw this answer here, however it does not cover if I need to iterate through the ids list.

A: You don't have to iterate over the ids list, at least not explicitly. Iterate over the dictionaries list and check if the id value is in the ids list using in. If you itreate over a copy of the list you can use remove(dict) to remove the dictionary from the list
list_with_dicts = [{"nbr": 1, "id": 11}, {"nbr": 3, "id": 15}, {"nbr": 2, "id": 13}]
ids = [11, 15]

for d in list_with_dicts[:]:
    if d['id'] in ids:
        list_with_dicts.remove(d)

print(list_with_dicts) # [{'nbr': 2, 'id': 13}]

If you want to preserve the original list you can build a new one using list comprehensions
new_list_with_dicts = [d for d in list_with_dicts if d['id'] not in ids]


text:
Q: jQuery spinner button won't style active state I'm trying to style the active state of jQuery spinner buttons like this:
.ui-spinner .ui-spinner-button:hover {
    background: #FF0;
}

.ui-spinner .ui-spinner-button:active{
    background: #0FF;
}

Hover is working, but active is not. See jsfiddle example here.
Please excuse the ugly colors - just have those for simplicity's sake.
Update: the issue is primarily in Firefox - it doesn't present itself in Chrome

A: I dont know how to do it in css tried some options but they dont work but i managed to solve it in jquery give it a try
$(".ui-spinner .ui-spinner-button").click(function(){
        //background you want to be in active state
        $(this).css("background","#111");

    //reverse the background in 0.1 second
        setTimeout(function(){
              $(".ui-spinner .ui-spinner-button").css("background","#fff");
        }, 100);
});

it works both in firefox and chrome, but you should remove the :active from css since it's going to work in chrome and you will get a mix of active state with the color specified in css and the one in jquery

A: Just replace :active pseudo-selector by :focus. See here: http://jsfiddle.net/xvWG5/92/
PD: I also replaced type="submit" by type="button" so I stay on the page.

Your new fiddle get fixed the same way. Checked: http://jsfiddle.net/xyb9fr35/2/
Same thing: replace :active by :focusand use #testSpinner as a selector instead of the class because that class is not in the DOM when the css is applied.

A: It looks like jQuery's background image is taking precedence over background color in Firefox. Try this:
.ui-spinner .ui-spinner-button:hover {
    background-color: #FF0;
    background-image:none;
}

.ui-spinner .ui-spinner-button:active{
    background-color: #0FF;
    background-image:none;
}


text:
Q: Why await execute a query of mongoose? I'm working with mongoose and I had a question about how the Query type and await work in mongoose.
When I execute const result = await Model.findOne(query), the result is the Model found in database, and that is fine. But if i don't write await, the result is Query type.
Well this is not a problem, but i don't understand how can mongoose execute the Query with the await command and don't execute without it.
I am very curious how this works.
And by the way, sorry for my grammar.


text:
Q: Change i3-sensible-terminal I've spent some time searching whether it's possible to change i3-sensible-terminal, for me it's from urxvt to Alacritty. Everyone suggests to put this keybinding in i3 config: bindsym $mod+Return exec alacritty. But that's only partial solution, since it doesn't work when system is trying to open some file in terminal automatically. For example when i3wm displays issue in configuration file, and you want to edit that, it automatically opens in in urxvt.
So, I'm looking for some way, how to "really" change i3-sensible-terminal.
Thanks.

A: Ok, I could't find solution how to change that, but what worked for me was that I removed urxvt from my system, though it was little tricky (official package name is rxvt-unicode).

A: One solution I've found is to modify /usr/bin/i3-sensible-terminal, and change the order of the terminals.
So for example, by default the file is something like:
for terminal in "$TERMINAL" x-terminal-emulator urxvt (etc etc) alacritty (etc etc)

You could modify it so that alacritty appears in the list before urxvt, and is therefore loaded first:
for terminal in "$TERMINAL" alacritty x-terminal-emulator urxvt (etc etc)

Alternatively, you should be able to modify the line:
exec "$terminal" "$@"

to be something like:
exec alacritty

You can also put other options there aswell, for example, mine is:
exec "$terminal" "$@" -rv -e bash -l


text:
Q: Check if user likes the page in Facebook I'm trying to check if the user likes the page or not with the following PHP and FQL code:
<?PHP
include 'facebook.php';
$facebook = new Facebook(array(
  'appId'  => 'my_app_ID',
  'secret' => 'my_App_secrert',
));
$user =$facebook->getuser();
$page_id= "200279160150349";
$result = $facebook->api(array(
    "method"    => "fql.query",
    "query"     => "SELECT uid FROM page_fan WHERE uid=$user AND page_id=$page_id"
));
if(count($result))
{
    echo "is a fan!";
}
else
{
echo "Not Fan";
}
?>

Determine that the user is authorized in another page
But always print Not Fan   :(

A:

      YOU DON'T LIKE ME :(

      YOU LIKE ME :)


text:
Q: How to debug status code 500 in Eclipse Tomcat? I am new to Java based Web Development.
I am using Eclipse Version: 2018-09 (4.9.0), JDK 1.8, Tomcat v9.0
I am currently building a tutorial Jersey Maven project. I just created an API endpoint but am getting status 500. The problem is I don't know how to debug it.
here is the controller code
@Path("aliens")
public class AlienResource {

    @GET
    @Produces(MediaType.APPLICATION_XML)
    public Alien getAlien() {
        Alien a1 = new Alien();
        a1.setName("hello");
        a1.setPoint(23);
        System.out.println("*****");
        System.out.println(a1);
        return a1;
    }
}

The eclipse console has no errors. It does have the System.out.println("*****") and System.out.println(a1);, which means that the function getAlien() is being called.
Upon researching the internet I found that Tomcat in eclipse prints out the server logs in the console itself, however, using this link I did try to redirect the logs to some other file, catalina.out which I created inside my workspace. I also did a sudo chmod a+w catalina.out in order to avoid any permissions issue. But catalina.out remains empty.
I don't understand how do I debug the 500 error and where will I get the error log?
PS: the default API endpoint provided by jersey works ie. http://localhost:8080/demorest/webapi/myresource works fine.


text:
Q: How to change the color of the spinner NOT the dropdown items? I have added a Spinner with a custom listadapter which uses this layout:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    android:layout_height="fill_parent"
    android:layout_width="fill_parent"
    android:gravity="center"
    android:textColor="@drawable/default_spinner_item_text"
    android:text="Sample Text"
    android:textSize="20dp"
    android:paddingBottom="7.5dp"
    android:background="@drawable/default_spinner_item"
    android:paddingTop="7.5dp">

</TextView>

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

    <item android:state_checked="true" android:drawable="@android:color/transparent"/>
    <item android:state_single="true" android:drawable="@android:color/transparent"/>
    <item android:state_active="true" android:drawable="@android:color/transparent"/>
    <item android:state_first="true" android:drawable="@android:color/transparent"/>
    <item android:state_focused="true" android:drawable="@android:color/transparent" />
    <item android:state_selected="true" android:drawable="@android:color/transparent" />

    <item android:drawable="@color/default_button_border_color" />
</selector>

The spinner allways gets the same color as the dropdown items...
I have tried all the states but it seams impossible to make the spinner item background transparent and the dropdown list colored (default_button_border_color).
@Solved
This is my Adapter:
public class CustomSpinnerAdapter extends ArrayAdapter<String> {

    private int _resource;
    private Typeface _typeFace;

    public CustomSpinnerAdapter(MainActivity context, int resource, List<String> items) {
        super(context, resource, items);
        _resource = resource;
        _typeFace = context.getDefaultAppTypeFace();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        TextView view = (TextView)super.getView(position, convertView, parent);
        if(convertView == null)
           view.setTypeface(_typeFace);
        }
        return view;
    }

    @Override
    public TextView getDropDownView(int position, View convertView, ViewGroup parent) {
        TextView view = (TextView) super.getDropDownView(position, convertView, parent);
        if(convertView == null)
           view.setTypeface(_typeFace);
        }
        return view;
    }
}

I now use two layouts, one for the view and one for the dropdownview. Another error in my code was that I called super.getView(position, convertView, parent); in the getDropDownView ovverride.

A: just make two layout with desired color and set it like following:
ArrayAdapter<yourObjecttype> adapter = new ArrayAdapter<yourObjecttype(this,R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(R.layout.dropdown_layout);

A: You will have to do it from code.
The BaseAdapter, ArrayAdapter and others implement an interface called SpinnerAdapter
This interface provides a method called getDropDownView. Using this method for the DropDown elements and the "normal" getView method for the selection should do the trick.
If you're using ArrayAdapter, you can also use it's setDropDownViewResource method

A: Try this
<Spinner
android:id="@+id/spinner1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@drawable/myspinner_background" />

under Drawable folder place this myspinner_background.xml
myspinner_background.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item   android:drawable="@drawable/big_drop_down_selected"
            android:state_focused="false"
            android:state_pressed="true"/>
    <item   android:drawable="@drawable/big_drop_down"/>

</selector>

in Activity
private ArrayAdapter<String> adpFromStation;
Spinner spnrFromStation = (Spinner) findViewById(R.id.spinner1);
adpFromStation = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,StationNamesList);
        adpFromStation.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spnrFromStation.setAdapter(adpFromStation);

A: Use XML file to change the spinner color
<Spinner
    android:id="@+id/idSpinner"
    android:layout_width="match_parent"
    android:layout_height="@dimen/_50sdp"
    android:background="@color/white" />

Use Java file to change spinner color programmatically
idSpinner = findViewById(R.id.idSpinner);
idSpinner.setBackgroundColor(getResources().getColor(R.color.black));


text:
Q: previous / next within a range of numbers hey all.. i need a function that would return a previous and next numbers, but only within my numbers range.
so, for example, if my range is from 0 to 7, and im on 6 - next should return 7. if im on 7 - next should return 0 (it circled back to it).
same for previous, if im on 0, previous should be 7. I think modulo can be used to figure this out, but cant figure out how. the function should take 3 arguments- current number we are on, maximum number and if we are going back or forward. something like
getPreviousOrNext(0, 7, "next" or "prev" )
thanks!!!

A: Use modulo..
function getPreviousOrNext(now, max, direction) {
    totalOptions = max + 1; //inlcuding 0!

    newNumber = now; // If direction is unclear, the number will remain unchanged
    if (direction == "next") newNumber = now + 1;
    if (direction == "prev") newNumber = now + totalOptions - 1; //One back is same as totalOptions minus one forward

    return newNumber % totalOptions;
}

(could be shorter, but this makes it more understandable)
Edit: The "now + totalOptions - 1" prevents us from going into negative numbers (-1 % 7 = -1)
Edit2: Ouch, there was a small error in the code..."If direction is unclear, the number will remain unchanged" was not correct!
Edit3: And for a bonus, this is how I would have written it before reading Code Complete ;-) (assumes it's 'next' whenever it's not 'prev'). This is ugly and beautiful in one :
function getPreviousOrNext(now, max, direction) {
   return (now + ((direction=="prev")?max:1)) % (max + 1);
}

A: is this a homework assignment?
i wouldn't use modulo, a handful of if/ternary statements should be sufficient.

A: var cycle_range = function (high, current) {
    return new function () {
       this.next = function () {
           return current = (current+1) % (high+1);
       };

       this.previous = function () {
           return current = (current+high) % (high+1);
       };
    }
};

cycle_range(7, 0).next() // 1

var the_range = cycle_range(7, 0);
the_range.next() // 1
the_range.next() // 2
the_range.previous() //1
the_range.previous() //0
the_range.previous() //7


text:
Q: Unable to deserialize or get the values into my object from service How to deserialize this below result from service to my object? I want only the Name, City and State values. I tried to use
{{
  "id": "123",
  "name": "Kaizen",
  "living": {
    "city": "Sydney",
    "state": "NSW"
  },
  "Country": {
    "name": "Australia",
    "region": "APAC"
  }
}}

JavaScriptSerializer details= new JavaScriptSerializer();
                var detailsOfDoc= service.Deserialize<DoctorDetails>(docDetails.ToString());

My DoctorDetails Class is as follows

public class DoctorDetails
{
 public string Name { get; set;}
public string State{ get; set;}
public string City{ get; set;}
}

I see the values as null in detailsOfDoc variable.
EDIT
The below response is what I get in the endpoint when I hit in browser for an ID
<DoctorDetails xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="Northshore.Details">
<Id>111</Id>
<Name>Kaizen</Name>
<Living>
<City>Sydney</City>
<State>NSW</State>
</Living>
<Country>
<Name>Australia</Name>
<Region>APAC</Region>
</Country>
</DoctorDetails>


text:
Q: group data from json i want show table product base of supplier, data from json
final display like this
supplier 1
product 1
product 2
product 3
supplier 2
product 1
product 2
prodoct 3
here is my json data
{
   "data":{
      "query":[
         {
            "key":"a27239eaec62ba6405f5e9f0fb715bd5"
         }
      ],
      "status":[
         {
            "code":202,
            "description":"ok"
         }
      ],
      "results":[
         {
            "id":"177",
            "user_id":"87",
            "supplier_id":"6",
            "product_id":"36",
            "product_name":"Tripod octopus",
            "varian_id":"141",
            "varian_name":"Varian Acak",
            "jumlah":"1"
         },
         {
            "id":"178",
            "user_id":"87",
            "supplier_id":"8",
            "product_id":"37",
            "product_name":"Pembersih Mata Buah Nanas",
            "varian_id":"140",
            "varian_name":"Acak",
            "jumlah":"3"
         },
         {
            "id":"179",
            "user_id":"87",
            "supplier_id":"8",
            "product_id":"42",
            "product_name":"Gunting dahan pohon",
            "varian_id":"135",
            "varian_name":"gunting dahan",
            "jumlah":"1"
         }
      ]
   }
}

and here is my code without grouping data
$datainventory = json_decode($jsondata, true);
$totalRecord = count($datainventory['inventory']['results']);
for ($j=0; $j < $totalRecord; $j++)
{
 echo  $datainventory['data']['results'][$j]['supplier_id'];
 echo  $datainventory['data']['results'][$j]['product_name'];
}

please any one can grouping my data json? thank you

A: i was got the answer
 foreach ($newdatainventory as $supplier_id => $product)
    {
    foreach ($product as $productname)
      {

       }

    }


text:
Q: jQuery Datatables adding 2 columns I am trying to add two columns with the fllowing code in the ajax that returns the data (Yarja)
 public function AllUsersData(Request $request)
    {
       $us = DB::table('users')
            ->join('clients','users.client_id','=','clients.id')
            ->select('users.id as id','users.name as name','users.email as email','clients.companyName as company','users.active','users.operative','users.superAdmin')
            ->get();
       return Datatables::of($us)
       ->addColumn('action', function($pubs){
             $btn = '

';
             return $btn;
        })
       ->addColumn('action2',function($pubs){
            $editBtn = '

';
            return $editBtn;
       })
        ->make(true);
    }

This will enable me to render each column with a link.
My problem is that it is returning the second addColumn wrongly.
Here is what is being returned:
"id": "3",
"name": "Jim Elliott",
"email": "webmaster@tdbcomputing.com",
"company": "Associated Locks Ltd",
"active": "1",
"operative": "0",
"superAdmin": "1",
"action": "

",
"action2": "<div style="float:right"><i class="fas fa-edit"></i></div>"

As you can see the last column is not return like it's previous column

A: OK. I have solved it. I was thinking backwards! The answer is to return the data differently and then reder it. I was making it too complicated!
My ajax call (Laravel using Yarja) is now
 public function AllUsersData(Request $request)
    {
       $us = DB::table('users')
            ->join('clients','users.client_id','=','clients.id')
            ->select('users.id as id','users.name as name','users.email as email','clients.companyName as company','users.active','users.operative','users.superAdmin')
            ->get();
       return Datatables::of($us)
       /*->addColumn('action', function($pubs){
             $btn = '

';
             return $btn;
        })
       ->addColumn('action2',function($pubs){
            $editBtn = '

';
            return $editBtn;
       })*/
        ->make(true);

    }

I got the name of the two URLs for edit and show with:
$editR = url('admin/allUsers.edit');
$showR = url('admin/allUsers.show');

I had to add the admin to the route name and my view now has the two additional columns defined with the parameters as below (in the colDefs):
 {
    "targets": 6,
    "data": "id",
    "render": function ( data, type, row, meta ) {
        return '';
    }
  },
  {
    "targets": 7,
    "data": "id",
    "render": function ( data, type, row, meta ) {
        return '';
    }
  },


text:
Q: Replacing tag without losing inner tags in JavaScript Let suppose I have this HTML code :

robots

wrong

hi

bye

i want to replace ol by ul without losing the inner tags (li)and thier content
i tried that:
        const actual = document.getElementById('actual');
        const ulReplace = document.createElement('ul');
        actual.children[0].replaceWith(ulReplace);

but i replace the ol by ul and remove every thing inside it.
also i try to clone the content and re-append it after but also i lose it when removed


text:
Q: Connection refused, Twisted Я новочок в Twisted. Скопировал пример с сайта crossbatio.com:
Код:
from autobahn.twisted.wamp import Application
app = Application()
@app.register('com.example.square')
def square():
    x = 2
    print("square() called with {}".format(x * x))
    return f'This is a test of com.example.square {x * x}'

if __name__ == "__main__":
    app.run("ws://127.0.0.1:9000", "realm1")

Пытаюсь запустить сервис. Он валится с ошибкой:

twisted.internet.error.ConnectionRefusedError: Connection was refused
  by other side: 61: Connection refused.

Если вместо порта 9000 поставить порт 8080, получаю эту же ошибку.
Если убрать порт вообще и оставить строку:
app.run("ws://127.0.0.1", "realm1")

Получаю вот такие сообщения:

2018-04-22T11:48:13+0300 failing WebSocket opening handshake
  ('WebSocket connection upgrade failed (200 - OK)')
  2018-04-22T11:48:13+0300 dropping connection to peer tcp4:127.0.0.1:80
  with abort=True: WebSocket connection upgrade failed (200 - OK)

Насколько понимаю, сервис стартовал с ошибкой (могу и ошибиться).
Собственно, вопрос вот какой. Как стартовать сервис по заданному порту?
Может быть кто-то уже сталкивался с подобной проблемой? Подкажите, как решить, пожалуйста.
Работаю в PyCharm, Python 3.6.1


text:
Q: Show that $Z^n$ for a nonnengative integer $n$ is normal family Show that the function $z^n$ for a nonnegative integer $n$ form a normal family in $|z|<1$ ,also in $|z|>1$ but not in the region that contains a point on the unit circle.
I am working on this problem from Complex Analysis by Lars Ahlfors and I need help.
This is what I am thinking, And it's a bit vague. Since the family $Z^n, n\geq 1$ converges for all $z$ within the unit circle, Any subsequence of $z^n$ converges. on the other hand, considering $|z|>1$ I don't know how to approach it.
Any assistance will be appreciated.
Thank you

A:
A family $\mathcal{F}$ of holomorphic functions on a region $\Omega$ is normal if and only if $\mathcal{F}$ is uniformly bounded on compact subsets.

In your case $z^n$ is uniformly bounded in the unit disc, and in $|z|>1$ every sequence contains a subsequence which tends uniformly to $\infty$. We also consider this latter case normal. See Ahlfors Definition 3:

A family of analytic functions is normal if every sequence contains a subsequence converging on compact subsets or a subsequence that tends to $\infty$ uniformly

Can you see what happens when $|z|=1$?


text:
Q: mysql reference aggregate table column name without alias I did
create table tmp select min(xxx_id) from xxx group by y having count(*)>1;

now I need to join this tmp table with another table, but how do I reference the only column in side the tmp table?

select * from table2 s, tmp t where s.xxx_id=t.xxx_id?

clearly won't work, what should be replacing t.xxx_id?

A: You need to enclose that column in quotes as:
select * from table2 s, tmp t where s.xxx_id = t.`min(xxx_id)`;

but it's always better to give alias to columns as it's not confusing:
create table tmp select min(xxx_id) AS min_xxx_id from xxx group by y having count(*)>1;

A: try this:
select *
from table2 s join tmp t
on s.xxx_id=t.xxx_id


text:
Q: What is the Emacs keyboard shortcut for the Agda  symbol? I mean the list symbol in case it does not show up well in the title.
It is not \bl like the book says.

A: The book provides the code to make typing easier in the "Some Extra Emacs Definitions" addendum:
(eval-after-load "quail/latin-ltx"
   '(mapc (lambda (pair)
            (quail-defrule (car pair) (cadr pair) "TeX"))
           '( ("\\bb" "") ("\\bl" "") ("\\bs" "") ("\\bt" "") ("\\bv" "") ("\\cv" "⋎") ("\\comp" "○") ("\\m" "↦") ("\\om" "ω"))))

You just need to copy it from here and paste it into your .emacs file.

A: It's not part of the emacs mode yet but I have submitted a Pull Request to add the missing blackboard bold letters.

A: Use M-x then agda-input-show-translations get a table of all the character bindings. Then you can use C-s to search for a specific character.

A: In my case I just typed in Emacs
\bL

, which gives me the blackboard bold font correctly. This is with agda 2.5.3 (installed via hackage per official documentation under Ubuntu 16.04)


text:
Q: Fatal signal 11 (SIGSEGV) at 0x00000014 (code=1), thread 15566 I am trying to add buddy in CSipSimple by the following code .
public int addBuddy(String buddyUri) throws SameThreadException {
        created = true ;
        if (!created) {
            return -1;
        }
        int[] p_buddy_id = new int[1];
        pjsua.start();

        pjsua_buddy_config buddy_cfg = new pjsua_buddy_config();
        pjsua.buddy_config_default(buddy_cfg);
        buddy_cfg.setSubscribe(1);
        buddy_cfg.setUri(pjsua.pj_str_copy(buddyUri));
        pjsua.buddy_add(buddy_cfg, p_buddy_id);
        System.out.println("Buddy Id is  "+p_buddy_id[0]);
        return p_buddy_id[0];
    }

When the app enters into the following line
    pjsua.buddy_add(buddy_cfg, p_buddy_id);

I am getting the following error and the app crashes .
03-27 12:12:42.007  15566-15566/com.csipsimple A/libc﹕ Fatal signal 11 (SIGSEGV) at 0x00000014 (code=1), thread 15566 (com.csipsimple)

How can I solve this error ? Any advice is of great help .


text:
Q: What does the arxiv.org anti-bot "search and destroy" actually do? The lanl.arxiv.org math and scientific preprint service (formerly known as xxx.lanl.gov) has a strict policy against bots that ignore its robots.txt, Robots Beware. On that page, the have a link labelled with "Click here to initiate automated 'seek-and-destroy' against your site", which is forbidden by their robots.txt but presumably badly behaved robots will follow it, and reap the consequences. The question, what are the actual consequences? I have never had the guts to actually click on that link to see what it does. What can they be doing that is both effective and legal?

A:
[reverse DNS result]: you've been identified as a robot operating in violation of the guidelines posted at arxiv.org.
If this determination is in error, please report to www-admin@arxiv.org so your problem can be investigated.

Scanning, Initialized:

10 minutes to Trinity...
9 minutes to Trinity...
8 minutes to Trinity...
7 minutes to Trinity...
6 minutes to Trinity...
5 minutes to Trinity...
4 minutes to Trinity...
3 minutes to Trinity...
2 minutes to Trinity...
1 minute to Trinity...

Ground zero. Have a nice day.
Contact

So... it's a page that would waste 10 minutes of a very naive bot's time. Probably useless for combating malicious bots, but might save some bandwidth when faced with a badly-written site-scraper.

A: No consequences other than spinning for a bit. Most browsers (and probably their server) will just timeout after a bit. They probably just cause more harm to themselves with this than the bots.


text:
Q: Jquery drag fires on mousemove but not on mousedown So I'm using Jquery-ui's "draggable", and noticed something; the drag event only fires on mousemove. Now for the app I'm building, I need it to fire on mousedown as well as mousemove. To demonstrate what I mean, take a look at this example from Jquery-ui's website. The elements snap to a certain position relative to the mouse - but only when you've moved the mouse. I understand that this is not default behavior, but I need to simulate it. Let me explain my situation here;
I have a box with a circle in it. The user can drag the circle around the box, but the circle snaps to the cursor when the user mousedowns somewhere else in the box. Now, I have this:
    $('#big-box').mousedown(function(event){
        $('#tiny-circle').trigger(event);
    });

this makes sure the drag event is fired when the user mousedowns and mousemoves somewhere else in the box, but when the user clicks somewhere in the box, not on the circle, I need that circle to snap to the cursor. How do I go about doing this in a clean way? To illustrate what I mean; Google's colorpicker shows my point exactly. You drag the circle around, but the circle snaps to the cursor when the user only clicks.

A: Okay so after some experimenting I think this is as close I can get to a clean solution to the problem:
    $('#big-box').mousedown(function(event){
        $('#tiny-circle').css({left:event.offsetX,top:event.offsetY});
        $('#tiny-circle').trigger(event);
    });

and this works as intended.


text:
Q: How to prevent an electrical motor surge from repeatedly blowing the fuse when it stalls? So, this is something that I shouldn't need to do, but I do. As far as I understand, it should be trivial, bit I'm hazy on the details.
I have a 2kW mains AC power tool with a rotary output. Its reliable, works well, does its job.
Unfortunately it seems to have skipped some kind of surge suppression or energy dump in the electrics, because if the rotary spindle jams in the material it's working on,it blows the mains fuse in the plug. Then I have to stop using it, hunt down a spare 13A cartridge fuse (UK mains style), replace, and continue.
It happens pretty easily, its usual use makes it that way, and I consider the tool safe but poorly designed from that point of view - other rotary tools I own don't blow fuses if they briefly jam.
In an ideal world, I'd switch to a competing model but there isn't an affordable competing model for this specific tool, and the tool itself is quite usable. It just runs through 13A fuses at a rate of 5-10 a day on a busy day.
Now, I routinely strip down, repair, and at times fix and update my equipment. I build my own electrical items. It occurs to me that adding some kind of appropriate surge handling inline between tool and mains plug, would be a tiny item, maybe 2-3 components, to handle it better. I'd trust myself to do this safely,  and robustly, but I have no idea of a suitable design.
What would I need to do, so that the transient surge from a jammed output spindle abruptly and temporarily stopping the motor, wouldn't blow the fuse, but current draw from other fault conditions would still blow it, so that it would still perform its safety function correctly?

A: forget using the terms transient surge, energy dump, surge suppression etc, the problem you describe is a simple motor overload.
The obvious solution is to avoid stalling the motor. A thermal circuit breaker or a class D rated thermal/magnetic circuit breaker might be a possible solution.
A mechanical solution would be a torque limiting clutch.
You've been eager to suggest it is trivial and can be fixed with 2,3 components but not given us the critical piece of information - what sort of power tool is it? And, if it is a common problem encountered with this type of tool, surely there is a common solution for it?

A: The obvious solution would be to use a resettable circuit breaker that trips at a lower current than that which blows the fuse.


text:
Q: rails has_many in show just displays table name I have the following has_many association.
class Indicator < ApplicationRecord
  belongs_to :statement, required: false
  belongs_to :identity, required: false
  belongs_to :phase, required: false
end

class Statement < ApplicationRecord
  belongs_to :student, required: false
  has_many :indicators
  has_many :identities, through: :indicators
  accepts_nested_attributes_for :identities
end

class Identity < ApplicationRecord
  has_many :indicators
  has_many :statements, through: :indicators
  accepts_nested_attributes_for :statements
  has_many :phases
end

class Phase < ApplicationRecord
  has_many :indicators
  belongs_to :identity, required: false
end

I'm looking to call the results in the statement show.html.erb. The <%= l.phases.name %> portion of the below code displays 'Phase', which is the table name and not the value of name.

 Description
 Phase
 <% @statement.identities.each do |l| %>

    <%= l.description %>
    <%= l.phases.name %>

  <% end %>

This is how the indicator table is setup:
| id | statement_id | identity_id | phase_id |
| 1  |      2       |      1      |    3     |
| 2  |      2       |      2      |    2     |
| 3  |      3       |      1      |    1     |
| 4  |      3       |      2      |    1     |

A: Since it has many phases you should display the name of each phase with a loop.
<% l.phases.each do |p| %>
<%= p.name %>
<% end %>

A: Your associations are incorrect. Since Identity has_many :phases and Phase belongs_to :identity, there is no reason to specify a through option. You would then do
<% @statement.identities.each do |l| %>

    <%= l.description %>
    <%= l.phases.pluck(:name) %>

  <% end %>

to retrieve the name of each of the phases for a particular instance of Identity.


text:
Q: How to plot data from multiple variables inside a single netCDF file with python I'm new to handling netCDF data with Python (and a programming beginner) so sorry if I'm unclear.
I have a nc file that contains several variables and I need to access the value of each variable for the same pixel and plot.
These are the variables inside my nc file:
odict_keys(['lon', 'lat', 'l2_flags', 'spm_nechad', 't_nechad', 't_dogliotti', 'chl_oc3', 'chl_re_gons740', 'chl_re_moses3b740', 'chl_re_mishra', 'Rrs_443', 'Rrs_492', 'Rrs_560', 'Rrs_665', 'Rrs_704', 'Rrs_740', 'Rrs_783', 'Rrs_833', 'Rrs_865', 'Rrs_1614', 'Rrs_2202', 'rhow_443', 'rhow_492', 'rhow_560', 'rhow_665', 'rhow_704', 'rhow_740', 'rhow_783', 'rhow_833', 'rhow_865', 'rhow_1614', 'rhow_2202'])
Basically what I need to do is to plot a spectra with wavelengths between 443nm and 865nm. Each wavelength is contained inside a variable with the name 'rhow_ (in X I will have the wavelength and in Y the corresponding reflectance value) for a single pixel. However, each value is stored in a different variable (rhow_<wavelength) and I need to extract the values corresponding on the same pixel from each variable.
This is what I've been trying so far:
fn = 'mypath/file.nc'
ds = nc.Dataset(fn)

print(ds.variables.keys())
wavelenghts = [443, 492, 560, 665, 704, 740, 783, 865]

lons = ds.variables['lon'][:]
lats = ds.variables['lat'][:]
rhow_443 = ds.variables['rhow_443'][-8.929999, 38.486744]
rhow_492 = ds.variables['rhow_492'][-8.929999, 38.486744]
rhow_560 = ds.variables['rhow_560'][-8.929999, 38.486744]  #coordinates of AS_7
rhow_665 = ds.variables['rhow_665'][-8.929999, 38.486744]
rhow_705 = ds.variables['rhow_704'][-8.929999, 38.486744]
rhow_740 = ds.variables['rhow_740'][-8.929999, 38.486744]
rhow_783 = ds.variables['rhow_783'][-8.929999, 38.486744]
rhow_865 = ds.variables['rhow_865'][-8.929999, 38.486744]

How can I plot the values to produce a spectra?
I hope I made my self clear. Cheers!

A: You can probably do this with my package ncplot (install using pip). This should work:
import ncplot

ncplot.view("mypath/file.nc")

This will generate an interactive plot for all variables in your file, so long as the netcdf file is close to cf compliant.


text:
Q: Deserialize XML to List failing with XmlArray, XmlElement, and XmlArrayItem I've got an object that is large, and contains several other objects.  The entire thing is deserialized from an XML file.
Everything in the deserialization is working correctly except for the following:
[XmlTypeAttribute("ClientInformation")]
public class ClientInfo
{
    public ClientInfo()
    {
        ClientName = "testclient";
        ClientDisplayFullName = "testclient";
        ClientDisplayShortName = "testclient";
        ContentClientName = "";
        ContentHeirarchy = new List<string>();
    }

    /// <summary>
    /// The "ShortName" for this client (URL Friendly)
    /// </summary>
    public string ClientName { get; set; }

    /// <summary>
    /// This is used to determine what content path to use for content.
    /// normally the same as the ClientName.
    /// </summary>
    public string ContentClientName { get; set; }

    public List<string> ContentHierarchy { get; set; }

    public string ClientDisplayFullName { get; set; }

    public string ClientDisplayShortName { get; set; }

}

The problem resides with 'ContentHierarchy'.  The relevant section of the XML is as follows:
<ClientInformation>
    <ClientName>ABC</ClientName>
    <ContentClientName>ABC</ContentClientName>
    <ClientDisplayFullName>ABC&D</ClientDisplayFullName>
    <ClientDisplayShortName>ABC&D</ClientDisplayShortName>
    <ContentHierarchy>
        <Content>XYZB</Content>
        <Content>Base</Content>
    </ContentHierarchy>
</ClientInformation>

All of the non-list parts of this object deserialize correctly.
I'm trying to figure out what I need to use above the property declaration of ContentHierarchy to get the deserializer to populate it with the ContentHierarchy\Content items from the XML file.
I have tried using XmlArray(), XmlArray(ContentHierarchy), XmlElement(Content), XmlElement(ContentHierarchy), XmlArrayItem(Content), and various combinations of the above.
Each time, the List<string> has a Count of 0.
What am I doing wrong?

A: Try to put the attribute [System.Xml.Serialization.XmlArrayItemAttribute("Content", IsNullable = false)] above the ContentHierarchy property. In the class constructor the property name is ContentHeirarchy, check if you property has the name ContentHeirarchy (wrong) or ContentHierarchy (right) too.
My full code:
    [XmlTypeAttribute("ClientInformation")]
public class ClientInfo
{
    public ClientInfo()
    {
        ClientName = "testclient";
        ClientDisplayFullName = "testclient";
        ClientDisplayShortName = "testclient";
        ContentClientName = "";
        ContentHierarchy = new List<string>();
    }

    /// <summary>
    /// The "ShortName" for this client (URL Friendly)
    /// </summary>
    public string ClientName { get; set; }

    /// <summary>
    /// This is used to determine what content path to use for content.
    /// normally the same as the ClientName.
    /// </summary>
    public string ContentClientName { get; set; }

    [System.Xml.Serialization.XmlArrayItemAttribute("Content", IsNullable = false)]
    public List<string> ContentHierarchy { get; set; }

    public string ClientDisplayFullName { get; set; }

    public string ClientDisplayShortName { get; set; }

}

class Program
{
    static void Main(string[] args)
    {
        string xml = "<ClientInformation>    <ClientName>ABC</ClientName>    <ContentClientName>ABC</ContentClientName>    <ClientDisplayFullName>ABC&D</ClientDisplayFullName>    <ClientDisplayShortName>ABC&D</ClientDisplayShortName>    <ContentHierarchy>        <Content>XYZB</Content>        <Content>Base</Content>    </ContentHierarchy></ClientInformation>";
        var xmlSerializer = new XmlSerializer(typeof(ClientInfo));
        var a = xmlSerializer.Deserialize(new MemoryStream(UTF8Encoding.Default.GetBytes(xml)));
    }

}


text:
Q: connectOnFrameAvailable() provides TangoImageBuffer with curious format infos Also trying to get access to color data bytes from color cam of Tango, I was stuck on java API by being able to connect tango Cam to a surface for display (but just OK for display in fact, no easy access to raw data, nor time stamp)... so finally I switch using C API on native code (latest FERMAT lib and header) and follow recommendation I found on stack Overflow by registering a derivated sample code to connectOnFrameAvailable()...  (I start using PointCloudActivity sample for that test).

*

*First problem I found is somewhat a side effect of registering to that callback, that works usually fine (callbacks gets fire regularly), but then another callback that I also registered, to get xyz clouds, start to fail to fire. Like in sample code I mentioned, clouds are get through a onXYZijAvailable() callback, that the app registers using     TangoService_connectOnXYZijAvailable(onXYZijAvailable).

So failing to get xyz callback fired is not happening always, but usually half of the time, during tests, with a awful workaround that is by taking the app in background then foreground again ... this is curious, is this "recover" related to On-pause/On-resume low level stuff??). If someone has clues ....
By the way in Java API, same side effect was observed, once connecting cam texture for display (through Tango adequate API ...)
But here is my second "problem", back to acquiring YV12 color data from camera :
through registering to TangoService_connectOnFrameAvailable( TangoCameraId::TANGO_CAMERA_COLOR, nullptr, onFrameAvailable)
and providing static funtion onFrameAvailable defined like this :
static void onFrameAvailable(void* ctx, TangoCameraId id, const TangoImageBuffer* buffer)
{
   ...
   LOGI("OnFrameAvailable(): Cam frame data received");
   // Check if data format of expected type : YV12 , i.e.
   // TangoImageFormatType::TANGO_HAL_PIXEL_FORMAT_YV12
   //  i.e.  = 0x32315659  // YCrCb 4:2:0 Planar
   //LOGI("OnFrameAvailable(): Frame data format (%x)", buffer->format);
   ....
}

the problem is that width, height, stride information of received TangoImageBuffer structure seems valid (1280x720, ...), BUT the format returned is changing every-time, and not the expected magic number (here 0x32315659) ...
I am doing something wrong there ? (but other info are OK ...)
Also, there is apparently only one data format defined (YV12 ) here, but seeing Fish Eye images from demo app, it seems grey level image, is it using same (color) format as low level capture than the RGB cam ???

A: 1)  Regarding the image from the camera, I came to the same conclusion you did - only availability of image data is through the C API
2) Regarding the image - I haven't had any issues with YUV, and my last encounter with this stuff was when I wrote JPEG stuff - the format is naked, i.e. it's an organizational structure and has no header information save the undefined metadata in the first line of pixels mentioned here -  Here's a link to some code that may help you decode the image in a response to another message  here
3) Regarding point cloud returns -
Please note this information is anecdotal, and to some degree the product of superstition - what works for me only does that sometimes, and may not work at all for you

*

*Tango does seem to have a remarkable knack to simply stop producing point clouds.  I think a lot of it has to do with very sensitive timing internally (I wonder if anyone mentioned that Linux ain't an RTOS when this was first crafted)

*Almost all issues I encounter can be attributed to screwing up the timing where

*A. Debugging the C level can may point clouds stop coming

*B. Bugs in the native or java code that cause hiccups in the threads that are handling the callbacks can cause point clouds to stop coming

*C. Excessive load can cause the system to loose sync, at which point the point clouds will stop coming - this is detectable, you will start to see a silvery grid pattern appear in rectangular areas of the image, and point clouds will cease. Rarely, the system will recover if load decreases, the silvery pattern goes away, and point clouds come back - more commonly the silvery pattern (I think its the 3d spatializing grid) grows to cover more of the image - at least a restart of the app is required for me, and a full tablet reboot every 3rd time or so

Summarizing, that's my suspicions and countermeasures, but it's based completely on personal experience -


text:
Q: Как проверить открыты ли вкладка tabpage1, winforms? У меня есть несколько вкладок tabControl, и надобность проверить какая вкладка открыта, что бы изменять значение свойства формы AutoScroll = true (если taBage1) в иных случаях AutoScroll = false.

A: Используйте SelectedTab или SelectedIndex.


text:
Q: Autoplay GIFs when on screen and stop on scrolling How to autoplay Gifs when they apper on screen and stop on scroll away in my React web application. Help me!
I have tried this.
<GifPlayer
 gif={url}
 pauseRef={pause => this.pauseGif = pause}/>

This is not working as on clicking on the gif I have to navigate to another screen. So if there is a way that the Gif plays automatically when it appears on the screen and stops on scrolling away then it would work smoothly.


text:
Q: PowerBI - Pandas isnull().sum() index I'm running the following Python script in PowerBI
# 'dataset' holds the input data for this script
import pandas as pd
import numpy as np

df=pd.DataFrame(np.sum(dataset.isnull(), axis=0),columns=['Null_Values'])
df['Items']=dataset.isnull().index

A few notes:

*

*simple dataset.isnull().sum() does not work as the output is not a DataFrame so is not visible as a table in PowerBI

*If I remove the last line from the snippet above, it works fine but the resulting table in PowerBI is just as follows:
Null Values
0
0
5
0
4
So you can only guess which column the 5 and 4 refer to. Outside Power BI, dataset.isnull().sum() would normally produce
            Null Values
Column A      0
Coulmn B      0
Column C      5
Column D      6

If I include the last line of the code snippet, I get an error that
ValueError: Length of values does not match length of index
I just want to add one more column to describe original column names (Column A, B, C, etc.)
Original dataset:
Department,OfficeCode,Sales,Target,Staffing,Dotation
South,23,80,100,0.8,10
South,24,67,100,0.78,15
North,33,111,120,0.98,10
South,25,87,100,,15
West,43,45,50,0.98,10
East,53,65,80,0.89,15
North,34,110,120,,10
North,35,112,120,0.96,15
North,36,,120,0.94,10
North,37,98,120,0.85,15
South,26,77,100,0.7,10
East,54,64,80,0.8,15
East,55,,80,,11
West,44,44,50,,14
East,56,,80,0.79,15
West,44,,50,0.9,16
West,45,34,50,0.89,13
South,27,,100,,14

EDIT: OK, I've solved it by changing the last line from:
df['Items']=dataset.isnull().index

to
df['Items']=df.index

What it did was to duplicate the index column so it can be seen in the PowerBi Query Editor table.
Perhaps, a follow up question would be how to make PowerBi treat the index column as any other column and display it?


text:
Q: PHP ANDROID JSON strange error I'm calling this file from an Android application which is as follows but the application  crashes :
Here's the code:
    <?php
include("connection.php");
$src=$_POST['src'];
$dir=$_POST['tab'];
if($dir=="up")
    $tab="TRAINS";
else
    $tab="TRAIN";
$sql = "SELECT * FROM ".$tab." WHERE STATIONS LIKE '%".$src."%'";

//mysql_select_db($mysql_database);
$result = mysql_query($sql)
or die(mysql_error());
$json = array();
while($row = mysql_fetch_array( $result ))
{

    $bus = array(
        'id' => $row['_id'],
        'trainname' => $row['TRAINNAME'],
        'stations' => $row['STATIONS'],
        'arrival'=>$row['ARRIVAL']
    );
    array_push($json, $bus);
}

$jsonstring = json_encode($json);
echo $jsonstring;
//mysql_close($conn);
?>

Logcat file :
    04-28 11:02:29.504: E/AndroidRuntime(8748): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mobisys.android.External_to_application/com.mobisys.android.External_to_application.ListTrainsFromSrc}: java.lang.NullPointerException
04-28 11:02:29.504: E/AndroidRuntime(8748):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1728)
04-28 11:02:29.504: E/AndroidRuntime(8748):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1747)
04-28 11:02:29.504: E/AndroidRuntime(8748):     at android.app.ActivityThread.access$1500(ActivityThread.java:155)
04-28 11:02:29.504: E/AndroidRuntime(8748):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:993)
04-28 11:02:29.504: E/AndroidRuntime(8748):     at android.os.Handler.dispatchMessage(Handler.java:130)
04-28 11:02:29.504: E/AndroidRuntime(8748):     at android.os.Looper.loop(SourceFile:351)
04-28 11:02:29.504: E/AndroidRuntime(8748):     at android.app.ActivityThread.main(ActivityThread.java:3814)
04-28 11:02:29.504: E/AndroidRuntime(8748):     at java.lang.reflect.Method.invokeNative(Native Method)
04-28 11:02:29.504: E/AndroidRuntime(8748):     at java.lang.reflect.Method.invoke(Method.java:538)
04-28 11:02:29.504: E/AndroidRuntime(8748):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
04-28 11:02:29.504: E/AndroidRuntime(8748):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:659)
04-28 11:02:29.504: E/AndroidRuntime(8748):     at dalvik.system.NativeStart.main(Native Method)
04-28 11:02:29.504: E/AndroidRuntime(8748): Caused by: java.lang.NullPointerException
04-28 11:02:29.504: E/AndroidRuntime(8748):     at com.mobisys.android.External_to_application.ListTrainsFromSrc.onCreate(ListTrainsFromSrc.java:71)
04-28 11:02:29.504: E/AndroidRuntime(8748):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1082)
04-28 11:02:29.504: E/AndroidRuntime(8748):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1692)
04-28 11:02:29.504: E/AndroidRuntime(8748):     ... 11 more

The class from which the php file is called:
ListTrainsFrmSrc.java
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

//import com.mobisys.android.External_to_application.R;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.os.Bundle;
import android.text.format.Time;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class ListTrainsFromSrc extends Activity{
String res=null;
private static final String TAG_ID = "id";
private static final String TAG_TRAINNAME = "trainname";
private static final String TAG_STATIONS = "stations";
private static final String TAG_ARRIVAL = "arrival";
ArrayList<String> indexes=null;
ArrayList<String> Tables=null;
//String res=null;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.setContentView(R.layout.single_list_item_view);
    String[] tabdata=null;
    Time dtNow = new Time();
    dtNow.setToNow();
    int hours = dtNow.hour;
    int minutes = dtNow.minute;
    int time=hours*100+minutes;
    ArrayList<String> indexes=new ArrayList<String>();
    ArrayList<String> Tables = new ArrayList<String>();
    Intent i = getIntent();
    // getting attached intent data
    String product = i.getStringExtra("Station");
    String dir=i.getStringExtra("Dir");
    String url="http://hotelmanagement.hostoi.com/dinesh/onlysrc.php";
    List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
    nameValuePair.add(new BasicNameValuePair("src", product));
    nameValuePair.add(new BasicNameValuePair("tab",dir));

    JSONParser jParser = new JSONParser();

    // getting JSON string from URL
    final JSONArray json = jParser.getJSONFromUrl(url,nameValuePair);
    try{
    for(int p = 0; p < json.length(); p++){
        JSONObject jobj = json.getJSONObject(p);

        // Storing each json item in variable
        String id = jobj.getString(TAG_ID);
        String name = jobj.getString(TAG_TRAINNAME);
        String stations = jobj.getString(TAG_STATIONS);
        String arr = jobj.getString(TAG_ARRIVAL);

        String stn[]=stations.split(",");
        String arrt[]=arr.split(",");
        for(int j=0;j<stn.length;j++)
            {
                    if(stn[j].equals(product) && stn.length==arrt.length){
                        int start_time=Integer.parseInt(arrt[j]);
                        if(start_time>time){
                            indexes.add(id);
                            Tables.add(arrt[j]+"\t"+name);
                        }

                    break;
                }
            }
        }

        tabdata=Tables.toArray(new String[Tables.size()]);
        final int[] a = new int[indexes.size()];
        int l = 0;

        for (String integer : indexes)
            a[l++] = Integer.parseInt(integer);
        ListView listView1 = (ListView) findViewById(R.id.listView1);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, tabdata);
        listView1.setAdapter(adapter);

       listView1.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                    Intent i = new Intent(getApplicationContext(), ListTrainDetails.class);
                    i.putExtra("trainID",a[position]);
                    i.putExtra("json",json.toString());

                    startActivity(i);
                }
              });

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

JSONParser.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

    static InputStream is = null;
    static JSONArray jArray = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    public JSONArray getJSONFromUrl(String url,List<NameValuePair> nvp) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(nvp));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jArray = new JSONArray(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jArray;

    }
}

A: In PHP you concatenate strings with the dot (.) operator, not with the + operator
so this line:
$sql = "SELECT * FROM "+$tab+" WHERE STATIONS LIKE '%"+src+"%"+$dest+"%'" ;
should be like:
$sql = "SELECT * FROM ".$tab." WHERE STATIONS LIKE '%".src."%".$dest."%'" ;
Also, your code is vulnerable to SQL Injection.
Try to stay away from mysql_ functions, and use PDO or at least mysqli

A: In PHP, . is used to concatenate strings, not +. Using + adds them as numbers, and in this case the result is 0. Therefore you are effectively running mysql_query("0"), which of course won't work.

A: String Concatenation in PHP is done with a . not a +.
$sql = "SELECT * FROM ".$tab." WHERE STATIONS LIKE '%".src."%".$dest."%'" ;

A: In php , you use concat a string as . (dot) operator , not (+ operator)
Change
$sql = "SELECT * FROM "+$tab+" WHERE STATIONS LIKE '%"+src+"%"+$dest+"%'" ;

to
$sql = "SELECT * FROM ".$tab." WHERE STATIONS LIKE '%".$src."%".$dest."%'" ;

A: Try this
$sql = "SELECT * FROM ".$tab." WHERE STATIONS LIKE '".src."%".$dest."%'" ;


text:
Q: cut a video file into many images and combine it in Android I just started to study android so I barely know android library.
Would you introduce some library so I can figure out the problem?
The reason I'm trying it is that there is no available parameter to manage shutter speed.
I would like to exposure image sensor a long time but I found it's not supported by firmware.
So I planned to record a video and cut it. Then, combine it together so it would be like long shutter speed picture.
Thank you for reading

A: I don't really understand what you're trying to do.
How capturing multiple frames will allow you to simulate different shutter speed.
Assuming you know what you're doing, check out this SO.
You can start recording for any time period you want, save all the images to files/memory and then do whatever you want with the frames.


text:
Q: Writing Unicode Characters to an OStream I'm working with unicode/wide characters and I'm trying to create a toString method (Java ::toString equiv). Will ostream handle wide characters, if so is there a way to warn the consumer of the stream that it is unicode coming out of it?

A: Neither ostream nor the rest of C++ know anything about Unicode. Usually you write a string conversion in C++ as follows:
template<typename Char, typename Traits>
std::basic_ostream<Char, Traits>&
operator<<(std::basic_ostream<Char, Traits>& stream, const YourType& object) {
    return stream << object.a << object.b;  // or whatever
}

Whether you get something Unicode-like is up to the implementation. Streams in C++ are never text streams in the sense of Java, and C++'s strings are not strings in the sense of Java. If you want a real Unicode string, you might want to have a look at the ICU library.

A: Wide strings are non-portable and better be avoided in C++. They can be UTF-16, UTF-32 or even non-Unicode depending on platform.
The common approach in C++ is to use UTF-8 encoded multibyte char strings internally and, if necessary, do transcoding at system boundaries. Most modern systems such as Linux and macOS work well with UTF-8 so passing them to an output stream works. Windows is the most problematic because of legacy code pages. You can use Boost Nowide or the {fmt} library for portable UTF-8 output.
Disclaimer: I'm the author of {fmt}.


text:
Q: Call a controller inside a template and another controller in Fatfree framework i'd like to know if i can call a controller action inside a template, and inside another controller in fatFree framework (F3).

A: I'm not sure if i understand you corrently, but calling a Class method in Template would go like this:
{{ MyConroller->doSomething() }}
Of cause you could call one controller within another too... just use raw php

$obj = new MyController();
$obj->foo();

or use the F3 call method $f3->call('MyController->doSomething');
Also check out the new API docs.
http://fatfreeframework.com/base#call
It's still under construction, but hopefully you'll find more information about this or any other framework part very soon.

A: Many MVC purists would balk at the idea of a View (template) calling methods on the Controller. They would say that the controller needs to provide the data that the view needs, or at least give it the Model, so that it can retrieve data from there.
Furthermore, the View probably shouldn't be doing anything (or asking another component to do anything), other than generating the display. But can query the Model for data. But maybe by doSomething() you do mean getSomeData().
While I'm not an MVC purist I do agree with the idea of keeping logic and functionality out of the view if at all possible.


text:
Q: Do Cocoa applications have a main loop? On Linux under X11 and using GTK+ you have something called "Main Loop". Once you start the main loop you have a timer that runs in the main thread of the application. You can set that timer to a callback function and you have a very nice application-wide timer.
This is sample code for that:
GMainLoop *loop;

if(!loop_running)
{
      display = XOpenDisplay( NULL );
      loop = g_main_loop_new(NULL, FALSE);
      g_timeout_add(1000, (GSourceFunc)callback, NULL); //1 sec laps
      g_main_loop_run(loop);  //to stop use g_main_loop_quit ()  with the "loop" as arg
      loop_running=1;
}

I am trying to write a similar application for Mac OS X and instead of a main loop i am using a simple timer:
- (void) handleTimer: (NSTimer *) timer
{
    CopyDataToDB();
} // handleTimer

- (IBAction)startStopAction:(id)sender
{

   isOn=!isOn;
   if(isOn)
   {
       // Add our timers to the EventTracking loop
       [[NSRunLoop currentRunLoop] addTimer: time forMode: NSEventTrackingRunLoopMode];

       // Add our timers to the ModelPanel loop
       [[NSRunLoop currentRunLoop] addTimer: time forMode: NSModalPanelRunLoopMode];
   }
   else
   {
       [timer invalidate];
   }

}

That doesn't seem to work very well. The timer is set off all the time. I tried also with an NSTimer but no luck.
I'm not very familiar with objective-c and specially with GUI applications.
Anyway, any ideas how to implement an application-wide timer on Cocoa (objective-c with Xcode)?
Thanks!
EDIT
When using NSTimer this is the error I'm getting at runtime:
**[Session started at 2009-07-12 16:49:59 -0400.]
2009-07-12 16:50:02.784 MouseClick[1490:10b] Starting
2009-07-12 16:50:02.786 MouseClick[1490:10b] *** +[NSTimer scheduledTimerWithTimeInterval:selector:userInfo:repeats:]: unrecognized selector sent to class 0xa08d54c0
2009-07-12 16:50:02.787 MouseClick[1490:10b] *** +[NSTimer scheduledTimerWithTimeInterval:selector:userInfo:repeats:]: unrecognized selector sent to class 0xa08d54c0**

The Debugger has exited with status 0.

EDIT 2
ok, i got it. The problem was that i didn't add a "target:" to the timer. now, when I'm shutting the timer off I am getting the following error:
MouseClick(1652) malloc: * error for object 0x1645c0: double free * set a breakpoint in malloc_error_break to debug

The freeing of the timer is done as follow:
[timer invalidate];
[timer release];
timer = nil;

A: Depends on what exactly you are trying to do. Most of the time you should not mess with the run loop and simply set up a timer:
const float framerate = 40;
const float frequency = 1.0f/framerate;
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:frequency
    target:self selector:@selector(doSomething)
    userInfo:nil repeats:YES];

Now the doSomething method is going to get executed about 40 times per second. If you want to execute something as often as possible, you can spawn a new thread:
- (void) loop
{
    while (running)
    {
        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
        // Do something useful.
        [pool release];
    }
}

- (void) run
{
    run = YES;
    [NSThread detachNewThreadSelector:@selector(loop)
        toTarget:self withObject:nil];
}

Of course now you have threads, which means synchronizations and more headache than you would have with timers. As I said, it depends on what you want to do.
And to answer your original question: Yes, Cocoa applications do have a "main loop" that's probably similar to the GTK one. As the loop is already created for you, there is no point in writing another one – unless you are trying to figure out how things work or do something sophisticated. See Run Loop Management in Threading Programming Guide for details.
If you want to simply handle events, the default run loop will do it for you. Just implement the handlers, ie. methods connected to buttons and such stuff. If you want to do something periodically (like update an animation or so), set up a timer (NSTimer). The default run loop will take care of the time and it will call the appropriate selector as often as you want to.

A: A timer can be set up with any object as its target; and there are a number of suitable entry points for "attaching" a timer to the the desired target.
I'm not quite sure where you get time from in this context; but I'm guessing it's a timer created with +timerWithTimeInterval:invocation:repeats: (on NSTimer) perhaps? If not, that particular method should hand you a very useful timer for your use.

A: When trying NSTimer, did you retain the timer?  What about retaining the object the timer calls as well...


text:
Q: Glassfish 5 not working with Intellij 2017 2.4 I am new to Intellij ide and i'm having issues running Glassfish 5 or any previous version on Intellij 2017 2.4.
After selecting New Project > Java Enterprise > Web Application i had to specify the application server, to which i selected the folder of glassfish 5, jdk is set to 1.8 and java ee to 7. So far so good, no errors and the project gets created. Then i have a greyed "play" icon next to GlassFish 5.0.0 in the upper right of the corner that says that i have to configure it, i click Edit Configurations and the Run/Debug Configurations opens up
Everything seems fine and when i click the "play" green button to start the server and run the project i have projectName:war exploded under Deployment and
[2017-09-26 08:47:57,836] Artifact testfornew:war exploded: Waiting for server connection to start artifact deployment...
Detected server admin port: 4848
Detected server http port: 8080
Exception in thread "main" java.lang.NullPointerException
at com.sun.enterprise.module.common_impl.AbstractModulesRegistryImpl.initializeServiceLocator(AbstractModulesRegistryImpl.java:152)
at com.sun.enterprise.module.common_impl.AbstractModulesRegistryImpl.newServiceLocator(AbstractModulesRegistryImpl.java:144)
at com.sun.enterprise.module.common_impl.AbstractModulesRegistryImpl.createServiceLocator(AbstractModulesRegistryImpl.java:218)
at com.sun.enterprise.module.common_impl.AbstractModulesRegistryImpl.createServiceLocator(AbstractModulesRegistryImpl.java:224)
at com.sun.enterprise.module.single.StaticModulesRegistry.createServiceLocator(StaticModulesRegistry.java:88)
at com.sun.enterprise.admin.cli.CLIContainer.getServiceLocator(CLIContainer.java:217)
at com.sun.enterprise.admin.cli.CLIContainer.getLocalCommand(CLIContainer.java:255)
at com.sun.enterprise.admin.cli.CLICommand.getCommand(CLICommand.java:231)
at com.sun.enterprise.admin.cli.AdminMain.executeCommand(AdminMain.java:371)
at com.sun.enterprise.admin.cli.AdminMain.doMain(AdminMain.java:306)
at org.glassfish.admin.cli.AsadminMain.main(AsadminMain.java:57)

Under output. Coming from Netbeans setting glassfish up was pretty straightforward, i've checked a couple of solutions online including this but they don't seem to work for me.

A: I was having the same problem and I found that it is caused by an issue with the JDK software. So the NullPointerException thrown at AsadminMain.java:57 can be solved by checking your system variables (PATH, JAVA_HOME). Be sure that they reference to an acceptable JDK supported by your GlassFish version. GlassFish 5.0 is certified to work with java sdk 8u144 as mentioned HERE: https://javaee.github.io/glassfish/doc/5.0/release-notes.pdf.
Be aware, the path may also contain a reference to an old SDK directory.
If you need more help, please post the results of calling echo %PATH% on your cmd.

A: In my case JDK 1.8.0_152 must be installed, path and java_home variables have to be configured AND JDK 9.X must be uninstalled. Without uninstall, the error persist.

A: Uninstall Java 9, stay with the version 8 update 162 and the jdk8. When you unistall the Java 9 your system variables (PATH, JAVA_HOME=C:\ProgramData\Oracle\Java\javapath) will update the 3 jar (java, javaw, javaws) in this path to Java version  8.

A: war exploded: Waiting for server connection to start artifact deployment...
Detected server admin port: 4848
Detected server http port: 8080
....
Assuming that you are certain that JDK has set well in your environment variables and you are using jdk 8 or lower-Well I read somewhere that java9 has issues with such configurations, maybe the issue has been solve but for my case I chose to avoid for now.

*

*Download and extract GlassFish of your version. For my case I'm
using GlassFish 5.181.O on Intellij 2018.1 ultimate version

*Start Intellij, and before opening any project, or rather close all projects that are open.

*Click on configure, then settings. A new window will appear as shown below. I have marked the steps you need to follow in the image. I will also add some explanation here.

*Under Application Servers, click on the + shown as step 2 on the image, here you need to specify you glassfish server, the folder where you extracted to.

*Next, click  on  + shown in step 3 on the image to add the server modules.

*Assuming all is a success upto this point, select all choices of as shown in step 4 on the image, apply changes and Ok.

*I will explain about creating a new project because I'm not sure how you would handle an existing project but I guess you can use concepts here to figure out what you need to tweak.Create your new java ee or whatever application you are working on,

*As shown on figure 2, assuming you are creating a Java EE app, Click on Java Enterprise, then check/tick Web Application and JSF

*Under libraries, use library from Glassfish ... Installation didn't help much because I got null pointer exceptions., so I used Download as shown in figure 2. Click next and finish.

*Automatically you will see GlassFish added to the project, run it from the IDE.

Edit
If you had done all of the above and still get some error like Null Pointer Exceptions. Do what @Jailson Evora says: Clear your systems from java 9 and install java 8 and make sure when you issue java -version on command line, the output is java 8

A: I had to uninstall both jdk9 and jdk10 and set my java_home back to jdk8_181