text:
Q: Quick book integration for PHP Website I am a PHP web developer. I have a project with a payment section. My client requested that I integrate this section with QuickBooks. I don't know anything about QuickBooks. Is there a framework for integrating QuickBooks? Also, how do I implement QuickBooks data into a PHP Mysql website? Thanks.

A: Quickbooks is an accounting package. Plenty of people have linked into Quickbooks for custom applications over the years. Implementing it to a web based application will depend on your requirements.
Normally what is necessary is for the user to export the records to a CSV file or a QIF file and then you import it. If not some basic work has been done integrating Quickbooks with PHP which you can use. For example http://www.consolibyte.com/download.php?ID=5. There is also a great stackoverflow question here https://stackoverflow.com/questions/151216/php-quickbooks-integration-api. Like I said it depends on your requirements.


text:
Q: Rails 3.* Devise Facebook OmniAuth intermittently fails with NoMethodError I followed the steps that are described in https://github.com/plataformatec/devise/wiki/OmniAuth:-Overview and have a method in user model like this:
def self.find_for_facebook_oauth(access_token, signed_in_resource=nil)
  data = access_token.extra.raw_info
  if user = self.find_by_email(data.email)
    user
  else # Create a user with a stub password.
    self.create!(:email => data.email, :password => Devise.friendly_token[0,20])
  end
end

I intermittently get errors like
A NoMethodError occurred in omniauth_callbacks#facebook:
undefined method email' for "false":String
app/models/user.rb:138:infind_for_facebook_oauth'
that I haven't been able to reproduce. What is the source of this problem?

A: I am not sure what causes this either. Here's a work-around that simply creates a new object:
def self.find_for_facebook_oauth(access_token, signed_in_resource=nil)
  data = access_token.extra.raw_info
  if data == "false"
    self.new
  elsif user = self.find_by_email(data.email)
    user
  else # Create a user with a stub password.
    self.create!(:email => data.email, :password => Devise.friendly_token[0,20])
  end
end

The controller code shown in the example will then work - it will redirect the user to sign up.

redpajama_set_name: RedPajamaStackExchange


text:
Q: NUnit Tests in generic abstract base class are ignored I have create a generic abstract base class to do some common tests. The test are showing up, but they are ignored. Why?
Example
public abstract class FooBase<TA, TB> : TestBase<TA, TB>
{
   [Test]
   public void SomeBaseTest(){}
}

[TestFixture]
public class ConcreteFooTest:FooBase<IFoo,MyContext>
{
   [Test]
   public void WorkingTest(){}
}

It this example are SomeBaseTest ignored.
TestBase are used by all my tests and are only containing some help methods, and no tests

A: As Ritch states it is due to RS' test runner. This is a bug in RS 6.0 which is scheduled for fix in 6.1.
See RSRP-273687 Unit test runner shows inconclusive with test class with generic base class.

A: Which test runner are you using?
And have you tried to add the TestFixture attribute?
[TestFixture]
public abstract class FooBase<TA, TB> : TestBase<TA, TB>
{
    [Test]
    public void SomeBaseTest(){}
}

A: The problem is likely with your test runner. Nunit 2.5.10's test runner ran it, Autotest.Net (1.3.1) ran it, and Resharper 6.0's test runner saw it, but wouldn't automatically run it.


text:
Q: React -Server-side-rendering I am using react 16.2.0 and doing SSR.
My web app blink after hydration.
So to find error or mismatch in server rendered HTML and client rendered HTML, I ran the code in development mode.
Now it shows
warning.js?6db0:33 Warning: Did not expect server HTML to contain a <div> in <div>.

I know this error is due to deletion of some div from server rendered HTML to client rendered HTML.
But now, my question is ...how to debug this? there is no reference to element node where it is happening.
One solution is to check the whole page manually.
Is there any other way..more efficient.
How to resolve this warning?


text:
Q: How do I make my GUID visible for a VSTO Add-in I've tried adding the following code to the beginning of my add-in code as such:
Namespace NS
    [Guid("211B3945-E2AE-48DD-8A9A-77ADB40EC6D5")]
    [ComVisible(true)]
    public partial class Classname
    {

but it doesn't appear when I list the COMAddins (the name does, but not the GUID).
I've also tried setting it in my compile settings under Assembly information with no luck.
BTW - the issue I'm trying to resolve is seeing if a COM Addin is loaded by searching for its GUID.  The Addin description shows up when I check the list of ComAddIns, but the GUID still shows zeroes no matter how I follow these directions.  I'm trying to see what's visible by using the following code:
olApp = this.Application;
Office.COMAddIns CAIs = olApp.COMAddIns;
foreach (Office.COMAddIn CAI in CAIs)
{
    StringBuilder sb = new StringBuilder();
    sb.AppendLine(CAI.Description);
    sb.AppendLine(CAI.Guid);
    sb.AppendLine("****");
    Debug.Print(sb.ToString());
}

A: There are a number of things missing here to expose COM, including overriding RequestComAddInAutomationService and setting [InterfaceType(ComInterfaceType.InterfaceIsDual)]
See the following items:

*

*VSTO Add-ins, COMAddIns and RequestComAddInAutomationService

*VSTO in VBA: AddIn.Object returns Nothing (null) sometimes


text:
Q: Create Column in sql based on condition? table:
  Student_Id    Roll_No    Date   _Rank
1    101         10101    201905    3
2    101         10101    201910    6
3    101         10101    201912    9
4    101         10102    201905    15
5    101         10102    201910    9
6    101         10102    201912    3
7    103         10103    201905    3
8    103         10103    201910    9
9    103         10103    201912    9
10   103         10104    201905    3
11   103         10104    201910    9
12   103         10104    201912    9

i need to create a result column based on the condition.

*

*check for particular Student_Id,Roll_No if rank is 9 and rank> 9 has not
appeared before 9 as per date then 1 else 0.

*if some Student_Id,Roll_No has multiple 9 then flag only the first occurrence.
Result:
  Student_Id    Roll_No    Date   _Rank   Result
1    101         10101    201905    3       0
2    101         10101    201910    6       0
3    101         10101    201912    9       1
4    101         10102    201905    15      0 ---
5    101         10102    201910    9       0 --- 15 > 9, came before 9 for that Roll_No
6    101         10102    201912    3       0
7    103         10105    201905    9       1
8    103         10103    201910    9       1
9    103         10103    201912    9       0
10   103         10104    201905    3       0
11   103         10104    201910    9       1 --- first occurrence should 1
12   103         10104    201912    9       0

Query:
SELECT Student_Id, Roll_Number, Date, _Rank,
ROW_NUMBER() OVER( PARTITION BY Roll_Number ORDER BY Date) as rw_number
FROM table t
-- this is giving the row_number which is appeared first.

A: You can use window functions:
select
    t.*,
    case
        when _rank = 9 and row_number() over(partition by roll_no, _rank order by date) = 1
        then 1
        else 0
    end result
from mytable t

A: I think you want:
select t.*,
       (case when _rank = 9 and
                  row_number() over (partition by roll_no, _rank order by date) = 1 and
                  max(_rank) over (partition by roll_no order by date) <= 9
             then 1 else 0
        end) as result
from t
order by roll_no, date;

The max(_rank) condition checks that no rank higher than 9 has occurred up to a given row.
Here is a db<>fiddle.


text:
Q: Is there a template hiearachy in Wordpress similar to Django? I'm a veteran Django programmer and a newbie in WordPress. In Django, we have the concept of templating such that I can create File1 which contains some html blocks that can be overriden by child File2. We are using {block block1} syntax in Django. This makes re-use in django very easy. In PHP (WordPress) do we have the same concept? I want to make File1 and override some of its html blocks by File2.

A: I don't know Django at all, but if I'm interpreting your statements correctly then there is no templating construct in that sense.
Wordpress child themes override the entire file from the parent theme using the same file in the child theme.
A way to achieve what you want might be to write a plugin that rewrites the theme output in the areas you're concerned with, The output model for Wordpress allows developers to hook in to events in the page life-cycle and modify the html to be output before it's sent to the browser.

A: Yes! Wordpress have hierarchy for templates/themes too. These are called Child themes.

the functions.php of a child theme
  provides a smart, trouble-free method
  of modifying the functionality of a
  parent theme.

Here is the best tutorial I could find.


text:
Q: making queries in SQL PLUS For this Database:
CREATE TABLE team (
  id    CHAR(3),
  name     VARCHAR2(80) CONSTRAINT nn_team_name     NOT NULL,
  district VARCHAR2(20) CONSTRAINT nn_team_district NOT NULL,

CONSTRAINT pk_team
PRIMARY KEY (id)
);

CREATE TABLE game (
 home,
 away,
 round    NUMBER(2) CONSTRAINT nn_game_round NOT NULL,
 spectators NUMBER(5),
--
 CONSTRAINT pk_game
  PRIMARY KEY (home, away),
--
 CONSTRAINT fk_game_home
    FOREIGN KEY (home)
    REFERENCES team(id),
 CONSTRAINT fk_game_away
    FOREIGN KEY (away)
    REFERENCES team(id),
--
CONSTRAINT ck_game_round
 CHECK (round BETWEEN 1 AND 30),
CONSTRAINT ck_game_spectators
 CHECK (spectators > 0)
);

CREATE TABLE player (
 nickname        NUMBER(8),
 name       VARCHAR2(80) CONSTRAINT nn_player_name      NOT NULL,
 yearOfBirth NUMBER(4)    CONSTRAINT nn_player_yearOfBirth NOT NULL,
 team                  CONSTRAINT nn_player_team    NOT NULL,
--
CONSTRAINT pk_player
  PRIMARY KEY (nickname),
--
CONSTRAINT fk_player_team
  FOREIGN KEY (team)
  REFERENCES team(id),
--
CONSTRAINT ck_player_yearOfBirth
  CHECK (yearOfBirth BETWEEN 1950 AND 2000)
);

CREATE TABLE plays (
  player,
  home,
  away,
  goals      NUMBER(2) CONSTRAINT nn_plays_goals NOT NULL,
--
CONSTRAINT pk_plays
  PRIMARY KEY (player, home, away),
--
CONSTRAINT fk_plays_player
   FOREIGN KEY (player) REFERENCES player(nickname),
CONSTRAINT fk_plays_game
   FOREIGN KEY (home, away) REFERENCES game(home, away),
--
CONSTRAINT ck_plays_goals
   CHECK (goals >= 0)
);

i'm having trouble making the following queries:

*

*names of the players and their teams, who always played away.

here's my attempt at this:
SELECT DISTINCT P1.Name, T.Name
FROM Player P1, Plays P2, Team T, Game G
WHERE P1.team = T.id
  AND P1.nickname = P2.player
  AND P1.team = G.away
  AND P1.team = P2.away;

*

*Average number of goals by round for the players who were born after 1993 and never played at home.

Here's my attempt:
WITH Number_of_Games AS (
  SELECT COUNT(1) AS Number_of_Games, G.Round
  FROM Game G
  GROUP BY G.Round)

SELECT G.Round, SUM(P.goals / N.Number_of_Games) AS Average_goals_per_round
FROM Player P1,Game G INNER JOIN Plays P2 ON (P1.team = P2.away AND G.away = P2.away AND P1.yearofbirth >= '1993')
INNER JOIN Number_of_Games N ON (G.round = n.round)
GROUP BY g.round
ORDER BY g.round;

*

*if i want the id's of the teams with the biggest number of goals against per round , how would i do that ?

HERE'S SOME TESTING DATA:
INSERT INTO TEAM (ID, NAME, DISTRICT) VALUES ('MAN','MANCHESTER UNITED','MANCHESTER');
INSERT INTO TEAM (ID,NAME,DISTRICT) VALUES ('CHE','CHELSEA FC','LONDON');
INSERT INTO PLAYER (NICKNAME,NAME,YEAROFBIRTH,TEAM) VALUES('1','VAN PERSIE','1994','MAN');
INSERT INTO PLAYER (NICKNAME,NAME,YEAROFBIRTH,TEAM) VALUES('2','TERRY','1970','CHE');
INSERT INTO GAME(HOME,AWAY,ROUND,SPECTATORS) VALUES ('MAN','CHE','1','15000');
INSERT INTO GAME(HOME,AWAY,ROUND,SPECTATORS) VALUES ('CHE','MAN','2','30000');
INSERT INTO PLAYS(PLAYER,HOME,AWAY,GOALS) VALUES('1','MAN','CHE','2');
INSERT INTO PLAYS(PLAYER,HOME,AWAY,GOALS) VALUES('2','MAN','CHE','1');
INSERT INTO PLAYS(PLAYER,HOME,AWAY,GOALS) VALUES('1','CHE','MAN','1');

why is this wrong ? Can anybody help ?

A: Query 1

names of the players and their teams, who always played away

This will get the names of the players who never played at home:
SELECT p.name AS player_name,
       t.name AS team_name
FROM   player p
       INNER JOIN
       team t
       ON ( p.team = t.id )
WHERE  NOT EXISTS ( SELECT 1
                    FROM   plays l
                    WHERE  p.nickname = l.player
                    AND    p.team     = l.home )

If you want to enforce that they must have played at least one game then:
SELECT p.name AS player_name,
       t.name AS team_name
FROM   player p
       INNER JOIN
       team t
       ON ( p.team = t.id )
WHERE  NOT EXISTS ( SELECT 1
                    FROM   plays l
                    WHERE  p.nickname = l.player
                    AND    p.team     = l.home )
AND    EXISTS     ( SELECT 1
                    FROM   plays l
                    WHERE  p.nickname = l.player
                    AND    p.team     = l.away -- Although you probably don't need this last line.
                  )

Query 2

Average number of goals by round for the players who were born after 1993 and never played at home.

This should get the mean number of goals in each round when only considering the goals scored by players who were born after 1993 and who have never played at home:
SELECT AVG( y.goals ),
       g.round
FROM   player p
       INNER JOIN
       plays y
       ON ( p.nickname = y.player AND p.team = y.home )
       INNER JOIN
       game g
       ON ( y.home = g.home AND y.away = g.away )
WHERE  NOT EXISTS ( SELECT 1
                    FROM   plays l
                    WHERE  p.nickname = l.player
                    AND    p.team     = l.home )
AND    p.yearOfBirth > 1993
GROUP BY g.round
ORDER BY g.round;

Query 3

if i want the id's of the teams with the biggest number of goals against, how would i do that ?

Can be answered using:
WITH team_goals AS (
  SELECT SUM( l.goals ) AS total_goals,
         p.team,
         CASE WHEN p.team = l.home THEN l.away
              WHEN p.team = l.away THEN l.home
              ELSE NULL
              END AS opposing_team
  FROM   player p
         INNER JOIN
         plays l
         ON (p.nickname = l.player)
  GROUP BY
         p.team,
         CASE WHEN p.team = l.home THEN l.away
              WHEN p.team = l.away THEN l.home
              ELSE NULL
              END
),
goals_against AS (
  SELECT p.team,
         SUM( q.total_goals ) AS total_goals_against
  FROM   team_goals p
         INNER JOIN
         team_goals q
         ON (    p.team = q.opposing_team
             AND p.opposing_team = q.team)
  GROUP BY p.team
)
SELECT *
FROM   goals_against
WHERE  total_goals_against = ( SELECT MAX( total_goals_against )
                               FROM goals_against );

A: NOT EXISTS should help you with the first question:
SELECT DISTINCT P1.Name, T.Name
FROM Player P1 JOIN team T ON p1.team = t.team
WHERE NOT EXISTS
      (SELECT 1
         FROM plays
        WHERE player = p1.name
          AND home = p1.team);

I try to avoid the old style joins in the WHERE clause. Use ANSI 92 join syntax for clarity and expanded functionality.
Now expand this query to include only those players born after 1993:
SELECT P1.Name, T.Name
FROM Player P1 JOIN team T ON p1.team = t.team
WHERE NOT EXISTS
      (SELECT 1
         FROM plays
        WHERE player = p1.name
          AND home = p1.team
          AND year_of_birth <= 1993);

Use this query to find the average:
  SELECT P1.Name, T.Name, g.round, AVG(p2.goals) "Average Goals"
    FROM Player P1 JOIN team T ON p1.team = t.team
                   JOIN plays p2 ON p1.nickname = p2.player
                   JOIN game g ON p2.away = g.away
   WHERE NOT EXISTS
         (SELECT 1
            FROM plays
           WHERE player = p1.name
             AND home = p1.team
             AND year_of_birth <= 1993))
  GROUP BY p1.name, t.name, g.round;

Also, in your games and plays tables, you don't provide a TYPE on your column definitions for some of the columns.
This will get you close. I haven't tested it.


text:
Q: Trying to run a Program called worldforge but it comes up with an error I recently downloaded a program called Worldforge, it is a game maker which is open source. I downloaded its executable file and gave it the permissions to run but when i went to start it it came back with this error:
/tmp/.mount_dskVs4/usr/bin/ember.bin: error while loading shared libraries: librtmp.so.0: cannot open shared object file: No such file or directory

I have tried searching for an answer but the only one I found which was relevant did not work, I would be greatful if anyone could help in any way.

A: It's not trivial to get the librtmp0 package in Xenial, so my first idea is to use librtmp.so.1 from the librtmp1 package instead since there's a good chance that the library is backwards-compatible.
To achieve that we need to create a symbolic link to it in a location where the program executable can find it. Since this is kind of a hack, it would be preferable if other applications don't find the same link automatically. Helpfully, this application adds ~/.ember/lib to its library search path by default.
I suggest that you

*

*assure that the librtmp1 package is installed,
sudo apt install librtmp1

*create the directory ~/.ember/lib,
mkdir -p ~/.ember/lib

*put the symbolic link there.
ln -sT /usr/lib/$(uname -m)-linux-gnu/librtmp.so.1 ~/.ember/lib/librtmp.so.0

If the application now fails with a "missing symbol" error message (or something like that) please update your question with the error message and notify me with a comment so I can address it.

If there are more missing shared libraries you can search for their packages and

*

*install them if they're available in Xenial or

*search for newer version of the same shared library (without the version number at the end of the package name) repeat the above process for it.


text:
Q: wp get_post of custom post type and images am trying to get 10 post of a custom post type
$args = array( 'numberposts' => 10, 'post_type' => 'mycustomposttype'  );

    $myposts = get_posts( $args );

    foreach ( $myposts as $post ) : setup_postdata( $post );

        if ( has_post_thumbnail() )
        {
            $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'full' );

            //my template here
        }

    endforeach;

The if statement
if ( has_post_thumbnail() )

returns false but all of my custom post have image
Now if i change the 'numberposts' => 10 to 'numberposts' => 100
i get the images of the posts
What am i missing here


text:
Q: Want to add a Collapse Button on the Table to expand it on the front end import React, { useState, useEffect, Fragment } from "react";
import classes from "../CSS/DataUpload.module.css";
import * as XLSX from "xlsx";
import axios from "axios";
import Table from "@mui/material/Table";
import TableBody from "@mui/material/TableBody";
import TableCell from "@mui/material/TableCell";
import TableContainer from "@mui/material/TableContainer";
import TableHead from "@mui/material/TableHead";
import TableRow from "@mui/material/TableRow";
import Paper from "@mui/material/Paper";
import { Button } from "@mui/material";

let initialSend = true;
const DataUpload = () => {
  const [sendData, setSendData] = useState([]);
  const [addData, setAddData] = useState(false);
  const [display, setDisplay] = useState(false);
  const [notification, setNotification] = useState();

  useEffect(() => {
    // console.log(sendData);
    // let payload = JSON.parse(sendData);
    // console.log("type of ", typeof payload);

    const excelData = async () => {
      // console.log(se)
      try {
        console.log(sendData);
        const url = "http://localhost:5000/users";
        const config = {
          "Content-Type": "application/json",
        };
        const response = await axios.post(url, sendData, config);
        const msg = response.data.msg;
        setNotification(msg);
      } catch (error) {
        console.log(error);
      }
    };
    if (initialSend) {
      initialSend = false;
      return;
    } else {
      setDisplay(true);
      excelData();
    }
  }, [addData]);

  const onChange = (e) => {
    const [file] = e.target.files;
    const reader = new FileReader();

    reader.onload = (evt) => {
      const bstr = evt.target.result;
      const wb = XLSX.read(bstr, { type: "binary" });
      const wsname = wb.SheetNames[0];
      const ws = wb.Sheets[wsname];

      const data = XLSX.utils.sheet_to_json(ws, {
        header: [
          "no",
          "name",
          "vuln_type",
          "summary",
          "tech_details",
          "remediation",
          "req",
          "res",
          "cvss_score",
          "cvss_eq",
          "severity",
        ],
        blankrows: false,
      });
      data.shift();
      setSendData(data);
    };
    reader.readAsBinaryString(file);
  };

  const addDataHandler = () => {
    setAddData(true);
  };
  const removeNotification = () => {
    setDisplay(false);
  };
  // };
  return (
    <Fragment>
      {display && (

{notification}

          <button
            style={{ float: "right", color: "white" }}
            onClick={removeNotification}
          >
            X
          </button>

      )}

Choose Excel File to Upload

        <input type="file" id="input" onChange={onChange}></input>

        <TableContainer component={Paper}>

            <TableHead>
              <TableRow sx={{ fontSize: 16 }}>
              <TableCell>No</TableCell>
                <TableCell align="right">Name</TableCell>
                <TableCell align="right">Vuln Type</TableCell>
                <TableCell align="right">Summary</TableCell>
                <TableCell align="right">Tech Details</TableCell>
                <TableCell align="right">Remediation</TableCell>
                <TableCell align="right">req</TableCell>
                <TableCell align="right">res</TableCell>
                <TableCell align="right">cvss score</TableCell>
                <TableCell align="right">cvsseq</TableCell>
                <TableCell align="right">severity</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {sendData.map((row) => (
                <TableRow
                  key={row.no}
                  sx={{ "&:last-child td, &:last-child th": { border: 0 } }}
                >
                  <TableCell component="th" scope="row">
                    {row.no}
                  </TableCell>
                  <TableCell align="right">{row.name}</TableCell>
                  <TableCell align="right">{row.vuln_type}</TableCell>
                  <TableCell align="right">{row.summary}</TableCell>
                  <TableCell align="right">{row.tech_details}</TableCell>
                  <TableCell align="right">{row.remediation}</TableCell>
                  <TableCell align="right">{row.req}</TableCell>
                  <TableCell align="right">{row.res}</TableCell>
                  <TableCell align="right">{row.cvss_score}</TableCell>
                  <TableCell align="right">{row.cvss_eq}</TableCell>
                  <TableCell align="right">{row.severity}</TableCell>
                </TableRow>
              ))}
            </TableBody>

        </TableContainer>

    </Fragment>
  );
};

export default DataUpload;[enter image description here][1]

This the code for my front end. I want to add a collapse button to the request and response field. I have no idea about how to do it as I am a newbie in this field. I am making this project for our company. It fetches the data from MongoDB which is the back end. It would be really great if anyone can suggest how to do it. Thanks in advance.

A: You are looking for the Collapse component.
Just put your table into Collapse component, sth like ↓

const [open, setOpen] = useState(false);

return (
  <>
    <button onClick={() => setOpen(!open)}>
      {open ? "Collapse" : "Expand"}
    </button>
    <Collapse in={open}>
      <TableContainer component={Paper}>
      ....
      </TableContainer>
    </Collapse>
  </>
)

Here is the demo I've created, you can take a look.
Update
I think you need sth like this example, horizontal collapse, am I right?
The example was not created by me though, I think it can give you some hints.


text:
Q: How to detect the url of all tabs using python and selenium I created a program in python selenium which does an action when you go on a specific url on selenium (with chrome driver).
The problem is that only the first tab detects the url and if any other tab is used to visit the url it will not be detected.
my code to detect the url:

driver = webdriver.Chrome()
driver.get('https://www.google.com')

paypal_url = "paypal.com"
google_url = "google.com"

while True:
    url = driver.current_url
    if paypal_url in url and "signin" in url:
        print("Connected on paypal !")
        sleep(1)
        do_action()
        break
    elif google_url in url and "signin" in url:
        print("Connected on google !")
        sleep(1)
        do_action()
        break
    else:
        sleep(1)

My question is:
How can I detect when the user goes on a specific url in any tabs (not only the first one)

A: You could use the following for-loop:
urls = []
for i in range(0, len(driver.window_handles), 1):
  driver.switch_to.window(driver.window_handles[i])
  urls.append(driver.current_url)


text:
Q: Applescript code messy, how to fix display dialog "Play Nillys Realm?" buttons {"Yes please", "No"} default button 1

if result = {button returned: "Yes please"} then
  display dialog "Long time loading, u think?" buttons {"Yes", "No"}
end if

if result = {button returned:"No"} then
  tell application "Google Chrome"
    repeat 5 times
        open location "http://test.nillysrealm.com"
        activate
    end repeat

    if result = {button returned:"Yes"} then
      tell application "Google Chrome"
        repeat 10 times
          open location "http://test.nillysrealm.com"
          activate
        end repeat

thats my code and it is a MESS. Can anyone help me fix? It will never load

A: It is not easy to help in your script, because reading it, I do not understand what you want to do. However you are not using the 'Result' variable correctly. This variable always contains the result of the last dialog, so when you have 2 dialog box, any test of that variable will always give you the result of the second dialog, never the first one.
The solution is to specifically assign the result to a separate variable, like in example bellow :
set Dialog1 to display dialog "do you agree ?" buttons {"Yes please", "No"} default button 1
if button returned of Dialog1 is "Yes please" then
-- do something here when user click "yes please"
else
-- do somthing here when user click "No"
end if


text:
Q: Is there something like a reverse geospatial query in MongoDB? I have a list of Points of Interest, say, restaurants, theatres, gardens, etc. saved in a Mongo database. Then, I have an application that tracks the user's movements in a city and keeps gathering the location intermittently. If I find that a person is "near" a point of interest, I need to send her/him a notification. "Nearness" for a POI is a variable quantity - for a restaurant it could be 100m, for a theatre it could be 200m, for a garden it could be 20m, etc.
Each POI is, of course, saved as a separate document. Now, is there a way to fire a query on MongoDB with the lat/lon of a person and retrieve the list of POIs nearby?
Say, my documents are like this:
{
  "type": "restaurant",
  "name": "Binny's",
  "loc": [-122.10396, 37.45093],
  "maxDist": 100
}
{
  "type": "museum",
  "name": "Ripley's",
  "loc": [-122.24546, 37.48251],
  "maxDist": 500
}
I need to fire a query that gives me the list of POIs nearby (not more than 'maxDist' metre away from the POI) for a given lat/lon value, say, [-122.12098,37.46001].
Is there a way to construct a query to achieve this? If I have to alter the document structure a little bit, that's fine.
Thanks in advance.

A: Use $near. It will allow you to query the position of the user and all locations that are within a specific distance.


text:
Q: Horizontal line after every table I want to draw a horizontl line after every table. I tried using \hrulefill after every table, but this breaks because of the floating behavior of the tables, e.g. if i have a Code
pseudo MWE:

\hrule

\hrule

\hrule

the Output will look somewhat like that:

*

*table

*horizontal line

*table

*horizontal line

*horizontal line

*table

and of course this is not want I want.
MWE
\documentclass{article}
\usepackage{array}

\newcommand{\cTable}
{
\begin{table}
  \caption{abc}
  \begin{tabular}{l | l}
    a & a   \\
    b & b   \\
    c & c
  \end{tabular}
\end{table}
}

\begin{document}
\cTable
\hrule
\cTable
\hrule
\cTable
\hrule
\end{document}

A: As you say, table environments float so you need to draw the line before you close the table environment. The following seems to do what you want:
\documentclass{article}
\usepackage{array}

\newenvironment{Table}{\table}{\newline\hrule width\textwidth\endtable}

\newcommand{\cTable}
{
\begin{Table}
  \caption{abc}
  \begin{tabular}{l | l}
    a & a   \\
    b & b   \\
    c & c
  \end{tabular}
\end{Table}
}

\begin{document}
\cTable

\cTable

\cTable

\end{document}

Here is the output:


text:
Q: Converting string to multidimensional array in PHP I have this as a string input.
$str = '[2]Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis vulputate cursus nulla, at rhoncus ante egestas vitae. [3]Cras euismod aliquet hendrerit. [3]Integer tortor lorem, suscipit a ante id, faucibus iaculis dolor. Sed aliquet, erat sit amet porta efficitur, eros lorem hendrerit purus, eget pellentesque lacus sapien ut dolor. [3]Donec eget accumsan velit. [4]Vestibulum consectetur enim in nunc fermentum lacinia. Maecenas fermentum rutrum sodales. Quisque vulputate, dolor tempus luctus cursus, massa urna ultrices odio, non dictum sem nulla ac mi. Quisque egestas tellus velit, non elementum lorem consequat id. Proin bibendum feugiat mollis. Sed vel odio neque. [4]Tempo. [2]Phasellus ut mauris purus. Quisque vel tortor erat. [2]Donec eget accumsan velit.';

And I'm trying to get to this...
array (
[0] => array ( //First [2] and everything below
    [0] => Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis vulputate cursus nulla, at rhoncus ante egestas vitae.
    [1] => array ( //[3]s that belong to first [2]
        [0] => Cras euismod aliquet hendrerit. //First [3]
        [1] => Integer tortor lorem, suscipit a ante id, faucibus iaculis dolor. Sed aliquet, erat sit amet porta efficitur, eros lorem hendrerit purus, eget pellentesque lacus sapien ut dolor. //Second [3]
        [2] => array ( //Third [3] and everything below
            [0] => Donec eget accumsan velit.
            [1] => array (
                [0] => Vestibulum consectetur enim in nunc fermentum lacinia. Maecenas fermentum rutrum sodales. Quisque vulputate, dolor tempus luctus cursus, massa urna ultrices odio, non dictum sem nulla ac mi. Quisque egestas tellus velit, non elementum lorem consequat id. Proin bibendum feugiat mollis. Sed vel odio neque.
                [1] => Tempo.
                )
            )
        )
[1] => Phasellus ut mauris purus. Quisque vel tortor erat. //Second [2]
[2] => Donec eget accumsan velit. //Third [2]

)
I've tried everything I knew and could find @php.net and everywhere else, but I've spent about six hours on this and I'm still stuck. I've tried explode, preg_replace, array_walk_recursive (along with explode), going from the biggest hierarchy to smaller (best results so far) and the other way around, but nothing. How can I convert a string to a multidimensional array in PHP, setting the hierarchy by tags in the string?
Many thanks!

A: $str = '[2]Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis vulputate cursus nulla, at rhoncus ante egestas vitae. [3]Cras euismod aliquet hendrerit. [3]Integer tortor lorem, suscipit a ante id, faucibus iaculis dolor. Sed aliquet, erat sit amet porta efficitur, eros lorem hendrerit purus, eget pellentesque lacus sapien ut dolor. [3]Donec eget accumsan velit. [4]Vestibulum consectetur enim in nunc fermentum lacinia. Maecenas fermentum rutrum sodales. Quisque vulputate, dolor tempus luctus cursus, massa urna ultrices odio, non dictum sem nulla ac mi. Quisque egestas tellus velit, non elementum lorem consequat id. Proin bibendum feugiat mollis. Sed vel odio neque. [4]Tempo. [2]Phasellus ut mauris purus. Quisque vel tortor erat. [2]Donec eget accumsan velit.';

$counter = 2;
function splitLevel($str, $counter) {
    if (strpos($str, '['.$counter.']') === false) {
        return $str;
    }
    $split = array_values(
        array_filter(
            explode('['.$counter.']', $str)
        )
    );

    array_walk(
        $split,
        function(&$value) use ($counter) {
            $value = splitLevel($value, ++$counter);
        }
    );

    if (($counter > 2) && (count($split) > 1)) {
        $first = array_shift($split);
        $split = array($first, $split);
    }
    return $split;
}
$array = splitLevel($str, $counter);

var_dump($array);

gives
array(3) {
  [0]=>
  array(2) {
    [0]=>
    string(117) "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis vulputate cursus nulla, at rhoncus ante egestas vitae. "
    [1]=>
    array(3) {
      [0]=>
      string(32) "Cras euismod aliquet hendrerit. "
      [1]=>
      string(179) "Integer tortor lorem, suscipit a ante id, faucibus iaculis dolor. Sed aliquet, erat sit amet porta efficitur, eros lorem hendrerit purus, eget pellentesque lacus sapien ut dolor. "
      [2]=>
      array(2) {
        [0]=>
        string(27) "Donec eget accumsan velit. "
        [1]=>
        array(2) {
          [0]=>
          string(306) "Vestibulum consectetur enim in nunc fermentum lacinia. Maecenas fermentum rutrum sodales. Quisque vulputate, dolor tempus luctus cursus, massa urna ultrices odio, non dictum sem nulla ac mi. Quisque egestas tellus velit, non elementum lorem consequat id. Proin bibendum feugiat mollis. Sed vel odio neque. "
          [1]=>
          string(7) "Tempo. "
        }
      }
    }
  }
  [1]=>
  string(52) "Phasellus ut mauris purus. Quisque vel tortor erat. "
  [2]=>
  string(26) "Donec eget accumsan velit."
}

So just add a bit of extra logic to trim trailing spaces, and you should be good

A: This code
$str = '<your_string>';

function stringToArray($str, $delimiter = 2, $isFirst = false) {
    $delimiterStr = "[{$delimiter}]";
    $outArr = array();
    if (strpos($str,$delimiterStr)!==false) {
        $outArr = explode($delimiterStr, $str);
        $isFirstElement = true;
        $tempArr = array();
        $key = 0;
        foreach ($outArr AS $v) {

            if (!empty($v))
            {
                if ($isFirstElement) {
                    $tempArr[$key] = stringToArray($v, $delimiter+1);
                    $key++;
                } else {
                    $tempArr[$key][] = stringToArray($v, $delimiter+1);
                }
            }
            $isFirstElement = false;
        }
        $outArr = $tempArr;
    }
    if (!$outArr) {return trim($str);} else {return $outArr;}
}

$elements = stringToArray($str);
print_r($elements[0]);

will return
Array
(
[0] => Array
    (
        [0] => Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis vulputate cursus nulla, at rhoncus ante egestas vitae.
        [1] => Array
            (
                [0] => Cras euismod aliquet hendrerit.
                [1] => Integer tortor lorem, suscipit a ante id, faucibus iaculis dolor. Sed aliquet, erat sit amet porta efficitur, eros lorem hendrerit purus, eget pellentesque lacus sapien ut dolor.
                [2] => Array
                    (
                        [0] => Donec eget accumsan velit.
                        [1] => Array
                            (
                                [0] => Vestibulum consectetur enim in nunc fermentum lacinia. Maecenas fermentum rutrum sodales. Quisque vulputate, dolor tempus luctus cursus, massa urna ultrices odio, non dictum sem nulla ac mi. Quisque egestas tellus velit, non elementum lorem consequat id. Proin bibendum feugiat mollis. Sed vel odio neque.
                                [1] => Tempo.
                            )

                    )

            )

    )

[1] => Phasellus ut mauris purus. Quisque vel tortor erat.
[2] => Donec eget accumsan velit.
)

A: // The string to parse
$str = '[2]Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis vulputate cursus nulla, at rhoncus ante egestas vitae. [3]Cras euismod aliquet hendrerit. [3]Integer tortor lorem, suscipit a ante id, faucibus iaculis dolor. Sed aliquet, erat sit amet porta efficitur, eros lorem hendrerit purus, eget pellentesque lacus sapien ut dolor. [3]Donec eget accumsan velit. [4]Vestibulum consectetur enim in nunc fermentum lacinia. Maecenas fermentum rutrum sodales. Quisque vulputate, dolor tempus luctus cursus, massa urna ultrices odio, non dictum sem nulla ac mi. Quisque egestas tellus velit, non elementum lorem consequat id. Proin bibendum feugiat mollis. Sed vel odio neque. [4]Tempo. [2]Phasellus ut mauris purus. Quisque vel tortor erat. [2]Donec eget accumsan velit.';

// Parse the string, start with level 2
$array = analyze($str, 2);

// Ignore the fragment before the first '[2]' (it's empty)
array_shift($array);
// Display the list of fragments marked with '[2]` and their offspring
print_r(current($array));

/**
 * Analyze the string $string, search for sections labeled with '[N]'
 * (N = $level).
 * Return an array with two elements: the text before the first '[N]'
 * marker and an array of the fragments that start with '[N]' marker.
 * Each fragment is parsed using the same function.
 *
 * Return the input string ($string) if it does not contain the marker.
 */
function analyze($string, $level)
{
    // The marker
    $marker = '['.$level.']';

    // If the marker does not exist in the string then this is a leaf
    if (strpos($string, $marker) === FALSE) {
        // Return the input string
        return $string;
    }

    // Split by section marker
    $pieces = explode($marker, $string);

    // Extract the first fragment; it is returned as is
    $first = array_shift($pieces);

    // Analyze the pieces, search for the next level
    return array(
        $first,           // First fragment as is
        array_map(        // Parse the rest using the same function (one level deeper)
            function ($piece) use ($level) {
                return analyze($piece, $level + 1);
            },
            $pieces
        ),
    );
}

In order to use it on PHP versions before 5.3 (when anonymous functions were introduced), replace the last block of code (starting with return array() with:
// Analyze the pieces, search for the next level
$rest = array();
foreach ($pieces as $piece) {
    $rest[] = analyze($piece, $level + 1);
}
return array($first, $rest);


text:
Q: WPF: item container not part of the item collection For another question I need to figure out the position of every item of a ListBox relative to the currently selected item, because I'd like to style the items before the currently selected item different than the items behind the currently selected item (by Trigger).
I try different things, one of them is using a MultiBinding with a MultiValueConverter.
The XAML of the DataTrigger looks like this:
<DataTrigger Value="True">
    <DataTrigger.Binding>
        <MultiBinding Converter="{StaticResource rpc}">
            <Binding Path="." RelativeSource="{RelativeSource FindAncestor, AncestorType={x:Type ListBox}}" />
            <Binding Path="." RelativeSource="{RelativeSource FindAncestor, AncestorType={x:Type ListBoxItem}}" />
        </MultiBinding>
    </DataTrigger.Binding>

    <Setter Property="..." Value="..." />
</DataTrigger>

This DataTrigger is used in a Style that is used inside the ItemTemplate of the ListBox.
The mentioned Converter "rpc" is a MultiValueConverter.
If I set a break point inside the Convert function of this MultiValueConverter I get the ListBox instance as the first value and the ListBoxItem instance as the second value, so the MultiBinding works.
But if I try to figure out the index of the ListBoxItem inside the ItemsCollection of the ListBox by using listBox.Items.IndexOf(listBoxItem) I always get -1, as if the ListBoxItem is not a member of the ItemsCollection.
Even if I try to find out the ListBoxItem by checking the Content of the items for equality (listBox.Items.OfType(Of ListBoxItem).FirstOrDefault(Function(x) x.Content.Equals(listBoxItem.Content))), I won't get a ListBoxItem.
Why is that so?
And how else can I get the index of the ListBoxItem if not by IndexOf?

A: You're getting -1 because the Items collection doesn't contain any ListBoxItem elements, but rather the actual contents of the ListBoxItem.
Try this:
var index = listBox.Items.IndexOf(listBoxItem.Content);


text:
Q: How to Display Two Javascript Functions with One Button Click I am currently finishing up a Web Development course and this week we are covering: Adding Javascript to your website. The scripts are easy to add and I have gotten everything to work, however, the purpose of the script and the site do not go together. One of the tasks is to add a button and onclick - the time and data are displayed. I get the intent here to demonstrate that you can add these elements to a page - but it does not make sense to me. So, I want to add the date and time in a way that it fits with the purpose of my site - which covers COVID information. Hence, what I am putting together is a button that when clicked will display the date and time (as required) and also display an embeded map from Our World In Data. This will meet the assignment requirements and have a logical purpose for displaying the time/date along with an update on COVID information.
Now, what I am finding out is that a div tag cannot have two IDs and that a function cannot have more than one element. However, there has to be a way that a button can display two things when clicked - right?
So, after two days at this - this is where I am at and any suggestions you may have are more than welcomed. Remember, I am learning here as I go and I do not have any education in Javascript at this time.

Where I am at with two separate buttons:

Covid Status

The following Button will display what the current COVID Status is around the world, according to Our World In Data.

        <input type="button" value="Show Chart" onClick="covid();">

        <input type="button" value="Show Time" onClick="time();">

What I am trying do via various online examples:

Covid Status

The following Button will display what the current COVID Status is around the world, according to Our World In Data.

        <button type="button" id="Show_Info">Show Information</button>

In advance, Thank You Very Much!

A: You could make a function that calls your other two functions when you click the button.

A: I hope I have been helpful.

        function myFunc() {
            document.getElementById('time').innerHTML = Date();
            document.getElementById('covid').innerHTML = '';
        }

        var showbtn = document.getElementById("Show_Info");
        showbtn.addEventListener("click", myFunc);

Covid Status

The following Button will display what the current COVID Status is around the world, according to Our
                World In Data.

            <button type="button" id="Show_Info">Show Information</button>


text:
Q: Image size zero when src'd as blob-url but not when src'd as data-url I have a image blob that I want the height and width of, so I create a blob url, set the src of an image object to it, and then get the height and width of the image object.
(let [window-url (or (-> js/window .-URL)
                       (-> js/window .-webkitURL))
        blob-url (window-url.createObjectURL blob)
        image (js/Image.)]
    (set! (.-src image) blob-url)
    (prn "image height" (.-height image))
    (prn "image width " (.-width image))
      )

But the result I get is:
image height 0
image width 0
But obviously the image doesn't have a 0 height and width, which I've already verified by displaying the image on the document through its data-url (which I then convert into the blob referred above like (js/Blob. [data-url])). So why is the blob's height and width zero if the corresponding data-url does show on the document?

A: Try displaying the properties naturalWidth and naturalHeight of the image instead: https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/Image#Usage_note

A: I'm pretty sure that you can only get the height/width after the image has been "loaded" so you need to attach an onload event handler. Using a blob URL does not change that restriction.
Probably something like this, I didn't test it though.
(let [window-url (or (-> js/window .-URL)
                     (-> js/window .-webkitURL))
      blob-url (.createObjectURL window-url blob)
      image (js/Image.)]
  (set! (.-onload image)
    (fn [e]
      (prn "image height" (.-height image))
      (prn "image width " (.-width image))))
  (set! (.-src image) blob-url))

A: Here is how we do it in our codebase. As Thomas Heller pointed out, you need to load the image in order to get proper image metadata.
(defn with-image-data
  "Asynchronously load an image `file` in a FileReader, then call the `callback`
  fn with a proper Image object"
  [file callback]
  (let [reader (js/FileReader.)
        img    (js/Image.)]
    (set! (.-onload reader) #(set! (.-src img) (.-result reader)))
    (set! (.-onerror reader) #(js/console.error %))
    (set! (.-onload img) (fn [_] (callback img)))
    (.readAsDataURL reader file)
    nil))


text:
Q: Can [NSMutableDictionary dictionaryWithObjectsAndKeys cause a buffer overrun? I have the following function in my code:
NSMutableDictionary* productDictionary =
[NSMutableDictionary dictionaryWithObjectsAndKeys:productIdentifier, @"Product ID", @(difficulty), @"Difficulty", nil];

If productIdentifier is nil, is it possible that this is cause a buffer overrun and write data beyond its allocated bounds?
Thanks for you help,
- Rich

A: No, if it's nil you will simply get an empty dictionary.

A: The arguments in the variable argument list are only read. You might get a "bad access" hardware exception when you forgot to set a terminating nil.
I would guess, if the first parameter firstObject is nil, you safely get an empty dictionary.


text:
Q: Pin chat windows in Windows Live Messenger to Task Bar in Windows 7 Is it possible to drag/pin individual conversations in Windows Live Messenger on to the Windows 7 task bar.
Currently, I have the Windows Live program pinned, and I need to hover over that, and then navigate to a given chat window. This is, in my eyes a) redundant, and b) irritating.
If I close the Live program, I lose all my conversations.
I may be doing something wrong, but I can't seem to achieve what sounds like it should be possible.
I like combining the task bar icons, with the exception of Live chat windows - so it may not be possible.
Thanks for any insight.

A: I haven't been able to pin any of my conversations individually in the taskbar, just the program itself. The only thing that I can think of is just to keep that chat window open, so it's always up.


text:
Q: Hibernation mode in Linux I am using 3.5.0-rc1-smp+ kernel. And when I close the cover of the laptop on Windows 7 the computer comes into hibernation mode with HDD and fans off. The machine stays cool.
But in Linux the drive is still periodically clicking and the fans are slowly moving. The laptop stays hot.
How can I make it work like in Windows?

A: If you use the GNOME desktop environment, you can use gsettings. There are two cases to distinguish and can be set seperately: if the laptop is running on AC or on battery.
gsettings set org.gnome.settings-daemon.plugins.power lid-close-ac-action hibernate
gsettings set org.gnome.settings-daemon.plugins.power lid-close-battery-action hibernate


text:
Q: Why do i have a syntax error on pgadmin4(Trigger)? this is my code:
CREATE TRIGGER sovrapposizione_spettacoli
BEFORE INSERT ON Spettacoli
FOR EACH ROW
BEGIN
DECLARE
CURSOR c1 IS SELECT data_e_ora, durata FROM mv_spettacoli_attivi s WHERE s.codice_sala=: NEW.sala; inizio_spettacolo     mv_spettacoli_attivi.data_e_ora%TYPE; durata_spettacolo     mv_spettacoli_attivi.durata

now ignore the code after SELECT, but pgadmin gave me a sintax error near "begin", i tried to correct it by deleting begin and declare and replacing it with execute but after that it still gives me a sintax error in CURSOR, can anybody tell me why?

A: The CREATE TRIGGER syntax does not allow to have direct pl/pgsql code in CREATE TRIGGER statement.
You must call a function or procedure:
CREATE [ CONSTRAINT ] TRIGGER name { BEFORE | AFTER | INSTEAD OF } { event [ OR ... ] }
    ON table_name
    [ FROM referenced_table_name ]
    [ NOT DEFERRABLE | [ DEFERRABLE ] [ INITIALLY IMMEDIATE | INITIALLY DEFERRED ] ]
    [ REFERENCING { { OLD | NEW } TABLE [ AS ] transition_relation_name } [ ... ] ]
    [ FOR [ EACH ] { ROW | STATEMENT } ]
    [ WHEN ( condition ) ]
    EXECUTE { FUNCTION | PROCEDURE } function_name ( arguments )

Here is a short demo that you can use to adapt your code (the trigger only declares a cursor using the 'new' value of the row being inserted and does nothing more than return 'new': this is needed for a before insert trigger in PostgreSQL).
Source code:
create function mytriggerfunc()
returns trigger
language plpgsql
as
$$
declare
 c1 cursor for select * from mytable2 where id2 = new.id1;
begin
 return new;
end;
$$;
\echo
CREATE TRIGGER mytrigger
BEFORE INSERT ON mytable1
FOR EACH ROW
execute function mytriggerfunc();
\echo
insert into mytable1 values(1, 'ONE');
\echo
select * from mytable1;

Execution with psql:
create function mytriggerfunc()
returns trigger
language plpgsql
as
$$
declare
 c1 cursor for select * from mytable2 where id2 = new.id1;
begin
 return new;
end;
$$;
CREATE FUNCTION

CREATE TRIGGER mytrigger
BEFORE INSERT ON mytable1
FOR EACH ROW
execute function mytriggerfunc();
CREATE TRIGGER

insert into mytable1 values(1, 'ONE');
INSERT 0 1

select * from mytable1;
 id1 | col2
-----+------
   1 | ONE
(1 row)

See PG trigger functions.


text:
Q: JSON Processing - Sending JSON text string to JSP, how to process in JSP sendng json data to another jsp page - for testing really.
You enter a JSON formatted string in a text field on my jsp. I submit this through a form request, handled by jquery processing. It is sent to a receiver JSP. I am using the following code to do this.
    $.ajax({
    type:       "POST",
    url:        "receiver.jsp",
    data:       term, // This is a formatted JSON string
    success:    function(data, textStatus, jqXHR) {
                        alert('Success : ' + data);
                        alert('textStatus : ' + textStatus);
                        alert('jqXHR : ' + jqXHR);
                        var jsonJqXHR = JSON.stringify(jqXHR);
                        alert('jsonJqXHR : ' + jsonJqXHR);
        },
    error:function (xhr, ajaxOptions, thrownError){
        alert('Error xhr : ' + xhr.status);
        alert('Error thrown error: ' + thrownError);
    },
    //complete: alert('complete'),
    dataType:   "text" // xml, json, script, text, html
});

My question is, how do I pick this POST up in the receiver JSP and do something with it? I have seen somethings with getParameter etc but I am not sure.

A: I think it will be easy to send it as parameter:
data: "jsonData=" + term,

Also you can put it in form input with name="jsonData" and serialize your form:
data: jQuery("form").serialize(),

Then you can read it in receiver.jsp:
<%
    String jsonData = request.getParameter("jsonData");
%>


text:
Q: How do I create a JAR where the package is in the root folder? (and not inside a bin folder) I am trying to create a jar from the command line using the following:
jar cfm EWSTerabot.jar ./MyManifest.txt ./bin/ews/
However, when I execute the JAR, I get the following error  "Could not find or load main class ews.main.gateway.Main"
The reason I receive this error is that when I extract the JAR and look inside, the main class is at bin/ews/main/gateway/Main.class. How do I create the JAR so that the ews folder is at the root and the Main class is located at ews/main/gateway/Main.class. I essentially want to create the JAR without this bin folder.

A: From the offical jar documentation (http://docs.oracle.com/javase/tutorial/deployment/jar/build.html) :
jar cfm EWSTerabot.jar ./MyManifest.txt -C ./bin .

use -C to specify a different directory than the current.

A: You have to use the -C option of the jar command which tells to switch to the specified folder and include the files and folders listed after that.
For example to include the ews folder/package in the jar file:
jar cfm EWSTerabot.jar ./MyManifest.txt -C bin/ ews/


text:
Q: Stitch two independent branch histories together I have two independent branches in my Git repository:
A---B---C branch "old"
X---Y---Z branch "master"

I want to generate the following history:
A---B---C---X---Y---Z

I tried this with the following rebase command (current branch is "master"):
git rebase --strategy=recursive --strategy-option=theirs old master

This fails with:
First, rewinding head to replay your work on top of it...
fatal: Could not parse object 'fb56e6e20ea4a605503732df1f5a0a407808dffa^'

fb56e6 is the first commit of the "old" branch.
As an alternative I used the cherry pick command (current branch is "master"):
git rev-list --reverse old | git cherry-pick --stdin --keep-redundant-commits -X theirs

This works fine, but all commits get a new "committer". Is there a way to tell cherry pick that it should not set the committer? If not, is there a way to achieve what I want with rebase?

A: I solved it using git filter-branch:
FIX_COMMITTER='
    if test "$GIT_AUTHOR_NAME" != "$GIT_COMMITTER_EMAIL"; then
        GIT_COMMITTER_EMAIL="$GIT_AUTHOR_EMAIL"
        GIT_COMMITTER_NAME="$GIT_AUTHOR_NAME"
        export GIT_COMMITTER_EMAIL
        export GIT_COMMITTER_NAME
    fi
'
git filter-branch -f --env-filter "$FIX_COMMITTER" -- master

Source of the idea: https://gist.github.com/maciej/5875814

A: I like your cherry-pick approach.  Just run the standard "set my author info" commands before doing cherry-pick to match the "commiter" data you want to preserve.
git config --global user.name "John Doe"
git config --global user.email johndoe@example.com

And then set the author info back to yourself when you're done.


text:
Q: Active Record join with params in condition I am not sure I know the best way to write this sql query in active record without totally writing it by hand. Essentially I want to write a combination of these two queries.
This query is essentially the join I am trying to re-create. I want to make sure any entries returned are only those with the images with a image_path_processing flag set to false.
@entries = ContestEntry.joins(:entry_images).where(contest_id: @contest.id, entry_images: {
        image_path_processing: false
        }).limit(10)

However the issue I am running into with the query I am writing is that I need to include params from a url and I am not sure that the above syntax is properly removing sql_injection
Here is what I am attempting to add the conditional join to.
@entries = ContestEntry.where("contest_id = ? and created_at > ?",
      params[:contest_id], Time.at(params[:after].to_i + 1))

A: Can you try this?
@entries = ContestEntry.joins(:entry_images).
                        where(contest_id: params[:contest_id],
                              entry_images: { image_path_processing: false }).
                        where('contest_entries.created_at > ?', Time.at(params[:after].to_i+1)).
                        limit(10)

A: First, read this documentation: http://guides.rubyonrails.org/security.html#sql-injection
Back in the day, the primary supported syntax was
ContestEntry.where("contest_id = ?", params[:contest_id])

but now you can also use the simpler and more ruby-ish
ContestEntry.where(:contest_id => params[:contest_id])

Both of these approaches will pass the params through a sql sanitizer to prevent sql-injection attacks as described in the documentation.
A couple additional points:

*

*I am not sure how to implement that latter syntax for anything but equality.

*The problems you've heard recently regarding sql injection, do not apply to the syntax you are using.  They apply to dynamic finders.

Finally, you shouldn't take my word for it.  One of the best pieces of advice a ruby developer ever gave to me was 'Use irb to learn ruby'.  If you have a question about how something works, load up irb and test it.  In your case you are implementing rails, so you have the full console at your disposal.
sql_injection_params = "anything' OR 'x'='x"
# This string variant tells active record to use sql as is
Model.where("name = '#{sql_injection_params}'").to_sql # bad
# This array variant tells active record to sanitize
Model.where('name = ?', sql_injection_params).to_sql # good
# This hash variant tells active record to sanitize
Model.where(:name => sql_injection_params).to_sql # good

The to_sql call will show you what raw SQL active record builds based on your query.  Just change the above example to use your data and you should get a better idea of what rails is doing under the hood.

A: @entries = ContestEntry.where("contest_id = ? and created_at > ?",
      params[:contest_id], Time.at(params[:after].to_i + 1))

seems perfect way to avoid the sql injection from the user entered result...


text:
Q: Understanding Skrollr data values I am trying to understand the Skrollr javascript script library, and am having difficulty understanding data values, and how they differ between absolute and relative.
I have a background image on a div (about 2x taller than the div) that I would like to scroll down as I scroll down the page. Here is what I have so far.

What are data-top and data-bottom? As near as I can figure from the documentation, data-top is the top of the div #jumbotron. What I want is that when #jumbotron is at the top of the viewport, the background position is right bottom. Then, as I scroll and the the bottom of #jumbotron reaches the top of the viewport, I want the background image to be right top. This isn't happening. What am i doing  wrong?

A: The skrollr library will transition the CSS on an element based on its data elements. For example, if you had an element as follows:

At scroll position 0 (user has not scrolled), the opacity of the element would be 1. Once the user has scrolled 100px down the page, the element would have faded to opacity 0. You can add as many data increments as you'd like.
Regarding data-top, the readme on the skrollr repo says the following:

data-top: When the element's top is aligned with the top of the
  viewport

I don't however see anything about data-bottom in the docs. I only see:

data-top-bottom: When the bottom of the element is at the top of the viewport (it's just not visible).

So you might try:

Just consider that the first data is your starting point, and the final data is your finishing point with as many increments along the way as you need.

A: Skrollr.js needs a data-attribute with two values.
The first describes the alignment to the viewport.
The second the edge (or center) of the element.
It can be a bit confusing, that both are named in the same manner (top, center or bottom).
You can further position the background with percentage values.
This way skrollr can transition between the values.
See this example.
https://jsfiddle.net/4frjantk/

PS:
The example contains a workaround for containers with 100% height as described here https://github.com/Prinzhorn/skrollr/issues/347


text:
Q: Converting to float: CAST vs CONVERT vs *1.0 Which is preferred and why? I'm using integer values for clarity however these would be field names.

*

*SELECT 2*1.0 / 3

*SELECT CAST(2 AS float) / 3

*SELECT CONVERT(float, 2) / 3

A: From a performance perspective regarding the first one and the CAST/CONVERT, I quickly created a temp table and queried it using the value of 2:
CREATE TABLE #temp (Two FLOAT)
INSERT INTO #temp VALUES (2)
SELECT * FROM #temp

SELECT Two*1.0 / 3 FROM #temp
SELECT Two*1E0 / 3 FROM #temp
SELECT CAST(Two AS FLOAT) / 3 FROM #temp
SELECT CONVERT(FLOAT,Two) / 3 FROM #temp

When selecting from it, no matter how many different values I enter, the Execution plan and Statistics IO give me the same numbers (each a fourth).  I tried entering other values like 5, 6, 7, 8, 9 and so on, and even more values, but the cost came as the same.  From the beyond relational article listed above this (here: http://beyondrelational.com/modules/2/blogs/77/posts/11334/cast-vs-convert-is-there-a-difference-as-far-as-sql-server-is-concerned-which-is-better.aspx), it appears that using your first method doesn't have any effect, as least on the small values (I did use 2,000,000).


text:
Q: How to remove colour scale legend from plot() of spp density in R I am plotting the density of a two-dimensional, weighted spatial point pattern. I'd like to make the plot without a colour scale legend, and save it with no (or minimal) boarders on all sides, like this: My problem is that I can't remove the colour scale legend. Reproducible code below:
## Install libraries:
library(spatstat) #spatial package
library(RColorBrewer) #create custom colour ramps

## Create reproducible data:
data <- data.frame(matrix(ncol = 3, nrow = 50))
x <- c("x", "y", "weight")
colnames(data) <- x
data$x <- runif(50, 0, 20)
data$y <- runif(50, 0, 20)
data$weight <- sample(1:200, 50)

## Set plotting window and colours:
plot.win <- owin(c(0,20), c(0,20)) # plot window as 20x20m
spat.bat.frame <- NULL # create a frame to store values in
cols1<-colorRampPalette(brewer.pal(9,"Blues"))(100) #define colour ramp for density plots

## Create and save plots:
jpeg(filename = "Bad plot.jpeg", res = 300, units = "cm", width = 20, height = 20)
par(mar=c(0,0,0,0),oma=c(0,0,0,0),lwd=1)

ppp_01 <- ppp(x = data$x, y = data$y, window = plot.win)
ppp_02 <- ppp(x = data$x, y = data$y, window = plot.win)
plot(density(ppp_01, weights = data$weights), main=NULL, col=cols1, sigma = 1)
plot(ppp_02, add=TRUE) #add spp points to density plot

dev.off()

I've tried legend=FALSE, auto.key=FALSE, colorkey=FALSE, which don't seem to be compatible with plot() (i.e. they don't give an error but don't change anything). I've also tried some work-arounds like saving a cropped image with dev.off.crop() or by adjusting margins with par(), but haven't been able to completely remove the legend. Does anyone have any suggestions on how to remove a colour scale legend of a density spp (real-valued pixel image) using plot()?
I specifically need to plot the density of the spatial point pattern, to specify a custom colour ramp, and to overlay the spp points onto the density image. I could try plotting with spplot() instead, but I'm not sure this will allow for these three things, and I feel like I'm missing a simple fix with plot(). I can't crop the figures manually after saving from R because there are 800 of them, and I need them all to be exactly the same size and in the exact same position.
Thank you!

A: Since plot is a generic function, the options available for controlling the plot will depend on the class of object that is being plotted. You want to plot the result of density(ppp_01, weights = data$weights). Let's call this Z:
Z <- density(ppp_01, weights = data$weights, sigma=1)

Note:  the smoothing bandwidth sigma should be given inside the call to density
To find out about Z, you can just print it, or type class(Z).
The result is that Z is an object of class"im" (pixel image).
So you need to look up the help file for plot.im, the plot method for class "im". Typing ?plot.im shows that there is an argument ribbon that controls whether or not the colour ribbon is displayed. Simply set ribbon=FALSE in the call to plot:
plot(Z, ribbon=FALSE, main="", col=cols1)

Or in your original code
plot(density(ppp_01, weights=data$weights, sigma=1), main="", col=cols1)

However I strongly recommend separating this into two lines, one which creates the image object, and one which plots the image. This makes it much easier to spot mistakes like the misplacement of the sigma argument.


text:
Q: SQL Query syntax, I want to use INNER JOIN I'm working on a windows application project using front end "vb.net" & back end "Ms Access" I have problem in wrinting sql query
Actually there are 5 tables Transaction,items,itemtitle,itemtype & userinfo.
check the following query & with this referance if u get idea then plz change in correct query
Thanking You
SELECT
TRANSACTIONS.ACCESSIONNO AS
ACCESSIONNO,TRANSACTIONS.TYPEID,
TRANSACTIONS.CHECKOUTDATE AS CHECKOUTDATE,ITEMTITLE.ITEMTITLE,
TRANSACTIONS.CHECKEDOUTBY,
USERINFO.FULLNAME_ENG,
USERINFO.FULLNAME_MAR,
TRANSACTIONS.ACCOUNTNO,
ITEMTYPE.TYPES_MAR,
ITEMTYPE.TYPES_ENG

FROM
  TRANSACTIONS,ITEMTYPE,
  ITEMTITLE,
  USERINFO

WHERE
  TRANSACTIONS.ACCOUNTNO=USERINFO.ACCOUNTNO
  AND TRANSACTIONS.ACCESSIONNO=ITEMS.ACCESSIONNO
  AND ITEMS.ITEMTITLEID=ITEMTITLE.ITEMTITLEID
  AND TRANSACTIONS.TYPEID=ITEMTYPE.TYPEID
  AND TRANSACTIONS.STATUS='Enabled'

A: It looks like you left out the ITEMS table. The below joins to that table. At any rate, it demonstrates the INNER JOIN syntax. (Usually I use aliases for readability. I purposefully them out.)
SELECT TRANSACTIONS.ACCESSIONNO AS ACCESSIONNO, TRANSACTIONS.TYPEID, TRANSACTIONS.CHECKOUTDATE AS CHECKOUTDATE, ITEMTITLE.ITEMTITLE, TRANSACTIONS.CHECKEDOUTBY, USERINFO.FULLNAME_ENG, USERINFO.FULLNAME_MAR, TRANSACTIONS.ACCOUNTNO, ITEMTYPE.TYPES_MAR, ITEMTYPE.TYPES_ENG
FROM TRANSACTIONS
INNER JOIN ITEMTYPE ON (TRANSACTIONS.TYPEID = ITEMTYPE.TYPEID)
INNER JOIN ITEMTITLE ON (ITEMS.ITEMTITLEID = ITEMTITLE.ITEMTITLEID)
INNER JOIN USERINFO ON (TRANSACTIONS.ACCOUNTNO = USERINFO.ACCOUNTNO)
INNER JOIN ITEMS ON (TRANSACTIONS.ACCESSIONNO = ITEMS.ACCESSIONNO)
WHERE TRANSACTIONS.STATUS = 'Enabled'


text:
Q: If a listbox contains an item LIKE Is there anywhere to check whether a listbox contains an item which is similar to a string?
I have tried to use a Like statement but this doesn't work.
I have tried:
For i As Integer = 0 To TopicListBox.Items.Count - 1
                If (TopicListBox.Items(i).ToString.Contains(Record.Item("Keyphrase2"))) Then
                    Dim Item As String = TopicListBox.Items(i).ToString
                    If Item Like "Questions related to:" & Record.Item("Keyphrase2") & ": |*| Qs" Then
                        Dim ItemSplit() As String = Item.Split(New Char() {"|"c})
                        Dim AmountOfQuestionsAfter As Integer = AmountOfQuestions + CInt(ItemSplit(1))
                        Item = ItemSplit(0) & AmountOfQuestionsAfter & ItemSplit(1)
                    Else
                        TopicListBox.Items.Add("Questions related to:" & Record.Item("Keyphrase2") & ": |" & AmountOfQuestions & "| Qs")
                        Exit For
                    End If
                End If
            Next

A: I don't really understand what you are trying to accomplish, but here is a LINQ function to return all the items that contain a certain string.
Dim lb As New ListBox

lb.Items.Add("asdf")
lb.Items.Add("asdfasdf")
lb.Items.Add("aifisasdf")
lb.Items.Add("adf")

'' find all items in the ListBox that contain the string "asdf"
Dim found = lb.Items.Cast(Of String).Where(Function(f) f.Contains("asdf"))

For Each s In found
  '' do something with those items
Next

A: Can't you just do
If Item.Contains("Questions related to:" & Record.Item("Keyphrase2")) Then
    ...
End If

or
If Item.StartsWith("Questions related to:" & Record.Item("Keyphrase2")) Then
    ...
End If

?

A: Dim Found = (From Result In lb.Items Where Result.ToString = "Value" Select Result)

If (Found.Count > 0) Then
    ' your code
End If


text:
Q: Sort array based on constantly changing map I have a ConcurrentHashMap which is asynchronously updated to mirror the data in a database. I am attempting to sort an array based on this data which works fine most of the time but if the data updates while sorting then things can get messy.
I have thought of copying the map and then sorting with the copied map but due to the frequency I need to sort and the size of the map this is not a possibility.

A: I'm not sure I understood your requirements perfectly, so I'll deal with two separate cases.
Let's say your async "update" operation requires you to update 2 keys in your map.
Scenario 1 is : it's OK if a "sort" operation occurs while only 1 of the two updates is visible.
Scenario 2 is : you need the 2 updates to be visible simultaneously or not at all (which is called atomic behavior).
Case 1 : you do not need atomic bulk updates
In this case, ConcurrentHashMap is OK as is, seeing iterators are guaranteed not to fail upon modification of the map. From ConcurrentHashMap documentation (emphasis mine) :

Similarly, Iterators and Enumerations return elements reflecting the state of the hash table at some point at or since the creation of the iterator/enumeration. They do not throw ConcurrentModificationException. However, iterators are designed to be used by only one thread at a time.

So you are guaranteed that you can iterate through the map even while it is being modified without the iteration crashing for concurrent modifications. But (see the emphasis) you are NOT guaranteed that all modifications made concurrently to the map are immediately visible not even if only part of them are, and in which order.
Case 2 : you need bulk updates to be atomic
Further more with ConcurrentHashMap, you do not have any guarantee that bulk operations (putAll) will behave atomically :

For aggregate operations such as putAll and clear, concurrent retrievals may reflect insertion or removal of only some entries.

So I see two scenarios for working this case, each of which entail locking.
Solution 1 : building a copy
Building a "frozen" copy can help you only if this copy is built during a phase where all other updates are locked, because the copying of your map implies iterating through it, and our hypothesis is that iteration is not safe if we have concurrent modification.
This could look like :
ConcurrentMap<String, String> map = new ConcurrentHashMap<String, String>(); //
AtomicReference<Map<String, String>> frozenCopy = new AtomicReference<Map<String, String>>(map);

public void sortOperation() {
    sortUsingFrozenCopy();
}

public void updateOperation() {
    synchronized (map) { // Exclusive access to the map instance
        updateMap();
        Map<String, String> newCopy = new HashMap<String, String>();
        newCopy.putAll(map); // You build the copy. This is safe thanks to the exclusive access.
        frozenCopy.set(newCopy); // And you update the reference to the copy
    }
}

This solution could be refined...
Seeing your 2 operations (map read and map writes) are totally asynchronous, one can assume that your read operations can not know (and should not care) wether the previous write operation occured 0.1 sec before or will occur 0.1 sec after.
So having your read operations depend on a "frozen copy" of the map that is actually updated once every 1 (or 2, or 5, or 10) seconds (or update events) instead of each time may be a possibility for your case.
Solution 2 : lock the map for updates
Locking the Map without copying it is a solution. You'd want a ReadWriteLock (or StampedLock in Java 8) so as to have multiple sorts possible, and a mutual exclusion of read and write operations.
Solution 2 is actually easy to implement. You'd have something like
ReadWriteLock lock = new ReentrantReadWriteLock();

public void sortOperation() {
    lock.readLock().lock();
            // read lock granted, which prevents writeLock to be granted
    try {
        sort(); // This is safe, nobody can write
    } finally {
        lock.readLock().unlock();
    }
}

public void updateOperation() {
    lock.writeLock().lock();
            // Write lock granted, no other writeLock (except to myself) can be granted
            // nor any readLock
    try {
        updateMap(); // Nobody is reading, that's OK.
    } finally {
        lock.writeLock().unlock();
    }
}

With a ReadWriteLock, multiple reads can occur simultaneously, or a single write, but not multiple writes nor reads and writes.
You'd have to consider the possibility of using a fair variant of the lock, so that you are sure that every read and write process will eventually have a chance of being executed, depending on your usage pattern.
(NB : if you use Locking/synchronized, your Map may not need to be concurrent, as write and read operations will be exclusive, but this is another topic).


text:
Q: Placing markdown within shinydashboard box compresses page I am trying to embed markdown within a shinydashboard box, to be later deployed on a shiny server. Using the solution here, I have created the following:
ui.R
library(shinydashboard)

dashboardPage(
   dashboardHeader(title = "xxx"),
   dashboardSidebar(),
   dashboardBody(
     column(
       box(
         title = "BoxTest",
         uiOutput('mymarkdown'),
         width = NULL
       ),
       width = 8)
  )
)

server.R
library(shiny)
library(knitr)
shinyServer(function(input, output) {

  output$mymarkdown <- renderUI(HTML(markdown::markdownToHTML(knit("mymarkdown.Rmd", quiet = TRUE))))

})

mymarkdown.Rmd
## R Markdown

Test Test Test

This creates the following:

If I switch to a non-markdown implementation, for example:
output$mymarkdown <- renderUI(h4("Test Test Test"))

I get:

the view I would expect.
Is there any way to avoid this compression of the page, or is there another way to deploy markdown text in a shinydashboard box?

A: I also used markdown in shiny, but with rmarkdown and includeHTML
library(shinydashboard)
library(shiny)
library(knitr)
library(rmarkdown)

ui <- dashboardPage(
  dashboardHeader(title = "xxx"),
  dashboardSidebar(),
  dashboardBody(
    column(
      box(
        title = "BoxTest",
         uiOutput('mymarkdown'),
        width = NULL
      ),
      width = 8)
  )
)
server <- shinyServer(function(input, output) {
    output$mymarkdown <- renderUI({
         rmarkdown::render(input = "mymarkdown.Rmd",
                           output_format = html_document(self_contained = TRUE),
                           output_file = 'mymarkdown.html')
         shiny::includeHTML('mymarkdown.html')
                            })
} )
shinyApp(ui, server)

A: markdown::markdownToHTML has an option to create only a HTML fragment. It omits the HTML header and styling. Like this, the Shiny site styling is not corrupted.
output$mymarkdown <- renderUI({
    k <- knitr::knit(input = "mymarkdown.Rmd", quiet = T)
    HTML(markdown::markdownToHTML(k, fragment.only = T))
})


text:
Q: Wordpress ACF relationship not in sync I have two custom post types "Departments" and "Employees" in which both I have added an custom field with the type of "relationship", so that I on the Departments page can see, which employees are assigned to the department and on the Employees page, I can see which department they are attached to.
So far it works but somehow, when I assign an employee to an department or vice versa, and I go to the department or employee page, the relationships has not been updated - is this a common issue? That doesn't make sense to me...

A: When you use relationship field, the link is only in one direction : if you link an employee to a department, you create a link employee->department, but not the reverse link department->employee.
Maybe this tutorial could help you to create a bidirectional relationship field :
https://www.advancedcustomfields.com/resources/bidirectional-relationships/


text:
Q: Python in SPSS Create new variable run arcpy script I have just found this module, and need a bit of help moving my ArcGIS python script over to python/SPSS module.  The script uses the Updatecursor feature from the Arcpy module.  Here is my text so far.
# BEGIN PROGRAM.
import arcpy

fc = C:\Users\Desktop\file.TXT
fields =('RESIDENTIAL_ADDRESS1', 'RESIDENTIAL_SECONDARY_ADDR', 'RESIDENTIAL_CITY', 'FULL_ADDRESS')
with arcpy.da.UpdateCursor(fc, fields) as cursor:
    for row in cursor:
        row[3] = '{0}{1}{2}'.format(row[0], row[1], row[2])
        cursor.updateRow(row)
    del cursor

# END PROGRAM.

I need the code to run on the current open file, create the new variable, do the concatenate.  I know I can do this through SPSS much easier, but I have many more additional python scripts I need to import in that do much more involved calcs also using the arcpy Update/Search Cursors.
My file size consists of 8 million records and came from a sqlexpress dbf. My python script was running in ArcGIS where I was doing some additional geocoding. I also run about another 5 to 6 python scripts doing various other calcs that I cannot program (like I can program concatenate) in spss. So my goal is to bring those python scripts into SPSS to do those calcs in SPSS instead of in ArcGIS. This was my first Arcpy task so I through it in here as an example of how to get this to work properly using the Python Plugin –

A: This is more of an extended comment. I'm confused where C:\Users\Desktop\file.TXT comes into play - is that not your currently opened file? Consider using spss.Submit for such a simple task of concatenating fields within an active SPSS file (e.g. there is no need to iterate over every row in the data for this task). So here is a simple example:
DATA LIST FREE / Add1 Add2 (2A20) City (A6) State (A2).
BEGIN DATA
"125 Main St" "" Albany NY
"Main St." "Lake St" Albany NY
END DATA.

BEGIN PROGRAM.
import spss
fields = ['Add1','Add2','City','State']
conc = ",' ',".join(fields)
spss.Submit("""
STRING ConcField (A255).
COMPUTE ConcField= CONCAT(%s).
""" % (conc))
END PROGRAM.

In unicode mode this will collapse the white space - but otherwise you would need to adjust your list to be something like RTRIM(Add1) for all of the different variables. This is just a simple example though.
SPSS has similar method to arcPy's cursor named spss.Cursor, but from your example it isn't clear that is what is necessary.


text:
Q: PhpDoc: protected property Is it possible to declare protected or private class @property using PhpDoc?
/**
  * Class Node
  * @package app\models
  * @property string $name
  */
class Node
{

}

A: I don't think so. For @property, public is implied, even if it's read-only or write-only. The point of such tags is about documenting interfaces that can't be inferred. A private/protected variable is really internal to the class so it's only relevant to child classes which should be written as if they already know this. You can still leave a plain docblock immediately before you declare it, though.


text:
Q: how to call factory function from another factory in the same module in angularJS I have these two factories .
factory one
sameRoof.factory('dbService', function (localStorageService, backendupdate) {
    return {
      checkCredentials: function () {
        return localStorageService.get('profile');
      },
      handle_credentials: function (param) {
        if (localStorageService.isSupported) {
          var profile = {id: param.id, name: param.name, gender: param.gender, zone: param.locale};
          localStorageService.set('profile', profile);
          backendupdate.updateRequestData();
        }
      }

    };
  });

and factory 2 :
sameRoof
  .factory('backendUpdate', function () {
    return {
      updateRequestData: function () {
        alert('requestData')
      }}
  });

i am not able to call factory 2 in factory one.
I am getting
Unknown provider: backendupdateProvider <- backendupdate <- dbService ERROR.

A: It's seems like you've a typo... Replace backendupdate with backendUpdate in your dependency injections....
 function (localStorageService, backendUpdate) {

A: It seems you have a typo in the first factory, this:
sameRoof.factory('dbService', function (localStorageService, backendUpdate)


text:
Q: The "right way" to host multiple NodeJS domains on a single server? I have a VPS that runs Apache and serves a number of WordPress site. I also managed to get a NodeJS server running on this same VPS account using the MEAN stack. Things worked fine with this setup.
I decided to add a second NodeJS/MEAN app to this same server, running on a separate port, and everything is operating fine - except I've noticed a significant impact to page load performance across all sites once I got this third server running.
I found this question and this question here on SO, but neither of these address performance. So my question is:
Is it possible/practical run two separate/unique domains on the same NodeJS server app? Or is that going to create more problems than it solves? (Note: I don't mean the same machine, I mean the same NodeJS instance)
If not, How can I improve performance? Is upgrading my VPS the only option?

A: So you can indeed run multiple apps on the same port/process.  This can be done using the express-vhost module if you need to separate by domain.  You can also use the cluster module to run a pool of processes that share resources (though they end up being the same 'app', you could combine that with the vhost approach to have a pool of processes service a number of domains.
That said, I don't think you're actually going to get the results you want.  The overhead of a nodejs process is pretty trivial compared to most (e.g a JVM); the costs come mostly in whatever your custom code is doing.  I think what's more likely happening is that whatever size server you've chosen for your VPS is just not enough to run everything you're throwing at it, or the node apps you've written are hogging the event loop through long running processes.  It could also be the case that Apache is the hog; you'll need to do more diagnostics to get to the root of it.


text:
Q: $L^p(\mu)$ space relations Let $(X,M, \mu)$ be a measure space. Suppose $1 \leq p < r \leq \infty$.
Suppose $f \in L^p (\mu) \cap L^r(\mu)$. Show that $f\in L^s(\mu)$ for $p \leq s \leq r$.
Attempt:
Suppose $f \in L^p (\mu) \cap L^r(\mu)$. Then $\int |f| ^p d\mu < \infty$ and $\int |f|^r d\mu < \infty$.
Isn't it obvious that $\int |f|^s d\mu < \infty$ already?
I'm bit confused on what to show.
Any help will be appreciated!
Thank you for your help!

A: Can also be done from the Hölder inequality, in the form:
If $1/\alpha+ 1/\beta = 1$, then
$$
\int |FG|\;d\mu \le
\left(\int |F|^\alpha\;d\mu\right)^{1/\alpha}\;\left(\int |G|^\beta\;d\mu\right)^{1/\beta}
\tag1$$
Given $p<s<r$ and $f \in L_p \cap L_r$ as in the problem, let
$$
\alpha = \frac{r-p}{r-s},\quad \beta = \frac{r-p}{s-p}
\quad\text{so that}\quad \frac{1}{\alpha}+\frac{1}{\beta} = 1\quad\text{and}\quad
\frac{p}{\alpha} + \frac{r}{\beta} = s,
$$
and let
$$
F = |f|^{p/\alpha},\qquad G = |f|^{r/\beta}
$$
Plug into $(1)$ to get
$$
\int|f|^s\;d\mu \le \left(\int |f|^p\;d\mu\right)^{(r-s)/(r-p)}
\;\left(\int |f|^r\;d\mu\right)^{(s-p)/(r-p)} < \infty.
$$

We will need a different (easier) argument in case $r = \infty$.

A: This is Proposition 6.10 in Folland: If $0< p <q<r \leq \infty$, then $L^p \cap L^r \subset L^s$ and $\|f\|_s \leq \| f\|_p^{\lambda}\|f \|_r^{1- \lambda}$, where $\lambda \in (0,1)$ is defined by $\lambda = \frac{s^{-1} -r^{-1}}{p^{-1} - r^{-1}}$ when $r \ne \infty$, and $\lambda = p/s$ when $r \ne \infty$.
When $r= \infty$, you use the definition of $\| f\|_{\infty}$ to show the inequality.
When $r \ne \infty$, it's just Holder's inequality.

A: It seems obvious and it is to some degree but it requires a small amount of work to get there. Kavi's comment almost completely gives it away. If $|f(x)| \le 1$, then $|f(x)|^s \le |f(x)|^p$ since $p < s$. Similarly if $|f(x)| > 1$, then $|f(x)|^s \le |f(x)|^r$ since $s < r$. Can you put these together to show that $\int |f(x)|^s \,d\mu(x) < \infty$?
This is called ($L^p$) interpolation for what it's worth and is a very useful technique in functional analysis.


text:
Q: How to display tabs as 4 spaces in gnome-terminal Actually gnome-terminal display tabs as 8 spaces, and this is very annoying when you cat files or view diffs, is there some way to change this permanently?

A: The unique solution I found is to type in terminal:
tabs 5,9,13,17,21,25,29,33,37,41

and append it to ~/.bashrc if you want permanent changes.
PS: This obviously cover up to 10 tab indents.

A: Instead of writing out an explicit list of tabstops, you can also use implicit intervals:
tabs -n

This will set tabstops to occur every n columns. For more information, check out the manpage for tabs at http://manpages.ubuntu.com/manpages/maverick/en/man1/tabs.1.html.

A: You need to set the tabwidth on the underlying tty, not in gnome-terminal itself.
Theoretically, you should be able to use 'setterm -regtabs 4' to set the tabwidth to 4 in your .bashrc.
Doesn't seem to be working on my linux distro, but it works when I ssh from a remote system.
The easiest way to reset the tabwidth to 8 is to use 'tabs -8' (tabs -d8 to get a visual of the change).

A: The problem with doing it as "tabs -4" is that the first tab stop is off by one (at least on my system). If I type in "tabs -4", for example, the first tab stop will start in the 4th column with 3 blank spaces in front of it instead of 4. Subsequent tab stops will all be correctly separated by 4 spaces. A workaround to this is to specify the tab stops like so:
tabs 1,+4,+4,+4,+4,...

A: If you're using bash, this is what I have in my ~/.bashrc:
# set tabs to width TABWIDTH
TABWIDTH=4
# for less(1) the option -x4 was added (see above);
# other programs may need their own flags
setterm -regtabs ${TABWIDTH} </dev/tty
tabs -0 </dev/tty
# this erroneously imho sets the first tab at offset 3, not offset 4:
#tabs 1,+${TABWIDTH} </dev/tty
# this works:
tabs 1`for i in {0..40}; do echo -n ",+${TABWIDTH}"; done`
unset TABWIDTH

Note the backticks around the 'for ... done' ditty.
edit: The last '+4' before the 'done' statement should of course have been +${TABWIDTH}.

A: You can also do tabs -4 and it will set a tab stop every 4th column.

A: tabs 1,5,9,13,17,21,25,etc
doesn't appear to work entirely correctly. On input, when backspacing over a tab, gnome-terminal goes back 8 spaces, not four. Looks like there's a gnome-terminal bug here. (Note: you won't see this if typing into the shell, because it usurps tabs for file completion. You have to first run cat or dc or some other command that doesn't arrogate tab characters for its own purposes.)


text:
Q: ibmmq with nodejs - unable to establish connection I'm trying to connect to IBMMQ using my nodejs code, following the instructions from the link https://github.com/ibm-messaging/mq-mqi-nodejs. I really don't understand why do we need to install MQ on client machine as per this step here
'It also requires the MQ C client libraries to be installed that you can get from your MQ installation media or from this site.' When I go and the there I see those instructions for installation is for MQ server. But without this MQ C library it is throwing me exception.
I don't really have any local queue, I don't understand why do I need to install all that in my local machine. All I want is that just send messages to the remote queue.
Has anyone used this before, if so how.

A: The latest version of the README for that package on github includes another link which points at the Redist client packages which are now available more easily. As Josh says, those can be unpacked without neededing a full install process. Of course, if you unpack those in a local directory, you need to remember to run setmqenv as the default locations for discovering the libraries won't work.


text:
Q: DB structure to handle chat groups similar to Telegram/FB Messenger Currently doing a chat app where a user could join multiple chat groups, something similar to what Telegram and Facebook Messenger has. Pretty straight forward. We're mainly using Firebase database for storing the chat groups and message details.
Sample DB structure:
To only get the chat groups a user has:
root/
users/
  chatGroups/
    $uid/
      $chatGroupId: true

We then get the details of the chat group from a different node, same with the latest chat message in that group:
root/
chatGroups/
  entries/
    $groupId/
      group details here...
  messages/
    $groupId/
      $messageId/
        message details here..

Everything above  to get the data for a single group item that looks something like this:

All works fine. We initially get at most 5 chat groups at first, then just sort the list. The problem lies where we have to listen for updates for the chat groups -- group with the most recent chat message would go to top of the list.
The structure we have listens only to the list of groups the specific user has -- we could detect groups joined (onChildAdded) and left (onChildRemoved) by the user, but it doesn't contain the timestamp we need to sort the chat group list by the most recent changes timestamp.
Has anyone tried this similar behavior with Firebase before (we're doing a client for both Android and Web -- Javascript)? Any ideas or suggestions would be appreciated. Let me know if you need some relevant details to make things clearer.

A: Because there is no auto-created metadata in Firebase about when a child was added, updated or deleted and also because those operations doesn't contain the information you are searching for, you need to create your own mechanism by adding the local timestamp for each operation or by writing a server-side timestamp.
There is another approach in which you can use denormalization. Add those chats to a new created section named uxChats. The chats will need to contain only the text message and the timestamp. If you are using FirebaseUI then you can reverse the order just using this lines of code:
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setReverseLayout(true);
layoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(layoutManager)

Latest chat goes on top.
Hope it helps AL.


text:
Q: What is the corresponding FACS Action unit name to the Affdex Emotion SDK expressions output? I wonder where I can find a full list of Action Unit names which are detected from Affdex? I have manually identified some: browfurrow (AU4),  browraise (AU2),  chinraise (AU17). However, an official information document will be a better choice for me. Thanks

A: We follow the same FACS system for naming the AU's, you can find the list of Action Units on Wikipedia. For a more visual representation you can refer to Academic Pages.


text:
Q: Nginx reverse proxy to wordpress in docker container through ecs I am trying to proxy_pass to an http Wordpress site that is set up in a docker container through an Amazon ecs instance. The client gets to the site through a test server we have set up (https://test.xxxxxxx.com). When a user goes to https://test.xxxxxxx.com, I want it to show https://test.xxxxxxx.com in the address bar, but bring up the page for my Wordpress site (http://xx.xxx.xxx.xxx on port 80).
I can get it to go to my Wordpress site, but it looks funny. I am getting a lot of mixed content errors because I'm trying to access http files via an https request. I understand what's happening, but I can't seem to fix it, even after trying all of the suggestions I could find online.
I have tried changing several settings in both the Nginx file in the sites-available folder and by changing settings in wp-config.php on my Wordpress site. Below is one thing I tried. Almost all the tutorials I found, and everything I tried, was a variation of this.
#Nginx file

server {
    listen 443;

    location / {
        proxy_pass http://xx.xxx.xxx.xxx:80;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

#wp-config.php

if ($_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https')
    $_SERVER['HTTPS'] = '1';

if (isset($_SERVER['HTTP_X_FORWARDED_HOST'])) {
    $_SERVER[HTTP_HOST'] = $_SERVER[HTTP_X_FORWARDED_HOST'];
}

define( 'WP_HOME', 'http://xx.xxx.xxx.xxx');
define( 'WP_SITEURL', 'http://xx.xxx.xxx.xxx');

What I would like to happen is that when a user enters https://test.xxxxxxx.com in the address bar, my Wordpress site loads with the proper theme and all my images, but https://test.xxxxxxx.com still shows in the address bar.

A: I wanna sugguest you use HA-Proxy reverse proxy in ECS.
I tried nginx reverse proxy, but failed. And success with HA-Proxy.
It is more simple than nginx configuration.
First, use "links" option of Docker and setting "environment variables" (eg. LINK_APP, LINK_PORT).
Second, fill this "environment variables" into haproxy.cfg.
Also, I recommend you use "dynamic port mapping" to ALB. it makes more flexible works.
taskdef.json :
# taskdef.json

{
    "executionRoleArn": "arn:aws:iam::<AWS_ACCOUNT_ID>:role/<APP_NAME>_ecsTaskExecutionRole",
    "containerDefinitions": [
      {
        "name": "<APP_NAME>-rp",
        "image": "gnokoheat/ecs-reverse-proxy:latest",
        "essential": true,
        "memoryReservation": <MEMORY_RESV>,
        "portMappings": [
          {
            "hostPort": 0,
            "containerPort": 80,
            "protocol": "tcp"
          }
        ],
        "links": [
          "<APP_NAME>"
        ],
        "environment": [
          {
            "name": "LINK_PORT",
            "value": "<SERVICE_PORT>"
          },
          {
            "name": "LINK_APP",
            "value": "<APP_NAME>"
          }
        ]
      },
      {
        "name": "<APP_NAME>",
        "image": "<IMAGE_NAME>",
        "essential": true,
        "memoryReservation": <MEMORY_RESV>,
        "portMappings": [
          {
            "protocol": "tcp",
            "containerPort": <SERVICE_PORT>
          }
        ],
        "environment": [
          {
            "name": "PORT",
            "value": "<SERVICE_PORT>"
          },
          {
            "name": "APP_NAME",
            "value": "<APP_NAME>"
          }
        ]
      }
    ],
    "requiresCompatibilities": [
      "EC2"
    ],
    "networkMode": "bridge",
    "family": "<APP_NAME>"
  }

haproxy.cfg :
# haproxy.cfg

global
    daemon
    pidfile /var/run/haproxy.pid

defaults
    log global
    mode http
    retries 3
    timeout connect 5000
    timeout client 50000
    timeout server 50000

frontend http
    bind *:80

    http-request set-header X-Forwarded-Host %[req.hdr(Host)]

    compression algo gzip
    compression type text/css text/javascript text/plain application/json application/xml

    default_backend app

backend app
    server static "${LINK_APP}":"${LINK_PORT}"

Dockerfile(haproxy) :
FROM haproxy:1.7
USER root
COPY haproxy.cfg /usr/local/etc/haproxy/haproxy.cfg

See :
Github : https://github.com/gnokoheat/ecs-reverse-proxy
Docker image : gnokoheat/ecs-reverse-proxy:latest


text:
Q: Importing .eml files into Exchange Discovery Folder I am needing to import over 18mm eml files into Exchange (this is for a client, so I'm restricted on what I can do - flexibility). They do not want these emails to go to the actual users email, so they do not want them to show up in the users inbox, deleted ..etc. They want to be able to search for these emails for litigation purposes ... hence the discovery folder.
I have looked into the Pickup folder, which does not do what I want. I have also been writing some C# code to use the EWS (Exchange Web Service) Managed API, but so far I have not found anything to work for me. The EWS Managed API does not have any methods available to do what I am needing either. I have also looked at the EWS (not the Managed API) as it has an UploadItem(s) call, this does not seem feasible due to the Data property which is an encoded Fast Stream.
Keeping the original email dates is important, some of solutions I have found (such as the EWS Managed API CreateItem method) changes the dates of the emails.
The Exchange server is 2010 SP1.
I have looked through other questions/answers and they do not really match up with what I'm needing to accomplish. These are older emails that have already been removed from the users mailbox. So to turn around and put these emails into the Users inbox would (of course) be very bad.

A: Urmm.. maybe not the easiest nor the quickest way or maybe i got the wrong end of the tail... why not public folders with relevant security applied and import the EML files?
Outlook can open EML with a bit of reg-hack (http://www.msoutlook.info/question/354)
There are paid solutions to convert EML files to MSG or bulk into PST and then simply move them over to public folders? One example: http://www.aid4mail.com/import-export-mail.php?
(assumption that user is/will be using MSFT Outlook)


text:
Q: Minimum sample size in each strata of stratified random sampling I am performing stratified random sampling on a population (country) containing ~20 strata (states). I need to calculate mean of the population. I also know the proportion of the strata. My question is: Should I have a minimum sample size (say >=30) in each strata/state? I have greater than 30 samples for the country, but I do not have greater than 30 samples for each state. My assumption is since I am calculating mean for the population (country), at a state level, I can as well have 1 or 2 samples.
Will this be an issue in estimating the means? Please let me know.
Thanks!

A: Minimum sample size is useful once you consider that units might not respond.  However, if you make it too large your design is going to be less efficient.  If you aim for about $5$ reponding units should be enough.  Bump this up with an assumed response rate $5/rr $.  $30$ is more than enough - but will probably mean you are putting sample where it isn't needed for a good estimate of the total