text:
Q: Pass option { useUnifiedTopology: true } to the MongoClient constructor Does anyone know why I'm still receiving a deprecation warning even though I've already specified useUnifiedTopoology: true in my MongoClient constructor?
Thank you in advance!
const mongodb = require('mongodb')
const MongoClient = mongodb.MongoClient
const connectionURL = 'connectionurl'
const databaseName = 'db'

const client = new MongoClient(connectionURL, { useNewUrlParser: true, useUnifiedTopology: true});

const insertHandler = async(data, collectionName) => {
  await client.connect().then(async() => {
    const collection = client.db(databaseName).collection(collectionName)
    await collection.insertOne(data)
  }).catch(error => {
    console.log("Failed to insert:", error)
  })
}

module.exports = {
  insertHandler: insertHandler
}

And I'm getting the following error:
DeprecationWarning: current Server Discovery and Monitoring engine
is deprecated, and will be removed in a future version. To use the
new Server Discover and Monitoring engine, pass option { useUnifiedTopology:
true } to the MongoClient constructor.

A: I'm using Mongoose for MongoDB, the same code with no error. mongoose.connect("mongodb://localhost:27017/YOURDB", { useNewUrlParser: true, useUnifiedTopology: true });

A: mongoose.connect('mongodb://localhost/vidly',
{ useNewUrlParser: true , useUnifiedTopology: true })
.then(()=>{ return console.log("Connected to MongoDB Localhost...");
 })
.catch(err => console.log("Could not connect",err))

It's working for me!!!

A: This is what I used and it worked for me:
const mongoServer = require('mongodb');
const mongoClient = mongoServer.MongoClient;
const dbName = 'tconnect';
const serverUrl = 'mongodb://localhost:27017/';

// Create a database
const dbUrl =  serverUrl + dbName;
const client = new mongoClient(dbUrl, { useUnifiedTopology: true });

client.connect( (err, db) => {
    if (err) {
        console.log(err);
        return;
    }
    else {
        console.log('Database successfully created!');
        db.close();
    }
});

A: I tried it, and this is the solution which worked:
mongoose.connect("mongodb://localhost:27017/fruitsDB", { useNewUrlParser: true,  useUnifiedTopology: true });

Kind regards,

A: You can do it this way
var mongoDb = require('mongodb');
var mongoClient = mongoDb.MongoClient;
var serverUrl = "mongodb://127.0.0.1:27017/";
var dbName = "sample_db";

mongoClient.connect(serverUrl, { useNewUrlParser: true, useUnifiedTopology: true }, function (err, db) {
   // Code goes here...
});

A: I use it this way, and I don't see that warning anymore.
const run = async () => {
await mongoose.connect(keys.mongoURI, {
  useNewUrlParser: true,
  useUnifiedTopology: true
});
};
run().catch(error => console.error(error);

A: https://github.com/Automattic/mongoose/issues/8169

this is the reference to solve this problem

const assert = require('assert');
const mongoose = require('mongoose');
mongoose.set('debug', true);

const GITHUB_ISSUE = `gh8169`;
const connectionString = `mongodb://localhost:27017/${ GITHUB_ISSUE }`;
const { Schema } = mongoose;

run().then(() => console.log('done')).catch(error => console.error(error.stack));

async function run() {
  console.log('Mongoose version:', mongoose.version);
  mongoose.set('useUnifiedTopology', true);
  mongoose.set('useNewUrlParser', true);
  mongoose.connect(connectionString, { useFindAndModify: false });
  const db = mongoose.connection;

  db.once('open', () => console.log('connected'));
}

A: Write as below:
mongoose.connect('mongodb://localhost:27017/contactlist', { useNewUrlParser: true, useUnifiedTopology: true });


text:
Q: npm install bcrypt failed node $ npm install bcrypt

bcrypt@5.0.0 install D:\courses\Angela Yu - Web Development\31. Authentication & Security\Secrets - Starting Code\node_modules\bcrypt
node-pre-gyp install --fallback-to-build

The system cannot find the path specified.
'"node"' is not recognized as an internal or external command,
operable program or batch file.
npm WARN website@1.0.0 No description
npm WARN website@1.0.0 No repository field.
npm ERR! code ELIFECYCLE
npm ERR! errno 9009
npm ERR! bcrypt@5.0.0 install: node-pre-gyp install --fallback-to-build
npm ERR! Exit status 9009
npm ERR!
npm ERR! Failed at the bcrypt@5.0.0 install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Aryan chauhan\AppData\Roaming\npm-cache_logs\2020-07-15T16_53_36_616Z-debug.log

A: I think that your problem can be for two things, please check the following:

*

*Bcrypt 5 it's the newest version of this package, and this package have some issues with some node's versions, we can see this here. Although it does not show version 5, it is very recent and it is possible that it is not documented. Try to update the node version (I recommend to use nvm to achieve this or test your bcrypt in a testing project with a more recent node version.

*Node isn't recognized. Try to execute node in the terminal and see if you're entering in the REPL. If not, and an error message it's displayed, this can be a signal that you don't have nodejs. Again, I recommend use nvm to install it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: print elements in list in reversed order and on a new line I want to print all elements in this list in reversed order and every element in this list must be on a new line.
For example if the list is ['i', 'am', 'programming', 'with', 'python'] it should print out:
python
with
programming
am
i
What is the best way to do this?
def list():
    words = []
    while True:
        output = input("Type a word: ")
        if output == "stop":
            break
        else:
            words.append(output)
    for elements in words:
        print(elements)
list()

A: generic :
for(i=wordsArry.size();i--;i<0){
    pritnln(wordsArry[i]+"/n")
}

*

*Start iteration from the end of the list - last element in it.

*Then iterate backwards - decrease iterator by 1 till you reach 0.

*Print each element plus new line symbol - might depend on OS,
language.

A: In Python you can reverse a list in place by:
words = ['i', 'am', 'programming', 'with', 'python']
words.reverse()
for w in words:
    print(w)

If you want to iterate in reverse but keep the original order, you can use a slice:
for w in words[::-1]:
    print(w)

Slice syntax is [begin:end:step], where begin (incl) and end (excl) indices are omitted (get all elements) and the step -1 returns a slice with the elements in reverse order.
Both methods produce the same output.


text:
Q: Quickly interpolate missing values in R plot I would like an efficient way to plot data frames with missing values as a line plot in R, by the following rationale;

*

*NAs in first and last values are omitted completely (no line/dots)

*NAs within actual values are replaced with intermediate values for line plotting (no dots appearing)

This is an example of my data frame (edited)
df <- data.frame("time" = c(1,2,3,4,5),
             "case1" = c(NA,2,3,4,NA),
             "case2" = c(5,4,3,2,NA),
             "case3" = c(4,NA,NA,NA,2))

And this is how it's working for the first case only
library(pracma)
df$case1.i <- with(df, interp1(time, case1, time, 'linear'))
library(ggplot2)
ggplot(df, aes(time)) + geom_point(aes(case1 = case1)) + geom_line(aes(case1 = case1.i))

I'm trying to work out something to make it work for the approximately 200 columns that I have in my actual data frame. So far this code doesn't seem to be working
for (i in colnames(df)){
  argument <- paste("df$case",i,".i <- with(df, interp1(time, case",i,", time, 'linear'))")
  eval(parse(text=argument))
}

A: Read the data into a new zoo object z, apply na.approx to it to fill in the NA values within the body of the data and then plot using ggplot2. If separate panels are wanted omit facet = NULL.  Note that fortify.zoo with melt = TRUE converts the data to long form with Index, Series and Value columns and that is used in geom_point.  Omit the geom_point(...) part if you just want lines. See image at end of this answer.  The approach shown here is relatively compact and avoids pasting together and then evaluating code.
library(ggplot2)
library(zoo)

z <- read.zoo(df)
autoplot(na.approx(z), facet = NULL) +
  geom_point(aes(Index, Value, group = Series), fortify(z, melt = TRUE))

or if you want a separate plot for each column try this instead:
pdf("civy.pdf")

for(i in 1:ncol(z)) {
  p <- autoplot(na.approx(z[, i])) +
    ylab(names(z)[i]) +
    geom_point(aes(Index, Value), fortify(z[, i], melt = TRUE))
  plot(p)
}

dev.off()

A: Here are two solutions: one where all data are plotted together, differentiated by colour; another where they are plotted separately by case in different facets. The principle is much the same: I use approx to perform linear interpolation, reformat the data from wide to long for ease of plotting in ggplot2, then plot it. In the second solution, I also create a new variable called type to differentiate between interpolated and raw data.
Plotted together
# Create data frame
df <- data.frame("time" = c(1,2,3,4,5),
                 "case1" = c(NA,2,3,4,NA),
                 "case2" = c(1,2,3,4,NA),
                 "case3" = c(1,NA,NA,NA,5))

# Perform interpolation on all columns
# Switch from wide to long format
df %<>%
  mutate_at(vars(contains("case")), funs(interp = approx(time, ., xout = time)$y)) %>%
  gather(var, val, -time)

# Plot results all in one figure
g <- ggplot()
g <- g + geom_point(data = df %>% filter(!grepl("interp", var)), aes(x = time, y = val, colour = var))
g <- g + geom_line(data = df %>% filter(grepl("interp", var)), aes(x = time, y = val, colour = var))
print(g)

Plotted separately
# Create data frame
df <- data.frame("time" = c(1,2,3,4,5),
                 "case1" = c(NA,2,3,4,NA),
                 "case2" = c(1,2,3,4,NA),
                 "case3" = c(1,NA,NA,NA,5))

# Perform interpolation on all columns
# Switch from wide to long format
# Create column to indicate whether raw or interpolated
# Strip "_interp" from var
df %<>%
  mutate_at(vars(contains("case")), funs(interp = approx(time, ., xout = time)$y)) %>%
  gather(var, val, -time) %>%
  mutate(type = ifelse(grepl("interp", var), "interp", "raw"),
         var = gsub("_.*", "", var))

# Plot results all separate figures
g <- ggplot()
g <- g + geom_point(data = df %>% filter(type == "raw"), aes(x = time, y = val))
g <- g + geom_line(data = df %>% filter(type == "interp"), aes(x = time, y = val))
g <- g + facet_grid(var ~.)
print(g)

Edit with new data frame
df <- data.frame("time" = c(1,2,3,4,5),
                 "case1" = c(NA,2,3,4,NA),
                 "case2" = c(5,4,3,2,NA),
                 "case3" = c(4,NA,NA,NA,2))

df %<>%
  mutate_at(vars(contains("case")), funs(interp = approx(time, ., xout = time)$y)) %>%
  gather(var, val, -time) %>%
  mutate(type = ifelse(grepl("interp", var), "interp", "raw"),
         var = gsub("_.*", "", var))

g <- ggplot()
g <- g + geom_point(data = df %>% filter(type == "raw"), aes(x = time, y = val, colour = var))
g <- g + geom_line(data = df %>% filter(type == "interp"), aes(x = time, y = val, colour = var))
print(g)

A: You're on the right path though you have some errors in pasting up the argument you want to evaluate, on the top of my head are those:

*

*you should use paste0() to remove spaces

*you are looping over the column names but using i as a number

*And I would loop over columns that I want to interpolate only not all columns

Here's your code with the changes I mentioned above:
cols_to_interpolate <- setdiff(colnames(df), 'time')

for (col in cols_to_interpolate){
  #print(col)
  argument <- paste0("df$", col,"_i <- with(df, interp1(time, ", col,", time , 'linear'))")
  #print(argument)
  eval(parse(text=argument))
}

p <- ggplot (df, aes(x = time))
for (col in cols_to_interpolate){
    p <- p +
      geom_point(aes_string(y = col, color = shQuote(col)),  na.rm = TRUE) +
      geom_line(aes_string(y = paste0(col,"_i"), color = shQuote(col)), na.rm = TRUE)
  }
p + ylab('Y Label') + xlab('X Label')

Note: I chose this method since it was the closest to what you were trying to do, however I'm sure there is lot more efficient ways to get the end result. (Less for loops would be of-course a plus)


text:
Q: Confusion with wait and Sleep method of thread sleep() maintains the lock but wait() does not,
my thinking on wait is that it releases the lock as to give other threads a chance to acquire the monitor on that thread while he is waiting.
but having doubt with sleep() why thread maintains the lock while sleeping as it always comes to the runnable state after sleeping

A: Thread.sleep doesn't have anything to do with locking.
Object.wait needs to be called when holding a lock because the test for the condition to stop waiting needs to be done while holding the lock, in order to have a consistent view of the condition. But usually a thread isn't holding a lock while sleeping.
Sleeping while holding a lock would seem like really bad behavior. But if you need multiple locks, where you acquire one, and have to back off before retrying getting the other, then sleeping while holding a lock might make sense. If calling sleep released locks, this kind of back-off tactic would not work.
Having Thread.sleep be oblivious to locks makes the API simpler and gives the programmer more options (by not totally ruling out its use by a thread that needs to hold onto a lock).

A: why thread maintains the lock while sleeping as it always comes to the runnable state after sleeping
Consider the below scenario:-
private Object objLock = new Object();

public void myMethod() {
   ....
   synchronized(objLock) {

      Thread.sleep(1000);   // make the current running thread sleep for 1 second only.
      ... // Code here which needs to be executed immediately after 1 second sleep time
   }
   ....
}

If at all JVM relesed lock when sleep was called in the above code then when it comes back to runnable state (resumption of execution will depend on scheduling and the availability of processors on which to execute the thread as per JLS Sleep ) your program may not resume at all if another thread by chance took a lock which would make the program behaviour inconsistent. This could be one of the reasons why it doesnot release any locks.

A: Q: What does Thread.sleep(n) do?
A: NOTHING.  Absolutely nothing at all.
Q: How long does it take?
A: At least n milliseconds if the thread is not interrupted.
You don't need to know much else about Thread.sleep().


text:
Q: Get data between two tags in Python

Granular computing based
data
mining
in the views of rough set and fuzzy set

Using Python I want to get the values from the anchor tag which should be Granular computing based data mining in the views of rough set and fuzzy set
I tried using lxml
parser = etree.HTMLParser()
tree   = etree.parse(StringIO.StringIO(html), parser)
xpath1 = "//h3/a/child::text() | //h3/a/span/child::text()"
rawResponse = tree.xpath(xpath1)
print rawResponse

and getting the following output
['\r\n\t\t','\r\n\t\t\t\t\t\t\t\t\tgranular computing based','data','mining','in the view of roughset and fuzzyset\r\n\t\t\t\t\t\t\]

A: You could use the text_content method:
import lxml.html as LH

html = '''

Granular computing based
data
mining
in the views of rough set and fuzzy set

'''

root = LH.fromstring(html)
for elt in root.xpath('//a'):
    print(elt.text_content())

yields
Granular computing based
data
mining
in the views of rough set and fuzzy set

or, to remove whitespace, you could use
print(' '.join(elt.text_content().split()))

to obtain
Granular computing based data mining in the views of rough set and fuzzy set

Here is another option which you might find useful:
print(' '.join([elt.strip() for elt in root.xpath('//a/descendant-or-self::text()')]))

yields
Granular computing based data  mining in the views of rough set and fuzzy set

(Note it leaves an extra space between data and mining however.)
'//a/descendant-or-self::text()' is a more generalized version of
"//a/child::text() | //a/span/child::text()". It will iterate through all children and grandchildren, etc.

A: With BeautifulSoup:
>>> from bs4 import BeautifulSoup
>>> html = (the html you posted above)
>>> soup = BeautifulSoup(html)
>>> print " ".join(soup.h3.text.split())
Granular computing based data mining in the views of rough set and fuzzy set

Explanation:
BeautifulSoup parses the HTML, making it easily accessible. soup.h3 accesses the h3 tag in the HTML.
.text, simply, gets everything from the h3 tag, excluding all the other tags such as the spans.
I use split() here to get rid of the excess whitespace and newlines, then " ".join() as the split function returns a list.


text:
Q: Update of QTreeView without changing selection I have a model that retrieves data from a table in a database from a certain SQL query, and shows the items in a QTreeView. The characteristics are:

*

*the data comes from a table, but has an underlying tree structure (some rows are parents that have rows below them as children)

*this tree structure is shown in the QTreeView

*the children are selectable in the QTreeView (not so the parents)

*the table in the database gets updated continuously

*in the updates, a children can be added to any existing parent

*periodically (with a QTimer) the QTreeView is updated with the contents of the table

Since the children are added at any time to any parent, the first silly approach when updating the QTreeView is clearing it all, and append all the rows again, in form of parent or children, to the QTreeView.  This is a 0-order approximation, and it is indeed terrible inefficient. In particular, the following problems appear:

*

*Any existing selection is gone

*Any expanded parent showing its children is collapsed (unless ExpandAll is active)

*The view is reset to show the very first row.

What is the best solution to this problem?  I mean, the first solution I will try will be not to clear the QTreeView, but instead parse all the returned rows from the table, and check for each of them whether the corresponding item in the QTreeView exists, and add it if not.  But I wonder if there is a trickiest solution to engage a given table in a database with a QTreeView (I know this exists for a QTableView, but then the tree structure is gone).

A: This thread mentions a general approach, but this might get tricky quickly, but I am not sure how this would work if the underlying model is changing constantly (i.e. the QModelIndex becoming invalid).
Worst case is that you will have to write your own mechanism to remember the selection before updating and then re-applying it.
I assume you use some model/view implementation? You could enhance your model with a safe selection handling, in case the example mentioned above does not work for you.

A: I guess this is the case for a self-answer.
As I presumed, after a careful analysis of what data is retrieved from the database, I had to do the following "upgrades" to the retrieval code:

*

*I retrieve, along with the fields I want to show in the view, two identifiers, one for grouping rows and one for sorting items into groups

*I also retrieve the internal record ID (an increasing integer number) from the table in the database, in order to ask only for new records in the next retrieval.

In the model population code, I added the following:

*

*I first scan the initial records that may belong to existing groups in the model

*When, in the scanning, I reach the last group in the model, this implies that the rest of retrieved records belong to new groups (remember the records are retrieved sorted such that items that belong to the same group are retrieved together)

*Then start creating groups and adding items to each group, until we use all the records retrieved.

Finally, it is very important:

*

*the use beginInsertRows() and endInsertRows() before and after inserting new items in the model

*capture the sorting status of the view (with sortIndicatorSection() and sortIndicatorOrder()) and re-apply this sorting status after updating the model (with sortByColumn())

Doing that the current position and selection in the QTreeView receiving the model updates are preserved, and the items in the view are added and the view updated transparently for the user.


text:
Q: Class field in Netty ChannelInboundHandler could not autowired I try to autowire some service class in channelInboundhandler class field.
but when handler use repository field it always null.
Here is my Netty Configuration
my.netty:
  server:
    bind: 9000

@SpringBootApplication
public class NettyApplication {

  public static void main(String[] args) {
    SpringApplication.run(NettyApplication.class, args);
  }

  @Bean
  NettyServerConfig serverConfig(@Autowired ServerHandler serverHandler) {
    return NettyServerConfig.builder()
        .propertiesPrefix("my.netty.server")
        .channelInitializer(pipelineOf(loggingChannelHandler(), serverHandler))
        .build();
  }

  @Bean
  ChannelHandler loggingChannelHandler() {
    return new LoggingHandler(INFO);
  }
}

And channelinboundhandler, Service(Repository)
@Slf4j
@Component
@Sharable
public class ServerHandler extends ChannelInboundHandlerAdapter {

  @Autowired ServerRepository repository; // always null

  @Override
  public void channelRead(ChannelHandlerContext ctx, Object object) throws Exception {
    log.info("ServerHandler.channelRead()");
    String data = repository.findOne();
    log.info("data={}", data);
    ctx.writeAndFlush(object);
  }
}

@Repository
public class ServerRepository {

  public String findOne() {
    sleep(1000); // data-access time
    return "data";
  }

  private void sleep(int millis) {
    try {
      Thread.sleep(millis);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
}

Is There any Problem?


text:
Q: Dart double toStringAsFixed rounds the number, but it shouldn't I have a Flutter project, in SharedPrefs, I'm storing a double id, from a Third-part API. (so I can only get it as a double)
The id from prefs is 43449716574226770.0
I have to parse this double to a String, I'm doing it like this:
String idString = id.toStringAsFixed(0)

What I'm getting is somehow: 43449716574226768  but I'd like it to be just  43449716574226770
I have tried .toInt().toString()  too, with the same results.
The weirdest part is that it sometimes works, with other ids.

A: Can you please try this
double x=43449716574226770.0;
print(x.toString());

A: This number as long would be in a 6-byte range?
As double this with an exponent part, this might mean that the previous double (bit wise) would have a difference more than 1. Also see java Math.ulp.
This implies that using a double instead of a long maps some double IDs to the same "long" ID.
I am not sure this is the problem here, but it would explain a deviation of 2.

A: Make it id.round().toString(), it will work.


text:
Q: add a second antenna My application requires to connect through Bluetooth reliably. I have an issue is that the receiver is not always in line of sight and when not, I experiment connection drop.
I would like to have 2 antennas in 2 different direction. The chipset is CSR 8635. Is that even possible to have dual antenna?

A: No. That chip (like most) only uses a single antenna. If you added a 2nd antenna and somehow combined their signals (in the RF domain), you might improve performance in a specific direction, but you are also going to get nulls where the 2 antennas both pick up a signal and the phases are such that they cancel.
You'd really need a 2nd RF amplifier & demodulator. Alternatively just use 2 of those CSR 8635 ?


text:
Q: Markov chain having unique stationary distribution Let be a finite time homogeneous Markov chain with $P_{n \times n}$ transition matrix. As far as I know, $P$ has a unique stationary distribution if and only if it has a unique recurrent class (***).
So, let's take:
$$P=\begin{pmatrix} 3/4&0&1/4 \\ 1/3&1/2&1/6 \\ 1&0&0 \end{pmatrix}$$
State $2$ is transient, so the chain can't have a unique recurrent class, right?
Now, if I calculate a stationary vector $\pi = (a, b, c)$ by $(a \ b \ c)P=(a \ b \ c)$, I find only one such vector $\pi = (34/5, 0, 1/5)$.
Isn't there a contradiction with statement (***) ?
I'm quite worried because there's obviously something I don't understand... but what the hell am I not understanding ?

A: This is an absorbing Markov chain, i.e. there exists a state $i$ such that $\mathbb P(X_n = i \mid X_0=1)=1$ for all $n>0$. For clarity of notation I'll swap columns $0$ and $2$ to write
$$
P = \left(
\begin{array}{ccc}
 \frac{1}{4} & 0 & \frac{3}{4} \\
 \frac{1}{6} & \frac{1}{2} & \frac{1}{3} \\
 0 & 0 & 1 \\
\end{array}
\right)=\begin{pmatrix} Q & R \\ \mathbf 0 & I\end{pmatrix}
$$
where $Q$ is the substochastic matrix obtained from $P$ by considering transitions betweeen transient states, $R$ that obtained from $P$ by considering transitions from a transient state to an absorbing state, $\mathsf 0$ that obtained by considering transitions from absorbing states to transient states, and $I$ that obtained by considering transitions between absorbing states (which with reordering of states can be written as the identity matrix with dimension the number of absorbing states).
By definition, a stationary distribution $\pi$ for a Markov chain is a row vector $\pi$  satisfying $\sum_i=1$ with $\pi>0$ and $\pi P=\pi$. Iteratively this would imply that $\pi P^n=\pi$ for all positive integers $n$, but as state $2$ is absorbing and $P_{02}$ and $P_{12}$ are positive, for any distribution $\pi$ there exists some positive integer $N$ such that $\pi P^n=\begin{pmatrix} 0 & 0 & 1\end{pmatrix}$ for $n\geqslant N$, meaning there can be no stationary distribution for this Markov chain.
In general, stationary distributions for finite Markov chains exist if and only if the chain is irreducible, in which case the stationary distribution is unique if and only if the chain is aperiodic (this is a good exercise to prove).
Edit: The above answer is considering (positive) recurrent Markov chains. As shown in this answer, $\begin{pmatrix} 0 & 0 & 1\end{pmatrix}$ is a valid stationary distribution for $P$.


text:
Q: something wrong in an edge case for chessboard? There's a combination of three features in chessboard that's doing something unexpected (typesetting some characters in nullfont):  curvemove, marking a not-in-a-single-file move, and a non-integer boardfontsize.  Any ideas for workarounds to avoid shedding these characters?
\documentclass{article}

% Running this code generates nullfont characters.  From the log:
%    Missing character: There is no . ("2E) in font nullfont!
%    Missing character: There is no 7 ("37) in font nullfont!
%    Missing character: There is no 5 ("35) in font nullfont!

\usepackage{chessboard}
\begin{document}
  \chessboard[
    pgfstyle=curvemove,   % with pgfstyle=straightmove, the problem goes away.
    boardfontsize=9.75pt, % with boardfontsize=10pt, the problem goes away.
    markmoves={a2-b3}     % with markmoves={a2-a4} or {a2-a3}, the problem goes away.
    % Note:  with markmoves={a2-b2,a2-c2,a2-d2,a2-f2}, a version of the issue persists
    %        (typesetting ".25" or ".5" or ".75" in nullfont), though markmoves={a2-e2}
    %        seems totally fine (possibly because of divisibility by four).
  ]
\end{document}

A: You can try the following patch. The next chessboard version will then contain it.
\documentclass{article}

% Running this code generates nullfont characters.  From the log:
%    Missing character: There is no . ("2E) in font nullfont!
%    Missing character: There is no 7 ("37) in font nullfont!
%    Missing character: There is no 5 ("35) in font nullfont!

\usepackage{chessboard,etoolbox}
\ExplSyntaxOn
\makeatletter
\newcommand\board@divide@NN[2]{%
 \dim_set:Nn#1 {#1*\dim_ratio:nn{1pt}{#2}}}%
\ExplSyntaxOff

\patchcmd\board@pgf@extractangle
  {\divide \len@board@tempy by \strip@pt\len@board@tempx\relax}
  {\board@divide@NN\len@board@tempy\len@board@tempx}{}{\fail}
\makeatother

\begin{document}

  \chessboard[
    pgfstyle=curvemove,   % with pgfstyle=straightmove, the problem goes away.
    boardfontsize=9.75pt, % with boardfontsize=10pt, the problem goes away.
    markmoves={a2-b3}     % with markmoves={a2-a4} or {a2-a3}, the problem goes away.
    % Note:  with markmoves={a2-b2,a2-c2,a2-d2,a2-f2}, a version of the issue persists
    %        (typesetting ".25" or ".5" or ".75" in nullfont), though markmoves={a2-e2}
    %        seems totally fine (possibly because of divisibility by four).
  ]
\end{document}


text:
Q: How to create the SAMLAuthenticationToken and send it to the SAML authentication provider I've configured the SAML extension in my application, and I want to authenticate an user. The flow that I implemented is the following:

*

*Getting the user credentials (username and password) from a rest service.

*Configuring application to use SAMLAuthenticationProvider.

*Building a SAMLAuthenticationToken object to be sent to the SAMLAuthenticationProvider.

*Building the SAMLMessageContext which will be inyected to SAMLAuthenticationToken.

But I've not been able to build the SAMLMessageContext object which I guess that will wrap the user credentials (among other data) that I got from the rest service.
Does anybody know how to build this object?. or if is the flow correct?
thanks.

A: You do not provide credentials to your SP when using SAML authentication. Credentials are only presented to the IDP during authentication. So the flow is incorrect.
Good starting points to learn more are SAML 2.0 wiki page, SAML 2.0 standard itself and the Spring SAML manual. This issue has also been discussed couple of times here on Stackoverflow, so you can find more in old questions.


text:
Q: Bluetooth Into service I am trying to establish a connection between my phone and bluetooth card within service in android, But i have a problem with service. Service does an auto restart after half an hour. My goal is to keep my service running as long as possible.
public void onCreate() {
Log.d("PrinterService", "Service started");

  super.onCreate();
 }

@Override
public IBinder onBind(Intent intent) {

 return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("PrinterService", "Onstart Command");
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter != null) {

    if(bluetoothProvider != null)
        bluetoothProvider = null;

        bluetoothProvider = new BluetoothProvider(getApplicationContext());
        bluetoothProvider.startUpdates();
}

return Service.START_STICKY ;
}

@Override
public void onDestroy() {
super.onDestroy();
}

A: You should create a sticky service.
You can do this by returning START_STICKY in onStartCommand.
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.i("LocalService", "Received start id " + startId + ": " + intent);
    // We want this service to continue running until it is explicitly
    // stopped, so return sticky.
    return START_STICKY;
}

Read also about application:persistent which is "Whether or not the application should remain running at all times". This is more troublesome - System will try not to kill your app which will effect others in the system, you should be careful using it.
refer following link:
https://stackoverflow.com/a/15038770/3110609


text:
Q: Glide custom adapter cannot access Fragment I'm trying to store the images on firebase storage and then retriving them and set into the recycler view. Using Glide I get this error, don't know how to fix it. Anyway If there is another way to retrieve and set image it's ok for me.
C:\Users\Gian\AndroidStudioProjects\RememberMe\app\src\main\java\com\example\rememberme\CustomAdapter.java:64: error: cannot access Fragment
            Glide.with(context).load(dataSet.get(listPosition).getAnime_image_url()).into(holder.image);
                 ^
      class file for android.support.v4.app.Fragment not found

This is my onbindview:
@Override
    public void onBindViewHolder(final MyViewHolder holder, final int listPosition) {
        Glide.with(context).load(dataSet.get(listPosition).getAnime_image_url()).into(holder.image);
        holder.anime_eng_name.setText(dataSet.get(listPosition).getAnime_eng_name());

        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putSerializable("toanimeelementfullbymainactivity", (Serializable) dataSet.get(listPosition));
                Intent intent = new Intent(context, AnimeElement.class);
                intent.putExtras(bundle);
                context.startActivity(intent);
            }
        });
    }

A: Solved updating the Glide versione and Gradle.


text:
Q: Modify The Following Matlab Parfor Loop In the following parfor loop, Matlab says the variable 'sf' cannot be classified. However, the way it is defined inside the innermost loop doesn't seem to affect parfor. Could you tell me the issue and show me how this code snippet should be modified?
parfor ii=1:1:10000
    for jj=1:200
        for kk=1:80
            sf{kk}=fit([kk*dKy;(kk+1)*dKy],[result{kk}(ii);result{kk+1}(ii)],'exp1','lower',[kk*dKy,result{kk}(ii)]);
            fun=@(t) sf{kk}(t).*cos(Ky(kk).*t);
            result2{ii}(jj)=0;
            result2{ii}(jj)=result2{ii}(jj)+integral(fun,Ky(kk),Ky(kk+1),'ArrayValued',true)/(2*pi);
        end
    end
end


text:
Q: MySql optimizer doesn't use the index on varchar I have a table defined as
CREATE TABLE `article` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `field1` varchar(1024) NOT NULL,
  `priority` int(11) NOT NULL,
  `prodcode` varchar(64) NOT NULL,
  `status` int(8) NOT NULL,
  `error` varchar(1024) DEFAULT NULL,
  `ctime` datetime DEFAULT CURRENT_TIMESTAMP,
  `mtime` datetime DEFAULT NULL,
  `event` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `article_prodcode_idx` (`prodcode`),
  KEY `article_status_idx` (`status`),
  KEY `article_priority_idx` (`priority`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

This table contains about 40 million of record.
When I run a query like
SELECT * FROM article WHERE prodcode='a-4536-x-bef45-green';

the optimizer "decides" that such query doesn't have to use any index (an "EXPLAIN SELECT..." results in a
+----+-------------+----------+------+---------------+------+---------+------+----------+-------------+
| id | select_type | table    | type | possible_keys | key  | key_len | ref  | rows     | Extra       |
+----+-------------+----------+------+---------------+------+---------+------+----------+-------------+
|  1 | SIMPLE      | article  | ALL  | NULL          | NULL | NULL    | NULL | 39415251 | Using where |
+----+-------------+----------+------+---------------+------+---------+------+----------+-------------+

If I add e.g. another field like priority or status, the optimizer uses just such indexes, but NOT the article_prodcode_idx one. The problem is that the query scans the whole 40 million records, and the result comes after 100 seconds. Why the index is not used there?
I checked this answer too: MySQL partial indexes on varchar fields and group by optimization but I didn't find any answer to my problem. What should I do to let the query return results... quickly?
Thank you

A: After a deep check, I solved the problem. In some ways, I did a mistake in describing the problem. In fact, in my script, I had something like
SET @pc='a-4536-x-bef45-green';
...
SELECT * FROM article WHERE prodcode=@pc;

while in some other points I had
SELECT * FROM article WHERE prodcode='a-4536-x-bef45-green';

In the first case, no indexes are used. In the second one, everything works as expected.
This is the explain of the first query:
EXPLAIN FORMAT=JSON SELECT * FROM article WHERE prodcode=@pc;
{
  "query_block": {
  "select_id": 1,
  "table": {
    "table_name": "article",
    "access_type": "ALL",
    "rows": 39498773,
    "filtered": 100,
    "attached_condition": "(convert(`shop`.`article`.`prodcode` using utf8mb4) = (@`pc`))"
    }
  }
}

And this is the second one
EXPLAIN FORMAT=JSON SELECT * FROM article WHERE prodcode='a-4536-x-bef45-green';

{
"query_block": {
  "select_id": 1,
  "table": {
    "table_name": "article",
    "access_type": "ref",
    "possible_keys": [
      "article_prodcode_idx"
    ],
    "key": "article_prodcode_idx",
    "used_key_parts": [
      "prodcode"
    ],
    "key_length": "194",
    "ref": [
      "const"
    ],
    "rows": 2,
    "filtered": 100,
    "index_condition": "(`shop`.`article`.`prodcode` = 'a-4536-x-bef45-green')"
    }
  }
}

I tried a lot of times, using e.g.
SELECT * FROM article WHERE prodcode in (@pc, 'another code');

but the result is always the same: if a variable is involved, NO indexes are used.
Knowing, that, I changed my scripts in order to not use SET anymore, and everything started running fine.
I still would like to know why... but at least the problem is solved.


text:
Q: Collision point detection and location between two objects in Java game(LWJGL) as the typical "Hello World" for game development I decided to make the pong game since I am learning to use LWJGL.
As of now, I already have both my entities ready (bat and ball), but the ball just runs back and forth on the x-axis. I obviously want it to hit the bat and run on different angles depending on how it was hit. The issue is I can detect the collision between both entities, but I have no idea how to tell at what point did the ball collide with the bat. Is there a specific algorithm, function or even a second library that can help me?
Thank you very much!
Edit: as requested, this is the code for the current collision detection that I have
    if(ball.getX()<=bat.getX()+bat.getWidth() && ball.getX() >= bat.getX() &&
        ball.getY()>=bat.getY() && ball.getY()<=bat.getY()+bat.getHeights()){
        //for now, the code in here just makes the ball go the opposite direction
    }

A: How are you detecting collisions?  I would think that if you are able to detect collisions, it would be because you know the position of the ball and the bat.
Edit:
OK, I have not done this exact type of program before, if it is a Hello World program, for simplicity's sake you may want to just have the bat and the ball just have a point location and the if statement would be
if(ball.getX() == bat.getX() && ball.getY() == bat.getY()){
    //for now, the code in here just makes the ball go the opposite direction
}

If you really want a bat with a width, you could do something like
double xDist = ball.getX() - bat.getX();
double yDist = ball.getY() - bat.getY();
if(xDist * xDist + yDist * yDist <= BAT_WIDTH * BAT_WIDTH) {
    //use trigonometry to find the angle between the ball and the mid point of the bat, and then find the point on the bat's surface that corresponds to that angle
}


text:
Q: Combinatorial design difference set proof: adding 0 to Paley difference set Suppose $D$ is the $(4t-1,2t-1,t-1)$-difference set obtained from the following theorem:
Suppose $v$ is a prime power congruent to $3\bmod 4$.  Let $v=4t-1$. Then there is a $(4t-1,2t-1,t-1)$-difference set (also called a Paley difference set).
For some prime power $4t-1$: Prove that $D \cup \{0\}$ is a $(4t-1,2t,t)$-difference set.

A: I think you mean $D\cup\{{0\}}$, not $D\cap\{{0\}}$.
Let's look at an example, $t=2$. Then if I understand your notation, we are working modulo $4t-1=7$, and we have a set with $2t-1=3$ elements, and every non-zero number comes up $t-1=1$ time as a difference. An example would be the set $D=\{{1,2,4\}}$, where we get the differences $1=2-1$, $2=4-2$, $3=4-1$, $4=1-4$, $5=2-4$, and $6=1-2$.
Now let's take the union with zero, $\{{0,1,2,4\}}$. The size of the set is now $2t=4$, and we get the new differences $1=1-0$, $2=2-0$, $3=0-4$, $4=4-0$, $5=0-2$, and $6=0-1$, so now every nonzero number comes up $t=2$ times as a difference.
So the thing you have to understand is why when you look at the numbers $d-0$ and $0-d$ for $d$ in $D$ you get each nonzero number exactly once. That has something to do with the special nature of prime powers congruent to $3$ modulo $4$, and the special nature of the Paley difference sets. So, do you understand how the Paley sets are constructed?


text:
Q: Get noNameSpaceSchemaLocation from xml file I'm trying to read a xml-file with it's schema.
My xml file looks like this:
<?xml version="1.0" encoding="utf-8"?>
<PersonList
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="D:\MySchema.xsd">

Now I'm reading the xml file like this:
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema;
settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;

using (XmlReader reader = XmlReader.Create("MyXmlFile.xml", settings))
{
    while(reader.Read())
    //.....
}

private static void ValidationCallBack(object sender, ValidationEventArgs args)
{
    if (args.Severity == XmlSeverityType.Warning)
    Console.WriteLine("\tWarning: Matching schema not found.  No validation occurred." + args.Message);
    else
    Console.WriteLine("\tValidation error: " + args.Message);

}

The problem is that when the schema 'D:\MySchema.xsd' is not found, it's still reading the xml so noNamespaceSchemaLocation is useless...
So I've set the Schema path in my code like this:
settings.Schemas.Add(null, "D:\\MySchema.xsd");

And now it's reading the xml file by using the schema, but I'm setting here the schema path hardcoded...
I want to get the schema path (noNamespaceSchemaLocation) from the xml file and add the schema to the settings depending on the schema from the xml file. By doing it like this, I can also check if the Schema exists or not.
To make it clear: How can I get the noNamespaceSchemaLocation from a xml file?

A: xsi:noNamespaceSchemaLocation="anyURI"
You probably need to specify the location as a uri, so something like file://d:/myschema.xsd

A: Why can't the framework load the value of noNamespaceSchemaLocation attribute as it is the standard attribute defined for the class? Could be an enhancement to XML library to load the noNamespaceSchemaLocation attribute value to some property under Schemas so that it will be easier for developer to extract the value and check if the file exists or not and proceed to validate the Xml.


text:
Q: Label data within Barplot ggplot2 based on 3rd variable Already seen here and here but still getting error.
I am trying to label my bars with ratios by customer type:
Here is the dput()output:
    structure(list(word = c("broadband", "broadband", "broadband",
"call", "call", "call", "cheaper", "cheaper", "cheaper", "customer",
"customer", "customer", "internet", "internet", "internet", "line",
"line", "line", "price", "price", "price", "reliable", "reliable",
"reliable", "service", "service", "service", "speed", "speed",
"speed"), word_cust_props = c(0.395536562203229, 0.36372269705603,
0.240740740740741, 0.486218302094818, 0.383682469680265, 0.130099228224917,
0.361738148984199, 0.535553047404063, 0.102708803611738, 0.45317483328501,
0.327051319222963, 0.219773847492027, 0.386215864759428, 0.360208062418726,
0.253576072821847, 0.403946002076843, 0.407061266874351, 0.188992731048806,
0.367229608336328, 0.435501257635645, 0.197269134028027, 0.178432893716059,
0.245151280062064, 0.576415826221877, 0.315767973856209, 0.251429738562091,
0.432802287581699, 0.383040935672515, 0.333333333333333, 0.283625730994152
), NPS_Level = c("Detractor", "Passive", "Promoter", "Detractor",
"Passive", "Promoter", "Detractor", "Passive", "Promoter", "Detractor",
"Passive", "Promoter", "Detractor", "Passive", "Promoter", "Detractor",
"Passive", "Promoter", "Detractor", "Passive", "Promoter", "Detractor",
"Passive", "Promoter", "Detractor", "Passive", "Promoter", "Detractor",
"Passive", "Promoter")), class = c("grouped_df", "tbl_df", "tbl",
"data.frame"), row.names = c(NA, -30L), vars = list(word, NPS_Level), drop = TRUE, .Names = c("word",
"word_cust_props", "NPS_Level"), indices = list(0L, 1L, 2L, 3L,
    4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L,
    17L, 18L, 19L, 20L, 21L, 22L, 23L, 24L, 25L, 26L, 27L, 28L,
    29L), group_sizes = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L), biggest_group_size = 1L, labels = structure(list(
    word = c("broadband", "broadband", "broadband", "call", "call",
    "call", "cheaper", "cheaper", "cheaper", "customer", "customer",
    "customer", "internet", "internet", "internet", "line", "line",
    "line", "price", "price", "price", "reliable", "reliable",
    "reliable", "service", "service", "service", "speed", "speed",
    "speed"), NPS_Level = c("Detractor", "Passive", "Promoter",
    "Detractor", "Passive", "Promoter", "Detractor", "Passive",
    "Promoter", "Detractor", "Passive", "Promoter", "Detractor",
    "Passive", "Promoter", "Detractor", "Passive", "Promoter",
    "Detractor", "Passive", "Promoter", "Detractor", "Passive",
    "Promoter", "Detractor", "Passive", "Promoter", "Detractor",
    "Passive", "Promoter")), class = "data.frame", row.names = c(NA,
-30L), vars = list(word, NPS_Level), drop = TRUE, .Names = c("word",
"NPS_Level")))

This is what I have tried:
    words_without_sw%>%

  mutate(position = cumsum(word_cust_props) - 0.5*word_cust_props)%>%
  ggplot(aes(word, word_cust_props,fill=NPS_Level)) +
  geom_bar(stat="identity") +
  coord_flip() +
  geom_text(aes(label = sprintf("%1.2f%%", 100*word_cust_props), y = position),colour = "white")+
  theme(plot.background = element_rect(fill = 'white'),
        legend.position = "top",
        axis.text.y=element_text(size=14, color="#6400aa",face = "bold"),
        axis.text.x=element_text(size=12,color="#6400aa",face = "bold"),
        plot.title = element_text(color="#6300aa", face="bold", size=20, hjust=0),
        strip.text.x = element_text(size = 17, face = "bold",colour = "blue"),
        legend.text=element_text(size=17,face = "bold"),
        legend.title = element_text(size=17,face = "bold")) +
  labs(x = "",
       y = "word proportions by customer type",
       title = "Top 10 words by customer type",
       subtitle = "Calc. by taking the word count and proportions by customer type",
       fill="")+
  scale_fill_manual(labels = c("Detractor","Passive","Promoter"), values = c("#E60014", "#333333","#14AA37"))

But the labels are still jumbled together. Like this:
Not sure what I am doing wrong ???

A:     words_without_sw%>%
 ggplot(aes(word, word_cust_props,fill=NPS_Level,label = sprintf("%1.2f%%", 100*word_cust_props))) +
  geom_bar(stat="identity") +
  coord_flip() +
  geom_text(size = 3, position = position_stack(vjust = 0.5),colour = "white")+
  theme(plot.background = element_rect(fill = 'white'),
        legend.position = "top",
        axis.title.y = element_blank(),
        axis.title.x = element_text(color="#6300aa", face="bold", size=14),
        axis.text.y=element_text(size=14, color="#6400aa",face = "bold"),
        axis.text.x=element_blank(),
        plot.title = element_text(color="#6300aa", face="bold", size=20, hjust=0),
        strip.text.x = element_text(size = 17, face = "bold",colour = "blue"),
        legend.text=element_text(size=17,face = "bold"),
        legend.title = element_text(size=17,face = "bold")) +
  labs(x = "",
       y = "",
       title = "Top 10 words by customer type",
       subtitle = "Calc. by taking the word count and proportions by customer type",
       fill="")+
  scale_fill_manual(labels = c("Detractor","Passive","Promoter"), values = c("#E60014", "#333333","#14AA37"))


text:
Q: MS office files downloaded from gmail are not opened when i download any office file (doc, ppt, xls) from g-mail or any other website they dont open and error msg is displayed that the file is corrupted. i have re-installed MS Office but the problem is still there.

A: Error when opening MS office files downloaded from gmail

They don't open and an error message  is displayed that the file is corrupted.

You need to disable "Protected View" for downloaded files. See below for instructions on how do this.

Can't open excel and powerpoint files downloaded from Internet

I have problem opening excel and powerpoint files downloaded from the Internet using my Office 2010.  Error messages - "file corrupted" (but it can't be that all files are corrupted)?

...

If you are using Office 2010, you need to check your settings in the
  Trust Center.

*

*Go to File -> Options -> Trust Center -> Trust Center Settings -> Protected View.

*Make sure the first box is NOT checked.

Source Can't open excel and powerpoint files downloaded from Internet
Note:

*

*You may also have to uncheck the other two boxes in the "Protected View" section.

Further reading

*

*What is Protected View?


text:
Q: angular route not working, throw page not found error in index.html
<script src="lib/angular.min.js"></script>
<script src="lib/angular-route.min.js"></script>

controller
angular.module("testCtrl",[]).controller('TestController', ["$scope", function($scope) {
    $scope.Myname = "my first route";
}]);

app.js
var app = angular.module('testApp',["ngRoute", "testCtrl"]);

app.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
    $routeProvider

        .when("/",{
            templateUrl: "Views/main.html"
        })
        .when("/details",{
            templateUrl: "Views/details.html",
            controller : TestController
        })
        .otherwise({
            redirectTo : "/"
        });
}]);

my homepage loads fine but with some reason /details show error like --- No webpage was found for the web address: http://127.0.0.1:8080/details
I am new to angular and I am learning. I am not able to understand whats wrong ..do we have any tools to debug route error? I am using angular 1.5.8 version for now.
server console - "GET /details" Error (404): "Not found"

A: The issue is that TestController isn't defined in app.js. You should use the controller name as a string, like so.
    .when("/details",{
        templateUrl: "Views/details.html",
        controller : "TestController"
    })

See this plunk for a working example.
https://plnkr.co/edit/xi20MmchJY6TO1SG2o0d?p=preview

A: I think you have omitted the dependency on ngRoute:
angular.module('testCtrl', ['ngRoute'])...

Are you referencing ng-app in your HTML as well (can't see your HTML code)
Presumably you have included your scripts in the HTML page too?


text:
Q: Build a specific querystring from an array of results In php I have the following array:
$car[] = array ("id"=>"1", "brand"=>"Audi", "price"=>"7000");
$car[] = array ("id"=>"9", "brand"=>"Merc", "price"=>"9000");

With this array I would like to build the following query string:
&brand0=Audi&brand1=Merc&id0=1&id1=9&price0=7000&price0=9000

How can I go about doing this?
Please note that the array may have more results than just the 2 rows, and so that the built querystring should be able to cope with it (also the results being used in this example may vary).
Thanks

A: As alternative you could use http_build_query. And to further simplify I would propose:
$url = http_build_query(array("car" => $car));

Which will result in such an URL parameter list instead:
&car[0][brand]=Audi&car[1][brand]=Merc&car[0][id]=1&car[1][id]=9&car[0][price]=7000&car[1][price]=9000

Which looks odd, but allows PHP to reconstruct your two arrays as-is.

A: Loop through the array, and put key-value pairs in another array. Then finally implode the array. Something like:
$data = array();
$i = 0;
foreach ($car as $k=>$v)
{
   $data[] = $k . '_' . $i .'=' . $v;
   $i++;
}
echo implode('&', $data);

I usually use implode because AFAIK it's faster than $data +=.
EDIT
Actually, that one above works for only 1 array. Here is for multiple arrays:
$data = array();
$i = 0;
foreach ($car as $c)
{
   foreach ($c as $k=>$v);
      data[] = $k . '_' . $i . '=' . $v;
   $i++;
}
echo implode ('&', $data);

A: Perhaps not the most elegant way.
$str = "";
foreach($car as $key => $val){
    $str .= "$key=$val&";
}
$str = substr($str, 0, strlen($str) - 2);

A: $params = array();
for($i=0;$i<count($car);$i++) {
    $params[] = 'id' . $i . '=' . $car[$i]['id'];
    $params[] = 'brand' . $i . '=' . $car[$i]['brand'];
    $params[] = 'price' . $i . '=' . $car[$i]['price'];
}
$string = implode('&', $params);

This will go through, and create the keys with the number on them, and then glue it all together at the end to give you the $string that you were wanting. It will also, just for cleanliness, not have an extra & at the start or end that you might get if you simply append.


text:
Q: Private method or inner class, which one to use If I have the following class
    public class Foo {
       public void bar(){
           fooBar();
       }
       private void fooBar(){
           System.out.println("text...");
       }
    }

instead I can also do something like
    public class Foo {

        public void bar() {
             new inner().fooBar();
        }

        private class inner {
             private void fooBar() {
                   System.out.println(" text ...");
             }
        }

    }

when should I use inner classes instead of private method? If the functionality is specific to the class Foo then it make sense to use an inner class but the same can also be achieve d through private method which can only be accessed within the class itself.

A: For your example, you don't need an inner class. Your first solution is simple, easy-to-read, and sufficient.
An inner class is useful when:

*

*You need to implement an interface, but don't want the outer class to implement it.

*There can be more than one instance of the class.

*There can be more than one type of the inner class.

EDIT: Examples of each, by request

*

*An interface might be implemented by an inner class to implement the Iterator pattern, or a Runnable, ...

*Multiple instances of an inner class could be necessary to implement an iterator, or a special key type to an internal map, ...

*Multiple types of inner classes might be necessary for the Strategy pattern, ...


text:
Q: Visual Studio error "Invalid attempt to read when reader is closed" when trying to authenticate login credentials in login form. C# MySQL I am trying to create a login form that will authenticate the user's credentials before letting them proceed to another form. I am getting an error message where it says "invalid attempt to read when reader is closed"
Error Message
Code:
private void btn_Login_Click(object sender, EventArgs e)
        {
            sqlConnection.ConnectionString = "server=" + server + ";" + "username=" + username + ";" + "password=" + password + ";" + "database=" + database;

            sqlConnection.Open();
            sqlCommand.Connection = sqlConnection;

            sqlCommand.CommandText = "Select tunapunaboysrc.addregister.Username, tunapunaboysrc.addregister.Password  "
            + "from tunapunaboysrc.addregister";

            sqlDataReader = sqlCommand.ExecuteReader();
            sqlData.Load(sqlDataReader);

            dg_Login.DataSource = sqlData;

             if (sqlDataReader.Read() == true)
             {
                 new frmDashboard().Show();
                 this.Hide();
             }

             else
             {
                 MessageBox.Show("Invalid Username or Password, Please Try Again", "Login Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
                 txtbx_username.Text = "";
                 txtbx_password.Text = "";
                 txtbx_username.Focus();
             }

            sqlDataReader.Close();
            sqlConnection.Close();

            new frmDashboard().Show();
            this.Hide();
        }

I also use this at the beginning also, incase if its needed.
public partial class frmLogin : Form
    {

        MySqlConnection sqlConnection = new MySqlConnection();
        MySqlCommand sqlCommand = new MySqlCommand();
        DataTable sqlData = new DataTable();
        MySqlDataAdapter SqlAdapter = new MySqlDataAdapter();
        DataSet sqlSet = new DataSet();
        MySqlDataReader sqlDataReader;

        String server = "localhost";
        String username = "root";
        String password = "cybers";
        String database = "tunapunaboysrc";

Can someone help me figure out why my reader is closing, and how i can solve it?
i tried pasting the authentication code

             if (sqlDataReader.Read() == true)
             {
                 new frmDashboard().Show();
                 this.Hide();
             }

             else
             {
                 MessageBox.Show("Invalid Username or Password, Please Try Again", "Login Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
                 txtbx_username.Text = "";
                 txtbx_password.Text = "";
                 txtbx_username.Focus();
             }


text:
Q: Creating a route with two optional parameters I am working with react router. Initially I two different components being rendered under the same route one with a parameter and one without(this is how the routes were differentiated). Now I am trying to add optional parameters to the first route while not editing the second one route. The issue is there is no way to tell the difference between the first route and the second.
For example:
Initially my routes looked like this:
<Route exact={true} path="/encounter-monitor" component={EncounterMonitor} />
<Route
    exact={true}
    path="/encounter-monitor/:encounterID"
    component={EncounterMonitorDetails}
/>

And with my update it now looks like:
<Route
   exact={true}
   path="/encounter-monitor/:queryData?"
   component={EncounterMonitor}
/>
<Route
    exact={true}
    path="/encounter-monitor/:encounterID"
    component={EncounterMonitorDetails}
/>

I tried editing the 2nd route name but this is causing issue for users on the site using links to the old paths. So I am trying to figure out if there is anyway to have two components rendered by the same route depending out the contents of the optional parameter? Or if theres a way to append an optional part of the route that is not a part of the query? for example I was trying something like this for the first route:
<Route
   exact={true}
   path="/encounter-monitor/search?/:queryData?"
   component={EncounterMonitor}
/>

Adding search as an optional part of the path but this doesnt work either. Does anyone have any suggestions on how to handle this? I want the base route to always be /encounter-monitor/

A: if the parameters are different you can try using regex to validate the route
for example suppose your id is numeric and your query alphanumeric
<Route
    exact={true}
    path="/encounter-monitor/:encounterID([0-9]+)"
    component={EncounterMonitorDetails}
/>
<Route
   exact={true}
   path="/encounter-monitor/:queryData?"
   component={EncounterMonitor}
/>

that way if the parameter has only numbers you show a route if it contains letters and numbers you show another
you can do validation tests on
https://pshrmn.github.io/route-tester/#/
more examples
https://github.com/pillarjs/path-to-regexp


text:
Q: Black bars on Eclipse after upgrading to Kubuntu 15.10 I just upgrade my desktop to Kubuntu 15.10 from Kubuntu 15.04, and I bizarre issue started happening in Eclipse. Looks like the divisors on software are black bars, instead of the desktop color for some reason. Below you can see two images with examples of that. As for configurations I'm using?
Workspace Theme: Breeze
Desktop Theme: Air
Widget Style: Breeze
Windows Decoration: air-breeze
GTK2 theme: oxygen-gtk
GTK3 theme: oxygen-gtk
Icon theme: Breeze


text:
Q: horizontal ul menu not displaying correctly in IE - Getting Squashed I'm having a problem with a horizontal UL menu im trying to make see screenshots...
In Chrome it works perfectly fine:

Where as in IE-8 it looks like this:

Here is the code I have:

 Google

 Google

 Google

 Google

 Google

and the CSS:
.horizontal-menu {
    width: 440px;
}

.horizontal-menu li {
    display: inline;
    list-style-type: none;
    padding-left: 40px;
}

Any clues guys?
Really baffling me now :p cheers
Nick

A: .horizontal-menu { white-space: nowrap }

Will force the li-elements to stay in one line.
This should fix the unexpected linebreak, if you want to have the paddings that way.
* { margin:0; padding: 0 }

Could fix several browser inconsistency. Or integrate a CSS reset

To center the navigation across all browsers, you can remove the width from .horizontal-menu and set it display: inline and center it via margin: 0 auto:
.horizontal-menu {
    display: inline;
    margin: 0 auto;
}

Explanation:
margin: 0 auto; >> top/bottom margin
margin: 0 auto; >> left/right margin.


text:
Q: PHP 7.3.30 extension not enabling I was using php version of v7.0.0 which I upgraded it to version of 7.3.30 with getting help from this answer.
This is working fine except facing below issue -

*

*Getting PHP error as Message: Call to undefined function openssl_encrypt().

I tried -

*

*Uncomment the extension=php_openssl.dll in php.ini file

*Also, uncommented it from phpForApache.ini file

*libeay32.dll and ssleay32.dll was not present in installation folder. I have downloaded the latest version and placed inside wamp64\bin\php\php7.3.30

*Even though, openssl is enabled from ini, when I tried print_r(get_loaded_extensions()), I din't see openssl extension.

Still getting the same error.
I have also observed few things like -
My phpinfo() is showing -
Configuration File (php.ini) Path:
Loaded Configuration File:         C:\wamp64\bin\php\php7.3.30\php.ini
Scan for additional .ini files in: (none)
Additional .ini files parsed:      (none)

Any help to resolve this openssl_encrypt() issue is appreciated.

A: Got the cause of the issue.
After the php upgrade, I missed to update Environment Variable for PHP path.
I simply updated the Path variable with newer version of php from C:\wamp64\bin\php\php7.0.0 to C:\wamp64\bin\php\php7.3.30
This solves my problem. May be this will help someone.


text:
Q: CLI Tizen build-web displays Invalid Password error I'm trying to build a tizen web application for a Samsung Active 2 smartwatch from CLI (Arch linux) and I keep getting this error:
[ERROR] Main.java(195) - org.tizen.common.sign.exception.CertificationException: Invaild password

I've followed this manual: Tizen CLI manual
The command I use to build the package is:
tizen package -t wgt -s CertificateName  -- .

Where CertificateName is the name of my already existing certificate that I created using also the CLI with the command:
tizen certificate -a CertificateName -p password -n Name -e fake@email.com

After generating the certificate I've added to the security profiles using the command:
tizen security-profiles add -n author -a /home/user/tizen-studio-data/keystore/author/author.p12 -p password

And after it, I've added the Trust Anchor to the project with the command:
tizen trust-anchor set -c /home/user/tizen-studio-data/keystore/author/author.p12 -s true -- projectfolder

How can I fix the Invalid Password error?
Thanks!

A: When you call tizen package, the app checks the certificates' entries of the default profile.xml file that you set. It should look like this:
<profileitem ca="<tizen>/tools/certificate-generator/certificates/developer/tizen-developer-ca.cer" distributor="0" key="<tizen-data>/keystore/author/<cert>.p12" password="<tizen-data>/keystore/author/<cert>.pwd" rootca=""/>

<profileitem ca="<tizen>/tools/certificate-generator/certificates/distributor/tizen-distributor-ca.cer" distributor="1" key="<tizen>/tools/certificate-generator/certificates/distributor/tizen-distributor-signer.p12" password="<tizen-data>/tools/certificate-generator/certificates/distributor/tizen-distributor-signer.pwd" rootca=""/>

Actually, the passwords aren't stored in the *.pwd files but in the Login keyring of gnome-keyring. In order to retrieve the passwords previously stored by calling tizen security-profiles add, tizen package calls:
<tizen>/tools/certificate-encryptor/secret-tool lookup --label=tizen-studio.
You'll see by using the command above that you'll have an error giving more information than tizan package. In your case, gnome-keyring may not be installed or the Login keyring may not be correctly initialized.
SOLUTION #1
To resolve the issue the simplest thing to do is to install/reinstall the gnome-keyring package and reboot (or restart gnome-keyring-daemon):
pacman -S gnome-keyring
reboot

This should add the Login keyring and if it doesn't you can add it manually using seahorse or echo <PASSWORD> | gnome-keyring-daemon --unlock
Finally, re-add your profile with tizen security-profiles add. You can see the Tizen blog post for remote/docker configuration.
SOLUTION #2
If you don't want to bother with gnome-keyring you can try to add the passwords directly in the profiles.xml file as shown on the Tizen forum and written below:
<profileitem ca="<tizen>/tools/certificate-generator/certificates/developer/tizen-developer-ca.cer" distributor="0" key="<tizen-data>/keystore/author/<cert>.p12" password="<strong_password>" rootca=""/>

<profileitem ca="<tizen>/tools/certificate-generator/certificates/distributor/tizen-distributor-ca.cer" distributor="1" key="<tizen>/tools/certificate-generator/certificates/distributor/tizen-distributor-signer.p12" password="tizenpkcs12passfordsigner" rootca=""/>


text:
Q: Creating node webkit installable I am developing a Windows application using node webkit for serial USB connection.
When I run the script using node command it gives me exact output:
var usb = require('usb');

var devices = usb.getDeviceList();

console.log("Devices are="+devices.length);

var findDevice=usb.findByIds(1027,24577);

console.log("Devices found="+findDevice);

findDevice.open();

When I implement it with HTML pages however, it gives me the error

invalid access to memory location while accessing USB using command require('usb') of script

The code snippet I tried is
$scope.callFun=function()
{
    var usb=require('usb');

    var devices = usb.getDeviceList();
}

I have already installed node-pre-gyp and npm install usb. What am I doing wrong?

A: Try the following, not sure but it might just work.
Add a 'node-main' script, and in there have do the require in the following manner:
exports.usb = require('usb');

Then, in your html use exports.usb to access it:
var devices = exports.usb.getDeviceList();

It really is a shot in the dark but it helped me when I had a similar issue. Did it work?


text:
Q: Can not parse the string to Exact DateTime in C# I have DateTime in string format.
2013-03-05T08:28:18+0000.
I need output like :- Mar 5, 2013 8:28:18 PM
I am trying to parse to DateTime Format.
string givenDate="2013-03-05T08:28:18+0000";

DateTime parsedDate= DateTime.Parse(givenDate);

string  output= parsedDate.ToString("MMM d, yyyy hh:mm:ss tt");

Console.WriteLine("OutPut is==>"+output);

But my out is :-Mar 5, 2013 01:58:18 PM
Here time is getting changed. My expected output is -:-Mar 5, 2013 8:28:18 PM
I have try like this also.
 parsedDate = DateTime.ParseExact("2013-03-05T08:28:18+0000", "MMM d, yyyy hh:mm:ss tt", new CultureInfo("tr-TR"));

But here I am getting error:- Value does not fall within the expected range.
I have try like this also:-
parsedDate = DateTime.ParseExact("2013-03-05T08:28:18+0000", "MMM d, yyyy hh:mm:ss tt", CultureInfo.InvariantCulture, DateTimeStyles.None);

and this
parsedDate = DateTime.ParseExact("2013-03-05T08:28:18+0000", "MMM d, yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);

Both are showing this error:- FormatException
Please help to convert the DateTime as what I need.

A: Try this way
string givenDate = ("2013-03-05T08:28:18+0000");
DateTime d = DateTime.Parse(givenDate, System.Globalization.CultureInfo.InvariantCulture);
string ouputDate = d.ToUniversalTime().ToString("MMM d, yyyy h:m:s tt",  System.Globalization.CultureInfo.InvariantCulture);

A:     //First, your entry does not include AM or PM.
    //Therefore it is considered a time format 24H
    string inputDate="2013-03-05T08:28:18+0000";
    //We indicate culture, although in this step is not necessary.
    DateTime d = DateTime.Parse(inputDate,CultureInfo.InvariantCulture);
    //Your date, contains the modifier +0000, indicating a time zone
    //We must become universal time, or local time is displayed
    //If you only want 1 digit for the hours, minutes, seconds, when their value < 10, we use a single symbol format
    // 01:02:03 ->1:2:3 using h:m:s -> 01:02:03 using hh:mm:ss
    //We use invariant culture, or we want to display the data
    string ouputDate = d.ToUniversalTime().ToString("MMM d, yyyy h:m:s tt", CultureInfo.InvariantCulture);
    // ouputDate ="Mar 5, 2013 8:28:18 AM";
    // Because your date dont include any time zone specifier, if want to convert to DateTime, must specify some
    // or DateTimeKind.Unspecified is used
    //Try this
    Console.WriteLine(ouputDate);
    DateTime d2 = DateTime.SpecifyKind(DateTime.Parse(ouputDate,CultureInfo.InvariantCulture),DateTimeKind.Utc);
    Console.WriteLine(d2);
    DateTime d3 = d2.ToLocalTime();
    Console.WriteLine(d3);
    DateTime d4 = d2.ToUniversalTime();
    Console.WriteLine(d4);
//Here d2 is DateTimeKind.Unspecified, the strange result happen in the conversion to string
    d2 = DateTime.Parse(ouputDate,CultureInfo.InvariantCulture);
    Console.WriteLine(d2);
    d3 = d2.ToLocalTime();
    Console.WriteLine(d3);
    d4 = d2.ToUniversalTime();
    Console.WriteLine(d4);

A: Your first line defines a date/time for Coordinated Universal Time with zero offset (AFAIR the time valid for Greenwich, UK).
Your second line parses this time correctly, however it readjusts the time for your local time offset. It adds 5:30 hours, because you live in the time zone UTC+5:30.
On top your input is an early morning time (08:28), but you expect it to be an evening time (08:28 PM).
That's why line three and four show the "unexpected" result.
You have some options:

*

*change the input to "2013-03-05T08:28:18+0530"

*change the input to "2013-03-05T08:28:18"

*readjust the output with parsedDate = parsedDate.ToUniversalTime();


text:
Q: Existence of a random variable given a cdf For every real function F which can be a CDF (so has the properties that $F(+\infty)=1$, $F(-\infty)=0$, and F is non-decreasing and right continuous), does there exist a random variable on a probability space with this function as it's CDF?
Seems rather trivial (I may be misunderstanding something here) but I would like to prove it.

A: The answer depends on the considered probability space.
If the probability space is not rich enough (for example if $\Omega$ is finite), the result won't hold.
But if we can find a random variable $U$ on $\Omega$ whose distribution function is uniform, then given a c.d.f. $F$, we may find a random variable $X$ on $\Omega$ whose distribution function is $F$: define $X:=F^{-1}(U)$ where $F^{-1}$ is the generalized inverse of $F$, that is,
$$F^{-1}(u)=\inf\left\{ x\in\mathbf R\mid  F(x)\geqslant u\right\}.$$


text:
Q: Autosys - Get Jobs list on a specific computer I try to get the list of all the jobs running on a specific client.
When running autorep -J ALL -q  I get the following output:
 /* ----------------- ### ----------------- */

  insert_job: ###   job_type: CMD
  box_name: ###
  command: ###
  machine: MACHINE X
  owner: autosys
  permission:
  date_conditions: ###
  condition: ###
  description: ###
  box_terminator: 1
  alarm_if_fail: 0
  application: ###

  /* ----------------- ### ----------------- */

  insert_job: ###   job_type: CMD
  box_name: ###
  command: ###
  machine: MACHINE Y
  owner: autosys
  permission:
  date_conditions: ###
  condition: ###
  description: ###
  box_terminator: 1
  alarm_if_fail: 0
  application: ###

  ...

As you can see, is displayed here the list of ALL the jobs for ALL the clients
What I expect to get is an output as following :
 /* ----------------- ### ----------------- */

  insert_job: ###   job_type: CMD
  box_name: ###
  command: ###
  machine: MACHINE X
  owner: autosys
  permission:
  date_conditions: ###
  condition: ###
  description: ###
  box_terminator: 1
  alarm_if_fail: 0
  application: ###

  /* ----------------- ### ----------------- */

  insert_job: ###   job_type: CMD
  box_name: ###
  command: ###
  machine: MACHINE X
  owner: autosys
  permission:
  date_conditions: ###
  condition: ###
  description: ###
  box_terminator: 1
  alarm_if_fail: 0
  application: ###

  ...

Unfortunately the commands autorep -J ALL -q -m MACHINE X doesn't work but give me the following output :
/* ----------------- MACHINE X ----------------- */

insert_machine: MACHINE X
type: a
factor: 1.00
port: 7520
node_name: MACHINE X
agent_name: WA_AGENT
encryption_type: DEFAULT
opsys: windows
character_code: ASCII

I guess that this is the JIL format to add a machine, so what no I expect to get.
Do you know if what I try to do is possible using autosys commands only or if I have to parse the first output trough some regex to finally obtain what I would like to ?

A: I have created a Autosys Jill parser , using that you can have required info in csv file .After that you can filter required information
first you must have a file which contains required columns to be extracted from jill like
$]cat Jill_Columns
insert_job
job_type
box_name
watch_file
watch_interval
command
date_conditions
machine
owner
permission
condition
days_of_week
exclude_calendar
start_times
description
std_out_file
std_err_file
alarm_if_fail
profile
application

and Jill file which needs to be parsed to csv
Here is the script
Command to run in unix box
sh JillToCsv.sh Your_Jill_Columns Yours_Jill_file
#!/bin/bash

Usage()
{
echo "----------------------------------------------------------------------------"
echo " "
echo " "
echo " "
echo "This script takes two parameter "
echo "First is the file which conatins column names like below for Jill information "
echo "cat Jill_ColumnOrder.txt"
echo "insert_job
job_type
box_name
command
date_conditions
machine
owner
permission
condition
days_of_week
exclude_calendar
start_times
description
std_out_file
std_err_file
alarm_if_fail
profile
application"

echo " "
echo " "
echo " "
echo "Second is the Jill File which needs to be parsed as csv "
echo " "
echo " "
echo " "
echo "----------------------------------------------------------------------------"
}

if [ $# -eq 2 ]
then
echo "File which contains column names  : $1"
echo "Input Jill File                   : $2"
else
echo "Please pass manadatory parameters"
Usage
exit 1
fi

Jill_ColumnOrder=$1

tfile=$2

dos2unix $tfile

final=${tfile}_Parse.csv
rm -f $final

heading=`cat $Jill_ColumnOrder|sed 's/$/@Akhilesh@/g'|sed '$ s/@Akhilesh@$//g'|tr -d '\n'`

line=
filler=1

no_columns=`cat $Jill_ColumnOrder|wc -l`

while [ $filler -lt $no_columns ]
do
        filler=`expr $filler + 1`
        line=$line`echo -n "@Akhilesh@"`
        #echo $line
done

#echo "$heading"
#echo "   "
#echo "$line"

echo "$heading">$final

count=1
cat $tfile|sed -r 's/job_type/\njob_type/g'|sed '/^$/d'|sed -r 's/\s+/ /g'|while read kk
do
        echo "$kk"|sed -r 's/^[ ]+//g'|grep '\/\* -----------------' # >/dev/null
        if [ $? -eq 0 ]
        then
                count=`expr $count + 1`
                echo "$line">>$final
        else
        PP=`echo $kk|cut -d ':' -f1|tr -d ' '`
        #echo "PP    : $PP"
        val=`echo $kk|cut -d ':' -f2-|sed -r 's/^[ ]+//g'|tr -d '"'|tr -d '\n'`
        #echo $val
        val=\"$val\"
        field=`grep -nw $PP $Jill_ColumnOrder|cut -d':' -f1|tr -d '\n'`

        #echo "field   :  $field"

        if [ -z $field ]
        then
        echo "$PP not there in column list"
        else

        awk -F'@Akhilesh@' -v OFS=@Akhilesh@ -v var="$val" -v var1=$count '{if(NR== var1) $'$field' = var;print}' $final > tmp.parse && mv tmp.parse $final
        fi

        fi
done

cat $final|sed 's/@Akhilesh@/,/g' > tmp.parse && mv tmp.parse $final

A: autorep does not support that sorting as of yet. You will need to parse out the output.
Dave

A: I have finally created a script that does it for me :
#!/bin/ksh
autorep -j ALL -q > alljobs.jil
mkdir /tmp/autosystemp
i=0
while IFS=\| read -r "line"; do
        if [ `echo $line | grep '/* ------' | wc -l` -eq 1 ]; then
                i=$((i+1))
        fi
        echo "$line" >> "/tmp/autosystemp/f$i"
done < alljobs.jil
rm tempo/f0
for file in /tmp/autosystemp/*; do
        while read line; do
                if [ `echo $line | grep "machine: $1" | wc -l` -eq 1 ]; then
                        cat $file >> "jobs-on-$1.jil"
                fi
        done < $file
done
rm -rf /tmp/autosystemp

To use it just pass the machine name as an argument to the script


text:
Q: Can one differentiate cases when returning an HTTP 422 in a REST API? I am developing a REST API in Rails.
The API returns an HTTP 422 unprocessable entity with error messages when model validations fail.
However, a model can have several validations and I want to delegate the translation of the error messages to the API consumer and that is why it needs to differentiate what was the specific cause for the server to return a 422.
I was thinking about using subcodes, just like Facebook does in its API. Is there a way to do this keeping the REST practices?
Also, what does one do when an error 422 occurs for multiple causes at the same time?

A: RFC 7231

Client Error 4.x.x
Except when responding to a HEAD request, the server SHOULD send a representation containing an explanation of the error situation, and whether it is a temporary or permanent condition.

Normally, you should encode information that is specific to your domain in the message-body of the response.  The status line and response headers are there for generic components (browsers, caches, proxies) to have a coarse understanding of what is going on.
The Problem Details specification lays out the concern rather well.

consider a response that indicates that the client's account doesn't have enough credit.  The 403 Forbidden status code might be deemed most appropriate to use, as it will inform HTTP generic software (such as client libraries, caches, and proxies) of the general semantics of the response.
However, that doesn't give the API client enough information about why the request was forbidden, the applicable account balance, or how to correct the problem.  If these details are included in the response body in a machine-readable format, the client can treat it appropriately; for example, triggering a transfer of more credit into the account.

I don't promise that Problem Details is well suited for your purposes; but as prior art it should help you to recognize that the information you want to communicate belongs in the body of the response, with a suitable Content-Type header to inform the consumers which processing logic they need to use.


text:
Q: Extract value from vector to another I have two vector (shapefile) data. One contains soil order for county, and the other one contains boundary for each county. I want to extract the soil order for each county by using county boundary. But I am not sure how to do this?

A: To provide the response based on @artwork21 comment.
To identify areas in one shapefile that contain the areas in a different shapefile as related to your soils data. You can than extract the data in your attribute table using a Spatial Join feature. Here is a tutorial using QGIS that you can reference Performing Spatial Joins
I've included a few of the general steps with some visuals for reference. You will need to input the datasets you have in each of the corresponding inputs of the spatial join tools and methodology.
Go to Layer ‣ Add Vector Layer. Browse

Go to Vector ‣ Data Management Tools ‣ Join attributes by location.


text:
Q: Do I need to have Steam for Wolfenstein (2009) single player? I am thinking about buying Wolfenstein (2009), but on the packaging I noticed that it says something about Steam. Do I also need Steam for single player mode? Basically I want to avoid Steam for various reasons that are irrelevant to this question.

A: Yes, you need Steam to install the game. I will not run at all without Steam.
Steam is a DRM and content-distribution client, not a multiplayer service. Its main function is to manage the installation of the game, tie the serial number to a single account, and keep it up-to-date. All of these functions are independent of online multiplayer options in a game – in fact, there are many games that use/require Steam that have no online capabilities at all, but even these non-online-aware games require Steam because the Steam client manages them.
For Wolfenstein (2009) in particular, it was released for PC before it was released for Steam (August 2009 for original NA, AUS, and EU releases, October 2009 for Steam release)[1], so in theory there are copies out there for sale that don't require Steam at all. If the one you're considering buying says "Steam" on the packaging though, then that copy is not one of them and it will not run without first installing Steam.


text:
Q: Migrating from TFS to Redmine My team currently is using TFS 2010 for source control, builds and project management.  We are moving to Git for source control, Cruise for builds, and Redmine for project management.  We are using Git-Tfs right now to integrate our source control with TFS, and cruise is a pretty trivial setup, my question is about project management migration.
Are there any processes or tools to migrate the issues, bugs, tasks, and user stories from TFS to Redmine?  Has anyone done this before?

A: Really when it comes to importing into Redmine the best bet is to use the REST API (http://www.redmine.org/projects/redmine/wiki/Rest_api_with_ruby). This requires that you export your data from TFS in some way (best bet is as a csv or tsv) and with a little ruby code iterate through your data and make new issues.
I don't know what tools TFS has built in for exporting data, but as a csv isn't uncommon, and at the least with access to the SQL back-end and an SQL script you could create a csv manually.
The import into Redmine normally requires coding, but there are plugins as well (http://www.redmine.org/plugins/issue_importer_xls).


text:
Q: Re-building list from a list of dictionary I've been trying to re-build the following list of dict by similar key:
Example:
n = [{'service_name': '001', 'service_type':'API', 'db_name': 'abc', 'db_type': 'test'},
     {'service_name': '002', 'service_type':'API', 'db_name': 'def', 'db_type': 'dev'},
     {'service_name': '003', 'service_type':'Service', 'db_name': 'ghi', 'db_type': 'uat'}
    ]

I want to group them by similar key and the expected output to be:
for service:
service: [{'service_name': '001', 'service_type':'API'},
          {'service_name': '002', 'service_type':'API'},
          {'service_name': '003', 'service_type':'Service'}]

for db:
db: [{'db_name': 'abc', 'db_type': 'test'},
     {'db_name': 'def', 'db_type': 'dev'},
     {'db_name': 'ghi', 'db_type': 'uat'}]

Prefix will be generated dynamically. It could be service, db, sch, etc.. I wonder would it be possible to done it through a loop and generate these new keys (service, db, sch.etc) on the fly.
If anyone can shed some lights, that would be very helpful.
Thank you in advance.

A: You can do it this way:
for service:
key = 'service'
[{v:k[v] for v in k if v.startswith(key)} for k in n]

Output:
[{'service_name': '001', 'service_type': 'API'},
 {'service_name': '002', 'service_type': 'API'},
 {'service_name': '003', 'service_type': 'Service'}]

for db:
key = 'db'
[{v:k[v] for v in k if v.startswith(key)} for k in n]

Output:
[{'db_name': 'abc', 'db_type': 'test'},
 {'db_name': 'def', 'db_type': 'dev'},
 {'db_name': 'ghi', 'db_type': 'uat'}]

Full code with dynamic prefixes :
from itertools import combinations
from os.path import commonprefix

n = [{'service_name': '001',
      'service_type':'API',
      'db_name': 'abc',
      'db_type': 'test'},
     {'service_name': '002',
      'service_type':'API',
      'db_name': 'def',
      'db_type': 'dev'},
     {'service_name': '003',
      'service_type':'Service',
      'db_name': 'ghi',
      'db_type': 'uat'}
    ]

prefixes = set()
for dictio in n:
  L = dictio.keys()
  line_prefixes = [commonprefix([i,j])
                   for i, j in list(combinations(L, 2))
                   if commonprefix([i,j]) != '']
  prefixes.update(line_prefixes)

print(prefixes)

for key in prefixes:
  print([{v:k[v] for v in k if v.startswith(key)} for k in n])

Output:
{'service_', 'db_'}
[{'service_name': '001',
  'service_type': 'API'},
 {'service_name': '002',
  'service_type': 'API'},
 {'service_name': '003',
  'service_type': 'Service'}]
[{'db_name': 'abc',
  'db_type': 'test'},
 {'db_name': 'def',
  'db_type': 'dev'},
 {'db_name': 'ghi',
  'db_type': 'uat'}]

A: There are lots of fancy one-liners and libraries you can use to help with this, but I'd suggest manually iterating so you gain an understanding of basic collection traversal:
n = [{'service_name': '001', 'service_type':'API', 'db_name': 'abc', 'db_type': 'test'},
     {'service_name': '002', 'service_type':'API', 'db_name': 'def', 'db_type': 'dev'},
     {'service_name': '003', 'service_type':'Service', 'db_name': 'ghi', 'db_type': 'uat'}
    ]

service = []
db = []

for d in n:
  service.append({"service_name": d["service_name"], "service_type": d["service_type"]})
  db.append({"db_name": d["db_name"], "db_type": d["db_type"]})

from pprint import pprint
pprint(service)
pprint(db)


text:
Q: Laravel 5.2 - Class 'GuzzleHttp\Client' not found, on live server only I have my config/mail 'driver' set to mandrill, host, port, etc. including in services.php mandrill secret set.
Sending Mail works fine locally, but on the live server I get:

Class 'GuzzleHttp\Client' not found

I have tried "guzzlehttp/guzzle": "~5.3|~6.0", and then back to "guzzlehttp/guzzle": "~4.0", no luck. I have done composer update, and dump-autoload still no luck on my live server. Been through every other associated Stackoverflow question and still can't resolve.

A: Please follow these simple steps:
First: Place this on top of your class
use Guzzlehttp\Client;

Second: Inside your function,  instead of using
$client = new Client();

use
$client = new \GuzzleHttp\Client();

reference:
http://docs.guzzlephp.org/en/latest/quickstart.html

A: try composer require guzzlehttp/guzzle without specifying the version. Worked for me

A: Error ?  the library GuzzleHttp (which is a Simple interface for building query strings, POST requests, streaming large uploads, streaming large downloads, using HTTP cookies, uploading JSON data ) is either missing or mis-configured.
Solution :  run the following command on your terminal(root folder):
composer require guzzlehttp/guzzle:^6.5


text:
Q: Sharepoint webpart in aspx page -markup I am trying to add a webpart to aspx page webpart code is pasted below.
I am able to see the content in the page, but it is not recognized as webpart.
 using (SPLimitedWebPartManager wpm = file.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.User))
  {
       foreach (WebPart wp in wpm.WebParts)
}

i am getting wpm.weparts.count=0 always until i customize the page and make it as un-ghosted.
may i know what i am doing it wrong here?

A: You should use System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared instead of System.Web.UI.WebControls.WebParts.PersonalizationScope.User.
Shared: gives you all the webparts which is on the pages for all users
User: only gives you the webparts where the current user has made any personalization


text:
Q: Same record want to remove in sql My table structure like :
Table Structure
Customer_Name   Month   Year    Effective_Date  Value
  Sanjay         Jan    2018      01-Jan-18       10
  Sanjay         Feb    2018      01-Feb-18       11
  Sanjay         Mar    2018      01-Mar-18       11
  Sanjay         Apr    2018      01-Apr-18       13
  Sanjay         May    2018      01-May-18       15
  Sanjay         Jun    2018      01-Jun-18       15
  Sanjay         Jul    2018      01-Jul-18       15
  Sanjay         Aug    2018      01-Aug-18       16
  Sanjay         Sep    2018      01-Sep-18       14

I want output like this:
Customer_Name   Month   Year    Effective_Date  Value
  Sanjay         Jan    2018      01-Jan-18       10
  Sanjay         Feb    2018      01-Feb-18       11
  Sanjay         Apr    2018      01-Apr-18       13
  Sanjay         May    2018      01-May-18       15
  Sanjay         Aug    2018      01-Aug-18       16
  Sanjay         Sep    2018      01-Sep-18       14

Logic: If simultaneous rows value will same then only first row will come.
I can do this using cursor. But I don't want to use cursor. Is there any other way to do do this?

A: Check both scripts find same results :
SELECT   Customer_Name
        ,YEAR(MIN(Effective_date)) [Year]
        ,DATENAME(month,MIN(Effective_date)) [Month]
        ,MIN(Effective_date) Effective_date
        ,Value
FROM TableCustomer
GROUP BY Customer_Name
        ,Value

SELECT   T1.*
FROM TableCustomer T1
INNER JOIN (SELECT Customer_Name,Value,MIN(Effective_date) Effective_date FROM TableCustomer GROUP BY Customer_Name,Value) T2
        ON T1.Customer_Name = T2.Customer_Name
        AND T1.Value = T2.Value
        AND T1.Effective_date = T2.Effective_date
ORDER BY T1.Effective_date

A: You could achieve it by using ROW_NUMBER() in following:
select Customer_Name, Month, Year, Effective_Date, Value
from (
    select
        *,
        cast(Effective_Date as date) as sort_date,
        row_number() over(partition by Value order by cast(Effective_Date as date)) as rn
    from #t
)x
where rn = 1
order by sort_date

A: if Effective_Date is a Date data type:
SELECT * FROM tablename t
WHERE
t.Effective_Date = (
    SELECT MIN(tt.Effective_Date) FROM tablename tt
    WHERE
    tt.Customer_Name = t.Customer_Name AND
    tt.Month = t.Month AND
    tt.Year = t.Year AND
    tt.Value = t.Value
)

If the pattern is always like the above sample, you can omit:
tt.Month = t.Month AND
tt.Year = t.Year AND

A: You can use CTE as below,
WITH Customer_CTE(Effective_Date)
AS
(
    SELECT MIN(Effective_Date) AS Effective_Date
    FROM Customer
    GROUP BY Value
)

SELECT * FROM Customer WHERE Effective_Date IN (SELECT DISTINCT Effective_Date FROM Customer_CTE)


text:
Q: Concrete5 - Can I get the package icon inside a tool? I have a tool inside my package (it is a loopback page which will be displayed at the end of an external authentication flow).
The page should display the package icon but because the base is an unusual URL I can't get anything relative to it and I'm not sure how I can get the icon.
URLHelper:getPackageIcon($pkg) no longer exists but if I can get the package object I'm sure I can still get the URL for the icon but I'm not sure how to get the package either.
I already tried the following
$package = Package::getByID($this->getPackageID());
$package_path = BASE_URL . $package->getRelativePath() . '/icon.png';

A: the tool is not aware of the package object. $this will be a view object.
$pkg=Package::getByHandle('my_package_handle');
$icon_url = $pkg->getRelativePath(). '/icon.png';

You may also be able to get away without BASE_URL.


text: Q: Wolfram API "data not available" message I have been using the WolframAlpha python API, and I sometimes get the output (data not available), despite it being something basic. An example is How many airplanes are in the air now?, which is something that I know wolfram can do. Does anyone know of a way to fix this, or just the reason?


text:
Q: Update Symfony translation files with nested keywords Symfony has support for nested keyword in translation files, for example:
symfony:
    is:
        great: Symfony is great
        amazing: Symfony is amazing
    has:
        bundles: Symfony has bundles

So now I can use this:
{% trans from 'domain' %}symfony.is.great{% endtrans %}

or this:
{% trans from 'domain' %}symfony.is.amazing{% endtrans %}

and everything works properly, as the official documentation says.
But, when I call command for update translation files, everything nested keywords will be converted to this:
symfony.is.great: Symfony is great
symfony.is.amazing: Symfony is amazing
symfony.has.bundles: Symfony has bundles

I need nested keywords to be preserved and properly generated. So if I define in template keyword symfony.is.great and symfony.is.amazing and call command php bin/console translation:update --force en, I need files with nested keywords as I mentioned above in the first example.
Is it possible somehow?

A: Yes, its possible with the --as-tree flag.
So you can use php bin/console translation:update --force --format=yaml --as-tree=3 en.
The '3' defines the level where to switch back to inline yaml.


text:
Q: How to have conda commands match behaviour in Vscode's integrated terminal and normal terminal? I was put off because conda info --envs does NOT display the same thing that my terminal does. Terminal:
(automl) brandBrandoParetoopareto~/anaconda3/envs $ conda info --envs
# conda environments:
#
base                     /Users/brandBrandoParetoopareto/anaconda3
automl                *  /Users/brandBrandoParetoopareto/anaconda3/envs/automl
coqgym                   /Users/brandBrandoParetoopareto/anaconda3/envs/coqgym

vscode integrated terminal outpute:
(automl) brandBrandoParetoopareto~/ultimate-utils $ conda info --envs
# conda environments:
#
                         /Users/brandBrandoParetoopareto/anaconda3
base                  *  /Users/brandBrandoParetoopareto/anaconda3/envs/automl
                         /Users/brandBrandoParetoopareto/anaconda3/envs/coqgym

it is really strange because it seems to be using the right env which I would have not know because in the debugger window it does not show (automl) but says (base) but points to the right env (In fact the previous command output if you read it carefully says it's using (automl) but then it's actually using base BUT it seems to be pointing to the right environment!?!? But wrong names).
This seems like weird behavior does anyone know how to fix this or if it's causing other unexpected issues?
Perhaps this should be posted in vscode issues but I couldn't figure out which one since there is a vscode and a vscode-python one too.

Related issue:

*

*I initially saw this issue Conda and Visual Studio Code debugging because I thought since it was pointing at base (or at least displaying wrong names) that it didn't recognize or know where my conda path was so that question seemed useful but ended up not fixing the naming issues.

*Initially I also thought that it might have been related to a conda init issue I had exactly 30 days ago but it wasn't related unfortuantely Why is conda init updating my .bash_profile incorrectly?

Per comment request to check inheritEnv (to get to it go to settings then in search bar type inheritEnv):

the box is unchecked which I assume means "terminal.integrated.inheritEnv" is set to false

The weird thing I am seeing now is that:

*

*the bottom conda right option to select environments, the environment I want to use does NOT appear. Even when I paste the path to it's option it does not work.

*When I start a new terminal, somehow it decides to activate base by it's own eventhough my zsh already starts using the correct environment. Why is that? But even when I do zsh to start a new prompt, the bottom left does not seem to point to the right conda env.

A: My recommendation would be to simply set VS Code to use the shell you are using normally:
How to change the integrated terminal in visual studio code or VSCode

A: Have you set the python environment in VScode?  If not explicitly it picks the first python it can find according to it's python search algorithm.

The Status Bar always shows the current interpreter.

To select a specific environment, use the Python: Select Interpreter command from the Command Palette (Ctrl+Shift+P).

This interpreter will be saved in the workspace settings:

Selecting an interpreter from the list adds an entry for python.pythonPath with the path to the interpreter inside your Workspace Settings. Because the path is part of the workspace settings, the same environment should already be selected whenever you open that workspace. If you'd like to set up a default interpreter for your applications, you can instead add an entry for python.pythonPath manually inside your User Settings. To do so, open the Command Palette (Ctrl+Shift+P) and enter Preferences: Open User Settings. Then set python.pythonPath, which is in the Python extension section of User Settings, with the appropriate interpreter.

Caveats:

Conda environments can't be automatically activated in the VS Code Integrated Terminal if the default shell is set to PowerShell. To change the shell, see Integrated terminal - Configuration.

Conda environment in your project will be used, but only if the conda environment contains the python interpreter, by setting python= when creating the conda environment:
conda create -n env-01 python=3.4

For further details check the python environments section of the VSCode  documentation.
https://code.visualstudio.com/docs/python/environments