text:
Q: Allow cors on localhost I know it has kinda been answered already, but i don't understand how to fix my issue. I'm developing a static website using webpack 4, and i'm having issues when trying to load images (locally and from my online server).
How do you fix the Access to XMLHttpRequest at 'XXX' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource error when using webpack? I'm not using express (still learning webpack) and all the answers i find are quite a bit complicated for me and uses custom servers, which i don't..
Is there a simple method to bypass this?
By the way, i'm using <img src="XXX" alt="" crossorigin="anonymous"> with my images. Sometimes it works, sometimes it doesn't.. the articles i've found are way too technical for me at this point..
I've tried to add the following to my webpack.config.dev.js file, but it doesn't work either :
devServer: {
    headers: {
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, PATCH, OPTIONS',
      'Access-Control-Allow-Headers': 'X-Requested-With, content-type, Authorization',
    },
(...)
}

A: I think your images loaded from your online server cause the CORS warning and your webpack conf has nothing to do with it.
If you're using Chrome you can bypass CORS by using an extension like this
or using Chrome's --disable-web-security argument explained as here

A: You could try to use JSONP, but it's kinda of a hack and it isn't allowed on every API


text:
Q: Place text before and inside fields in contact form 7 for Wordpress I am trying to figure out how to put the text before a text field in the WordPress plugin Contact form 7. How can I do that?
I managed to put it inside the field by adding this:
[text your-name placeholder "Your name here"]
However, how do I change the color of the text inside to be a certain color?

A: The Contact Form 7 editor accepts HTML. You can get the text above the inputs by doing something similar to the following:

    Your Name
    [text* your-name]

    Your Email
    [email* your-email]

    Your Message
    [textarea your-message]

    [submit "Send"]

I believe the second part of your question involves changing the placeholder color text. This doesn't have great support but can be done by doing the following.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to count lines of code in a PHP project? I'd like to count the the lines of code of a PHP-project in a given git repository. Currently I'm using:
git ls-files -- *.php* | xargs wc -l

to count the lines of code in all php files.
It would be great to have a step before counting all lines, that skips all empty lines and maybe also lines containing comments (in PHP this in # and // for single line comments and /* */ for multiline comments). I guess sed might help, but how to handle multiline comments?

A: You may use powershell for this as pointed out here. Open Powershell and go to the directory with your PHP-files. Issue the following command:
(dir -include *.php -recurse | select-string .).Count

If you want files of other file types to be included, simply add them like
(dir -include *.php, *.js -recurse | select-string .).Count

If there aren't any subdirectories, the command would be
(dir *.php | select-string .).Count


text:
Q: Answer for "You know what?" Could 'Yes' be the answer for 'You know what?'
I mean:

A: 'You know what?'
B: 'Yes.'
C: 'I won the first prize.'

I'm not sure if I bother to write 'Yes' between A's words.

A: I think it would sound more natural if you replaced B's line with

'What?'

This logic is based on a typical conversation like the following:

'Guess what?'
'What?'
'I won first prize!'

A: The appropriate answer to

*

*You know what?

is

*

*No, What?

The person then proceeds to tell you the [amazing fact/tidbit of gossip].
If you reply (or interrupt) with a statement of your own, it frustrates the asker's intent to surprise you with something you don't know.

A: "Yes." as an answer works if it's a joke, or passive aggressive ("Yes, I know what you're about to say, so much for your making a big mystery of it"). If you want B to be replying in good faith ("It sounds like the announcement you're going to make is exciting and I want to hear it") you want it to be a question at least, i.e. "Yes ?" (as in the "filler" word for "I heard you, please proceed", not the actual answer "yes"). Other possibilities are "what ?", "no, what ?", "hmmmm ?"

A: It can be done both ways. This is James Patterson's way :-), showing impatience, and interrupting:

Double Cross - Page 52 James Patterson - 2007
"You know what — "
"Yes," Bree said. "We're done, Brady. For the moment, anyway. We're
  leaving."

A: You know what? is not a question and does not expect an answer. It's an expression.
The correct response is to wait and let the speaker continue and announce the "what" of it.
See Wiktionary you know what

(idiomatic) A phrase used to get someone's attention before announcing something.  …  Well, you know what, he's got a cloud over him.

Similarly, guess what, you know, you-know-what, you know what I mean, if you know what I mean, you know what they say (ibid.)


text:
Q: ArcGIS 10.6 opening mxd from 10.2 I previously had 10.5 and opened up an ArcGIS 10.2 versions MXD.  This week, I upgraded to 10.6 and tried to open the MXD from that same 10.2.  That MXD would not open. All it would do is "not responding".  I copied, renamed it and even re-downloaded it from the email it was sent from.  Nothing.  Corrupted?
I opened up older mxd's of mine when I had 10.1.  Another Mapper used different versions 10.5 and 10.2, could not open that one either.  But, could open others.
Are there any solutions?

A: It could be something in that particular MXD is corrupt. You could try two things.
The first is to run the "MXD Doctor" it normally comes with the installation of ArcMap. I am not sure if it comes with 10.6. Normally it is found in (using Window 7): Start -> Programs -> ArcGIS -> Desktop Tool -> MXD Doctor
I have had some success in using this tool to recover corrupted MXDs.
Another alternative method, would be to check the Data Sources of the MXD. It is possible that perhaps a layer in the MXD is creating the error. Open ArcCatalog and navigate to the MXD giving issues, Right Click and select "Set Data Sources". This opens a window with all of the data loaded in the MXD. Try checking each data source to ensure it is reading information from the correct locations.
I have had issues with some of my MXDs where I have used a base map. These MXDs often will not open and I either have to reset my PC or run through the steps above to try and avoid the crash on opening.

A: SOLUTION.. I ended up opening a blank mxd and clicked to the problem mxd. It opened 15-20-ish minutes later.  All the layers were broken from all the data being moved to a new drive.
Thank you for all the help as I learned a few new problem-solving ways.


text:
Q: how to make javac to compile my multi language program I hava a java program which I wrote that in netbeanse. In my program I have some output like JoptionPane which include some non- english words (arabic). when I run that in netbeanse every thing is OK. But I try to compile my code by javac in cmd. javac give errors about them(Non-english words) and that is this  "unmappable character for encoding Cp1252". how can I compile my program. I want to add this which also I have a jar file too. to compile. My code is
"javac -cp jasperreports-6.3.0.jar; class1.java class2.java ".

how can I change that.

A: NetBeans probably saves your source files in UTF-8, so you need to tell the javac compiler that.
javac -encoding UTF-8 MyClass.java


text:
Q: Why is the "repo" package unavailable in Ubuntu 20.04? How can I install it? I tried to install repo , but apt said that package is not available. I refreshed package lists cache by apt update , but the same message.
So, I opened my browser and searched Ubuntu repositories for "repo" by going to the URL https://packages.ubuntu.com/repo. I saw that a repo package is available for xenial, bionic, eoan and even the upcoming groovy release. But it is not available for my Ubuntu, 20.04 Focal Fossa.
Why isn't it available? How can I install it?

A: I encountered this issue as well and I solved it by manually installing repo
from the repo installation page:
Taken from the install instructions:
mkdir -p ~/.bin
PATH="${HOME}/.bin:${PATH}"
curl https://storage.googleapis.com/git-repo-downloads/repo > ~/.bin/repo
chmod a+rx ~/.bin/repo

A: I didn't want to add eoan to my /etc/apt/sources.list file permanently so I downloaded the packages manually:

*

*python-kerberos from https://packages.ubuntu.com/eoan/python-kerberos

*repo from https://packages.ubuntu.com/eoan/repo
I then installed them using sudo dpkg -i <filename>, python-kerberos first.

A: I have managed to install repo by downloading and installing repo and it dependency python-kerberos from eoan repositories from https://packages.ubuntu.com. To install, type these commands and hit enter:
apt update
apt install gnupg python

This to ensure that all dependencies are installed. Now download repo and it's dependency python-kerberos as described above.

A: I solved it by manually installing repo from the
install manually repo
and resolve error Python 3
This answer for android build system error
For Python 3
If you get a "/usr/bin/env 'python' no such file or directory" error message, use one of the following solutions:
If your Ubuntu 20.04.2 LTS is a newly installed (vs. upgraded) Linux version:
sudo ln -s /usr/bin/python3 /usr/bin/python

f using Git version 2.19 or greater, you can specify --partial-clone when performing repo init. This makes use of Git's partial clone capability to only download Git objects when needed, instead of downloading everything. Because using partial clones means that many operations must communicate with the server, use the following if you're a developer and you're using a network with low latency:
repo init -u https://android.googlesource.com/platform/manifest -b master --partial-clone --clone-filter=blob:limit=10M

you can see document in
Downloading the Source


text:
Q: Google map API V3, maps disappear randomly I am coming across a very weird problem using google maps. The maps are working fine but just they just disappear randomly and then after sometime they get fixed by themselves. I am using a php wrapper class that generates google map V3 javascript code. I have also gone through the whole php wrapper class project website and there is no such issue reported.I am using it in a wordpress based website.
Moreover, I am displaying multiple maps on some pages and single map on others. But when the maps disappear, all of them just disappear only the maps controls remain there. I have checked the code over and again and I see no problem in it. I have no clue why this is happening. Here are the links of the websites

*

*http://knuj.ingstadbroadcasting.com/

*http://kmrskkok.ingstadbroadcasting.com/

*http://mybasin.ingstadbroadcasting.com/
Please let me know if more details are required.

A: I had a similar problem in one project: I had a hidden div containing a Gmap, when I make mouse over to image, this map show correctly.
But, if I make this action any times and drag the map, the background (the map background images, the road, ground, etc..) doesn't show.
The problem its caused, because the Gmap tries to rewrite when its hidden, and in this state the map doesn't have width & height (you can´t get this values if a div is hidden).
The only solution I find, is to not make the map hidden. Use opacity, z-index or move the map outside of the window (top -99999, left -99999).
PD: and yes.. its a fuc*** bug...


text:
Q: AMZN stock data retrieval with YahooDailyReader Up until 30 minutes ago I was executing the following code without problems:
import pandas_datareader.data as web
import datetime

start = datetime.datetime(2012,1,1)
end = datetime.datetime(2015,12,31)

AAPL = web.get_data_yahoo('AAPL', start, end)
AMZN = web.get_data_yahoo('AMZN', start, end)

Instead now I get:
Traceback (most recent call last):
File "/Users/me/opt/anaconda3/lib/python3.7/site-packages/pandas_datareader/yahoo/daily.py", line 157, in _read_one_data
data = j["context"]["dispatcher"]["stores"]["HistoricalPriceStore"]
KeyError: 'HistoricalPriceStore'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/me/opt/anaconda3/lib/python3.7/site-packages/pandas_datareader/data.py", line 82, in get_data_yahoo
return YahooDailyReader(*args, **kwargs).read()
File "/Users/me/opt/anaconda3/lib/python3.7/site-packages/pandas_datareader/base.py", line 251, in read
df = self._read_one_data(self.url, params=self._get_params(self.symbols))
File "/Users/me/opt/anaconda3/lib/python3.7/site-packages/pandas_datareader/yahoo/daily.py", line 160, in _read_one_data
raise RemoteDataError(msg.format(symbol, self.__class__.__name__))
pandas_datareader._utils.RemoteDataError: No data fetched for symbol AMZN using YahooDailyReader

How can I fix this?
Is there a work around to get the AMZN data as DataFrame from another source (different from Yahoo_Daily_Reader)?
Python version 3.4.7

A: How about this solution?
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import scipy.optimize as sco
import datetime as dt
import math
from datetime import datetime, timedelta
from pandas_datareader import data as wb
from sklearn.cluster import KMeans
np.random.seed(777)

start = '2019-4-30'
end = '2019-10-31'
# N = 90
# start = datetime.now() - timedelta(days=N)
# end = dt.datetime.today()

tickers = ['MMM',
'ABT',
'AAPL',
'AMAT',
'APTV',
'ADM',
'ARNC',
'AMZN']

thelen = len(tickers)

price_data = []
for ticker in tickers:
    prices = wb.DataReader(ticker, start = start, end = end, data_source='yahoo')[['Adj Close']]
    price_data.append(prices.assign(ticker=ticker)[['ticker', 'Adj Close']])

df = pd.concat(price_data)
df.dtypes
df.head()
df.shape

pd.set_option('display.max_columns', 500)

df = df.reset_index()
df = df.set_index('Date')
table = df.pivot(columns='ticker')
# By specifying col[1] in below list comprehension
# You can select the stock names under multi-level column
table.columns = [col[1] for col in table.columns]
table.head()

plt.figure(figsize=(14, 7))
for c in table.columns.values:
    plt.plot(table.index, table[c], lw=3, alpha=0.8,label=c)
plt.legend(loc='upper left', fontsize=12)
plt.ylabel('price in $')


text:
Q: Haskell Profiling I'm going through LYAH and have been looking at the use of list comprehension vs map/filters when processing lists. I've profiled the following two functions and included the prof outputs as well. If I am reading the prof correctly id say the FiltB is running a lot slower than FiltA (although its only by thousandths of seconds).
Would  be right in saying this is because FiltB has to evaluate x^2 twice?
FiltA.hs (filter odd)
-- FiltA.hs

module Main
    where

main = do
    let x = sum (takeWhile (<10000) (filter odd (map (^2) [1..])))
    print x

    Sat Jul 26 18:26 2014 Time and Allocation Profiling Report  (Final)

       Filta.exe +RTS -p -RTS

    total time  =        0.00 secs   (0 ticks @ 1000 us, 1 processor)
    total alloc =      92,752 bytes  (excludes profiling overheads)

COST CENTRE MODULE           %time %alloc

main        Main               0.0   10.1
main.x      Main               0.0   53.0
CAF         GHC.IO.Handle.FD   0.0   36.3

                                                         individual     inherited
COST CENTRE MODULE                     no.     entries  %time %alloc   %time %alloc

MAIN        MAIN                        37           0    0.0    0.2     0.0  100.0
 CAF        GHC.IO.Encoding.CodePage    61           0    0.0    0.1     0.0    0.1
 CAF        GHC.IO.Encoding             58           0    0.0    0.1     0.0    0.1
 CAF        GHC.IO.Handle.FD            52           0    0.0   36.3     0.0   36.3
 CAF        Main                        44           0    0.0    0.2     0.0   63.3
  main      Main                        74           1    0.0   10.1     0.0   63.1
   main.x   Main                        75           1    0.0   53.0     0.0   53.0

FiltB (list comprehensions)
-- FiltB.hs

module Main
    where

main = do
    let x = sum (takeWhile (<10000) [n^2 | n <- [1..], odd (n^2)])
    print x

    Sat Jul 26 18:30 2014 Time and Allocation Profiling Report  (Final)

       FiltB.exe +RTS -p -RTS

    total time  =        0.00 secs   (2 ticks @ 1000 us, 1 processor)
    total alloc =     107,236 bytes  (excludes profiling overheads)

COST CENTRE MODULE           %time %alloc

main        Main              50.0    8.8
CAF         Main              50.0    0.1
main.x      Main               0.0   59.4
CAF         GHC.IO.Handle.FD   0.0   31.4

                                                         individual     inherited
COST CENTRE MODULE                     no.     entries  %time %alloc   %time %alloc

MAIN        MAIN                        37           0    0.0    0.2   100.0  100.0
 CAF        GHC.IO.Encoding.CodePage    61           0    0.0    0.1     0.0    0.1
 CAF        GHC.IO.Encoding             58           0    0.0    0.0     0.0    0.0
 CAF        GHC.IO.Handle.FD            52           0    0.0   31.4     0.0   31.4
 CAF        Main                        44           0   50.0    0.1   100.0   68.3
  main      Main                        74           1   50.0    8.8    50.0   68.1
   main.x   Main                        75           1    0.0   59.4     0.0   59.4

A: Yes. In this particular case, since n^2 will be odd if and only if n is odd, you can speed up FiltB to the same speed as FiltA by replacing odd (n^2) with odd n.
Like you said, the problem is that for each element n it's squaring it, checking if that's odd, and if it is, then squaring n and adding that to the list.
More generally though, the difference is that in a list comprehension, the filtering happens before you map, whereas with map and filter, you can choose the order. So if what you actually want to filter based on is the values in the list after mapping, using map and filter is probably a better choice. You still could do something like this to filter based on whether the squared values are odd:
sum (takeWhile (<10000) [ x | x <- [ n^2 | n <- [1..] ], odd x ])

But that's getting to be pretty hard to read. Map and filter or filtering over the list comprehension explicitly (i.e. filter odd [ n^2 | n <- [1..] ]) are much better options.


text:
Q: uncaught exception: could not open file so i'm trying to upload to uploadcare cdn and i get this error: Uncaught Exception: couldn't open file "ce3577f708f527ff570e0d21acb39c62.jpg"
$description = $_POST['uploaddesc'];
  list($width,$height) = getimagesize($_FILES['uploadimage']['tmp_name']);
 $extensions  = array('image/jpeg','image/jpg','image/gif', 'image/png', 'image/tiff');
 $move = 'uploads/';
 $finfo = finfo_open(FILEINFO_MIME_TYPE);

$extension = pathinfo($_FILES['uploadimage']['name']);
if(!$_FILES['uploadimage']['tmp_name']){
$errors[]="Please choose an image";
}
if(empty($description)){
    $errors[]='Please choose a description for the image';
}
//IF IMAGE IS UPLOADED..
if($_FILES['uploadimage']['tmp_name']){
    $mime = finfo_file($finfo, $_FILES['uploadimage']['tmp_name']);

// IF MIME FAILES OR GETIMAGESIZE IS NULL (meaning its no an image)
        if(!getimagesize($_FILES['uploadimage']['tmp_name']) && !in_array($_FILES['uploadimage']['tmp_name'],$mime)){
       $errors[]='Please choose an image';
       unset($_FILES['uploadimage']['tmp_name']);
          }
     if(empty($errors)){

 $randString = md5(time()); //encode the timestamp - returns a 32 chars long string
 $fileName = $_FILES["uploadimage"]["name"]; //the original file name
 $splitName = explode(".", $fileName); //split the file name by the dot
 $fileExt = end($splitName); //get the file extension
 $newFileName  = strtolower($randString.'.'.$fileExt); //join file name and ext.
 if(move_uploaded_file($_FILES['uploadimage']['tmp_name'], $move . $newFileName)){
 $description = $_POST['uploaddesc'];
 $user->insertArt($description, 'uploads/' . $newFileName, $user->getUsername($_SESSION['username']));
 $file = $api->uploader->fromPath('uploads/' . $newFileName);
 $file->store();

//throw new ErrorException('MEMORY USAGE ' . memory_get_peak_usage());

 }
     }

}

A: i have fixed it. i had to use realpath('uploads/' . $newfilename);


text:
Q: How to install cvxopt without downgrading mkl and python Environment:
OS = Windows 10, Python ver = 3.7.0, mkl ver = 2019.0-118, conda ver = 4.5.12. All up to date as of now (2019/1/13).
Issue:
When attempting conda install cvxopt, it prompts at the end:
The following packages will be DOWNGRADED:

    mkl:                                2019.0-118              --> 2018.0.3-1
    python:                             3.7.0-hea74fb7_0        --> 3.6.8-h9f7ef89_0

Proceed ([y]/n)? n

I don't want to downgrade either. Actually, when I visit the cvxopt's installation page it states clearly that

Wheels for Windows:

*

*are available for Python 27, 3.4, 3.5, 3.6, and 3.7 (64 bit only)

The suggested installation procedure is a bit complicated, though.
I'm just wondering if there's a simple way (that is, for dummies) such as a one-line command that can install cvxopt without compromising python or mkl.
Thanks.

A: It's best not to mix conda and pip packages. It looks like conda-forge has the latest version of cvxopt, so simply do:
conda install -c conda-forge cvxopt

A: You could just try pip3 install cvxopt
I've just tried it and it works on my Windows machine


text:
Q: 403 Forbidden nginx/1.6.2 on Laravel Homestead installation I'm out of ideas about what I can do to finish my Laravel Homestead install.
Some infos :

*

*laravel/homestead (virtualbox, 0.2.4)

*vagrant base is lucid32. I can't use the serve command with SSH.

Here is my homestead.yaml :
---
ip: "192.168.10.10"
memory: 2048
cpus: 1

authorize: ~/.ssh/id_rsa.pub

keys:
    - ~/.ssh/id_rsa

folders:
    - map: /Users/bolos/base
      to: /home/vagrant/base

sites:
    - map: homestead.app
      to: /home/vagrant/base/homestead/public

databases:
    - homestead

variables:
    - key: APP_ENV
      value: local

provider: virtualbox

# blackfire:
#     - id: foo
#       token: bar

I don't know what else I can provide to help, but feel free to ask.
Thank you in advance.

A: According to your configuration you must replace:
to: /home/vagrant/base/homestead/public

with:
to: /home/vagrant/base/public

And this should work if you have Laravel on /Users/bolos/base.


text:
Q: dd dsync results extremely slow. Is this normal? I am investigating slow application issues with some New Hardware and am running into some odd results.  I am trying to determine what is causing this behavior.
 I am using :

dd if=x.b1 of=x.b10 bs=8192 oflag=dsync     of a 101MB file
  to simulate how our database is writing to disk (the dsync flag was suggested by our database vendor), and while normal dd commands without the dsync option are showing 80-100 Mb/s, with the dsync command I am getting results in the 160Kb/s-200Kb/s range.

This behavior has been viewed on multiple pieces of hardware, as well as different model hard drives and doing a drive wipe test:
dd if=/dev/zero of=/dev/sda bs=8192 oflag=dsync
shows more expected 80-100Mb/s speed, which seems to suggest it is something in our Custom OS that is slowing things down.  We have run these tests under a custom SuseLinux as well as OracleOS (32 and 64 bit)  and we continue to see these very low numbers.
Can you give me some ideas of where the problem is?
Thanks


text:
Q: How to disable spell checking in MS Edge My Windows 10 settings are set to "Off" for highlight misspelled words but Edge still highlights what it considers a misspell. See screenshot below.

A: If you're disabling the spelling options while the apps are still running, you'll need to restart the app you want to use without the autocorrect in order the changes to take effect.

A: If for some reason even Origami's solution did not work, then I recommend you my force-workaround. Download the Tampermonkey MS Edge extension from the Windows Store and install the following UserScript:
https://greasyfork.org/de/scripts/39190-disable-spellcheck-globally
This UserScript sets the "spellcheck" attribute to the global  element/tag of every website you visit so that Edge MUST obey the rules. This also fixes the issue of auto-correction, tested on reddit.
You can get Tampermonkey here: https://www.microsoft.com/en-us/store/p/tampermonkey/9nblggh5162s
Works on Windows 10 build 17112.1

A: I had the same problem in my windows 10 pro. solved by opening «group policy», «user configuration», «administrative templates», «control panel», «regional and language options», then enable «turn off autocorrect misspelled words» and «turn off highlight misspelled words» policies. restart the machine.


text:
Q: Complex function defined on the real axis by a power series $f(z) = u(x,y)+iv(x,y)$ in the segment : $ y=0, 3.2\leq x \leq 3.8 $ is: $$ u(x,0)=\sum_{n=1}^{\infty}\Bigl({x\over4}\Bigr)^n+\sum_{n=0}^\infty \Bigl({3\over x}\Bigr)^n, v(x,0)=0 $$
Find $f(z)$ in the point $ z=5+i8$.$$$$
The power series is well defined for $ 3<x<4 $. I can rewrite $ u $ as:
$$ u(x,0)= {x\over4-x}+{x \over x-3}$$
And this function is well defined for $ x\neq3, x\neq4$ (but is it equal to the power series outside of it's region of convergence?). Now I can maybe solve 2 Laplace's equations one for $u$ and one for $v$ with the initial condition $ u(x,0)= {x\over4-x}+{x \over x-3}$  and $v(x,0)=0$ with $-\infty<x<\infty $,and then maybe impose the CR conditions, but don't know how to really do it.


text:
Q: How can I automate the following web browsing using python? How can I automate the following web browsing using python?

*

*go to certain url

*click on some buttons

A: You can consider leveraging Selenium.
Here is some information:
https://pypi.python.org/pypi/selenium
How to use Selenium with Python?


text:
Q: How to I populate a treeView from a mouse click on an item in listView in C#? How to I populate a treeView from a mouse click on an item in listView in C#? Data in the listView is read from an access database.

A: Use BeforeExpand event of TreeView and utilize TreeViewCancelEventArgs.
 e.Node.Nodes.Add(...)


text:
Q: pgfplots: Two half-planes (Gödel logic graph) I want to plot the function
 (x <= y) * (1) + (x > y) * (y)
which should give two triangle-styled areas.
(1) With the first try
\addplot3[surf, domain=0:1, domain y=0:1
]{   (x <= y) * (1) + (x > y) * (y)   };

I get a bad result, because the areas are connected.
(2) So I split into two functions and use restrict z to domain=<..>.
But now I get zigzag at the margins and gaps to the origin of the second area.
Which settings should use?
Hint: It is clear how to use straight lines and fill between here I would like to figure out how to use the shown functions here with pgfplots.

\documentclass[border=10pt, tikz]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=newest, width=7cm,
colormap = {whiteblack}{color(0cm)  = (white); color(1cm) = (black)},
every axis plot post/.append style={cyan},
%fill=cyan,
}
\begin{document}

\begin{tikzpicture}
\begin{axis}[title={Bad - areas connected}, xtick={0,0.5,1}, ytick={0,0.5,1}, ztick={0,0.5,1},
xlabel=$p$, ylabel=$q$, zmin=0, zmax=1, small]
\addplot3[surf, domain=0:1, domain y=0:1
]{   (x <= y) * (1) + (x > y) * (y)   };
\end{axis}
\end{tikzpicture}

\begin{tikzpicture}
\begin{axis}[title={Better but not perfect: gaps and zigzags}, xtick={0,0.5,1}, ytick={0,0.5,1}, ztick={0,0.5,1},
xlabel=$p$, ylabel=$q$, zmin=0, zmax=1, small]
\addplot3[surf, cyan,
domain=0:1, domain y=0:1,
restrict z to domain=1:1,
]{    (x <= y ) * (1)     };

\addplot3[surf,
domain=0:1, domain y=0:1,
restrict z to domain=0.000001:1,% not good
]{   (x > y) * (y)     };
\end{axis}
\end{tikzpicture}
\end{document}

A: This is not exactly, what OP is looking for, but for reasons of elegance, I show the patch plot:
\documentclass[border=0.5 cm, tikz]{standalone}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
\begin{axis}
\addplot3[patch, patch refines=8, cyan] coordinates {(0,0,1) (1,1,1) (0,1,1) };
\addplot3[patch, patch refines=8, cyan] coordinates {(0,0,0) (1,1,1) (1,0,0) };
\end{axis}
\end{tikzpicture}
\end{document}


text:
Q: How can I expand CSS shorthand properties programmatically? Is there a .Net CSS parser that will allow me to parse css shorthand properties into their longhand form?
For example I'd like to take the following:
        #somediv{
            margin: 10px;
            padding: 10px 20px;
            border:5px solid #FFF;
        }

And translate it to:
        #somediv{
            margin-top: 10px;
            margin-right: 10px;
            margin-bottom: 10px;
            margin-left: 10px;
            padding-top: 10px;
            padding-right: 20px;
            padding-bottom: 10px;
            padding-left: 20px;
            border-width: 5px;
            border-style: solid;
            border-color: #FFF;
        }

Here is a pretty good list of all the different properties I'd need to handle in this manner:  http://www.dustindiaz.com/css-shorthand/
Ideally I'd like something in .Net but if there's something in another language that's open source I can probably adapt it.
Update
Without getting into too much detail as to exactly what I'm trying to do here is the basic premise:
I need to programmaticly take multiple CSS docs and merge them to create one definitive set of CSS.
So if doc 1 has :
p { padding: 10px;}

And then I add on doc 2:
p { padding-left:20px;}

The resulting CSS should be:
p { padding-top: 10px; padding-right:10px; padding-bottom:10px; padding-left:20px;}

Because the later added doc overwrites the single property.  To do this accurately I would need to take every CSS and break down every property to it's lowest element first.

A: For regular CSS parsing I've found this to be the easiest to use:
http://www.codeproject.com/KB/recipes/CSSParser.aspx
For breaking down the shorthand properties into their longhand form I've found two that can do it:
In .Net : http://www.modeltext.com/css/index.aspx
In JavaScript: http://www.glazman.org/JSCSSP/

A: The most simplest approach would is to make use of .NET's WebBrowserControl along with MsHTML(IE Renderer) and this is most reliable approach too !
//Create the instance of new webbrowser control.
        WebBrowser browser = new WebBrowser();

        //Navigate to the specified URL.
        browser.Navigate(@"test.html");

        //Wait until the webpage gets loaded completely.
        while (browser.ReadyState != WebBrowserReadyState.Complete)
        {
            Application.DoEvents();
        }

        foreach (object divElement in
            (browser.Document.GetElementsByTagName("div")))
        {
            IHTMLCurrentStyle currentStyle = ((divElement as HtmlElement)
                .DomElement as IHTMLElement2).currentStyle;

            Console.WriteLine(currentStyle.marginLeft);
            Console.WriteLine(currentStyle.marginRight);

        }

Note:
In order to get this code working you need to add reference to Microsoft.MSHTML.dll which can be found on the following location.
c:{Program Files}\microsoft.net\Primary Interop Assemblies\

A: Could you give a little more detail on why you want to do this?
And are you looking for it to do correct parsing with things like:
padding:10px 15px;
into
padding-top:10px;
padding-right:15px;
padding-bottom:10px;
padding-left:15px;


text:
Q: How do I validate an SQL query before executing it using C# I have a textbox where the user enters his SQL query. However,I need to make a program that validates the query before executing it in the database.
For Example:
Suppose the user enters
SELECT A1,
       A2,
       A3
  FROM XYZ

So now, before executing the query, I need to check whether A1, A2 and A3 exists in the table XYZ or not. If not, the user should be shown an error message.
I'm not able to think of a way to proceed.
So Can anyone give a basic idea with a sample code snippet about how to proceed further?

A: I doubt if you should do this:

*

*what if XYZ is not a table, but a view, materialized view, stored procedure (depends on RDBMS) which returns cursor?

*what if XYZ is a table, but user has not permission (grant) to read it?

*what if user has no permission on, say, A2 field reading?

There're other cases which should be taken into account

*

*the query can be re-written (e.g. in case of Oracle via FGA - Fine Grain Audit)

*XYZ can be a synonym for whatever, e.g. dblink to remote table on Hadoop, while this Hadoop is temporary out of service

So I suggest executing the query without any preliminary check, but parsing and explaining exception thrown if any.

A: The very suitable way is excecuting the code in MS SQL and let MS SQL figure out the errors.
StringBuilder  query= new StringBuilder();

query.Append("BEGIN \n");
query.Append("BEGIN TRY \n");
query.Append("    -- Table does not exist; object name resolution   \n");
query.Append("    -- error not caught.   \n");
query.Append("    --Append the variable which holds your sql query \n");
query.Append("    --For eg.: SELECT * FROM NonexistentTable;   \n");
query.Append("    END TRY \n");
query.Append("    BEGIN CATCH \n");
query.Append("      SELECT \n");
query.Append("        ERROR_NUMBER() AS ErrorNumber \n");
query.Append("       ,ERROR_MESSAGE() AS ErrorMessage; \n");
query.Append("    END CATCH \n");
query.Append("END");

Excecute the query using ExcecuteScalar() of SQLCommand.
SQL Server will return the exact errors for the query submitted.

A: Probably you need to do it one by one. First Check whether the Table XYZ exist or not
SELECT * FROM INFORMATION_SCHEMA.TABLES
           WHERE TABLE_NAME = 'XYZ';

Then would come to the next question that is if the field name in the table exists or not
SELECT * FROM   INFORMATION_SCHEMA.COLUMNS
          WHERE  TABLE_NAME = 'XYZ'
                 AND COLUMN_NAME = 'A1'
                 AND COLUMN_NAME = 'A2'
                 AND COLUMN_NAME = 'A3'

A:
So now, before executing the query, I need to check whether A1,A2 and A3 exist in the table XYZ or not.

If you want to check if the values exists in the table you have to query in the table. Without executing the query you cannot find if the value exists in the table.
If you are working in SQL Server(for example) then you can make use of the IF EXISTS clause like
IF EXISTS(
    SELECT *
    FROM sys.columns
    WHERE Name = 'A1' AND Name = 'A2' AND Name = 'A3'
      AND Object_ID = Object_ID(N'XYZ'))
BEGIN

END


text:
Q: How can I exit from mysql_secure_installation? Screenshot of the installation process
As you can see at the image (link above) I started an installation of mysql by typing

mysql_secure_installation

on the Ubuntu 20.04 terminal.
But now I just want to cancel (exit) the installation. The process is now in the password setting section (like in the image above).
I tried ctrl+x, ctrl+q, ctrl+d, ESC but none of them worked.
Should I just close the terminal window? (I want that nothing will be saved of the process)
I'm waiting for your help, thanks in advance.

A: ctrl+c will work, but only at the following position:

Do you wish to continue with the password provided?(Press y|Y for Yes,
any other key for No) :

A: The Solution
From another terminal:
sudo kill $(ps aux | grep mysql_secure_installation | grep -v grep | awk '{print $2}')

Per qt-x's comment, if your system supports pgrep you can use:
sudo kill $(pgrep mysql_secure_installation)

You can then run 'mysql_secure_installation' again.   But you may want to read the "Why I Know This" section below first....., which may explain why you have to exit 'mysql_secure_installation' in the first place [for some people].
Why I Know This
For some reason, recently I've had to set my root password first before running this script:
> mysql
mysql> ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password by 'mynewpassword';

Or I end up in an endless loop where I can't set the password, and the message is:
Failed! Error: SET PASSWORD has no significance for user 'root'@'localhost' as the authentication method used doesn't store authentication data in the MySQL server

A: Maybe a simpler command to kill mysql_secure_installation
sudo pkill -f mysql_secure_installation

pgrep -af mysql_secure_installation to get the current state.

A: very easy, just type ctrl+c
it worked for me, don't know about you


text:
Q: Почему в разметке не разместить знак ">" как текст? Разметка:
   <Button
        android:id="@+id/btnRR"
        android:layout_width="50dp"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:text="<<" />

проект не собрать, пока вместо "<<" не поставить например "11". Как это обойти?

A: Знаки больше и меньше являются спецсимволами и для передачи как текст их необходимо экранировать, используя так называемые escape-последовательности. Так, например, чтобы знак больше не воспринимался как спецсимвол, его необходимо записать как &_gt;(без нижнего подчеркивания), что означает "greater then", а меньше будет выглядеть как &_lt;(без нижнего подчеркивания). Подробнее можно почитать тут https://thequestion.ru/questions/145118/chto-oznachaet-and-gt


text:
Q: Can't add ScrollBar to ScrollablePositionedList (it doesn't have a ScrollController) I'm using the scrollable_positioned_list package, and have it rendering a large dynamic list. It works very well. However, I need my list to have a scrollbar (something like this). So far, this is impossible.
Does anyone know how to do it?
My code looks as follows:
Scrollbar(
          child: ScrollablePositionedList.builder(
            physics: const ClampingScrollPhysics(
              parent: AlwaysScrollableScrollPhysics(),
            ),
            itemCount: posts.length + 1,
            itemBuilder: (context, index) {
              if (index == 0) {
                return Container(
                  height: 200,
                  color: Colors.green,
                  child: const Center(
                    child: Text('post content'),
                  ),
                );
              } else if (posts[index - 1].isRoot) {
                return Container(
                  padding: const EdgeInsets.symmetric(vertical: 15),
                  margin: const EdgeInsets.symmetric(vertical: 5),
                  color: Colors.redAccent,
                  child: Text('ROOT COMMENT, index: ${index - 1}'),
                );
              } else {
                return Container(
                  padding: const EdgeInsets.symmetric(vertical: 15),
                  margin: const EdgeInsets.symmetric(vertical: 5),
                  color: Colors.lightBlueAccent,
                  child: Text('Threaded comment, index: ${index - 1}'),
                );
              }
            },
            itemScrollController: itemScrollController,
            itemPositionsListener: itemPositionsListener,
          ),
        ),

I realize a ScrollBar needs to have the same ScrollController as the scroll view it's wrapping, however, I'm not sure how to get this because ScrollablePositionedList doesn't have a ScrollController.
Errors in my terminal after running the project with the solution provided (little snippet of it):
Performing hot restart...
../../tools/flutter/.pub-cache/git/flutter.widgets-6
d6dac5f19b577338d912d3c9a45d26593e0a475/packages/scr
ollable_positioned_list/lib/src/scrollable_positione
d_list.dart:437:24: Warning: Operand of null-aware
operation '!' has type 'SchedulerBinding' which
excludes null.
Performing hot restart...
 - 'SchedulerBinding' is from
 'package:flutter/src/scheduler/binding.dart'
 ('../../tools/flutter/packages/flutter/lib/src/sche
 duler/binding.dart').
Performing hot restart...
      SchedulerBinding.instance!.addPostFrameCallbac
      k((_) {
Performing hot restart...
                       ^
Performing hot restart...
../../tools/flutter/.pub-cache/git/flutter.widgets-6
d6dac5f19b577338d912d3c9a45d26593e0a475/packages/scr
ollable_positioned_list/lib/src/scrollable_positione
d_list.dart:484:26: Warning: Operand of null-aware
operation '!' has type 'SchedulerBinding' which
excludes null.
Performing hot restart...
 - 'SchedulerBinding' is from
 'package:flutter/src/scheduler/binding.dart'
 ('../../tools/flutter/packages/flutter/lib/src/sche
 duler/binding.dart').
Performing hot restart...
        SchedulerBinding.instance!.addPostFrameCallb
        ack((_) {
Performing hot restart...
                         ^
Performing hot restart...
../../tools/flutter/.pub-cache/git/flutter.widgets-6
d6dac5f19b577338d912d3c9a45d26593e0a475/packages/scr
ollable_positioned_list/lib/src/positioned_list.dart
:298:24: Warning: Operand of null-aware operation
'!' has type 'SchedulerBinding' which excludes null.
Performing hot restart...
 - 'SchedulerBinding' is from
 'package:flutter/src/scheduler/binding.dart'
 ('../../tools/flutter/packages/flutter/lib/src/sche
 duler/binding.dart').
Performing hot restart...
      SchedulerBinding.instance!.addPostFrameCallbac
      k((_) {
Performing hot restart...
                       ^
Performing hot restart...
Restarted application in 195ms.

After fixing the warnings (reply to comment), this now occurs randomly when using it:
The following assertion was thrown while notifying status listeners for AnimationController:
The Scrollbar's ScrollController has no ScrollPosition attached.
A Scrollbar cannot be painted without a ScrollPosition.
The Scrollbar attempted to use the provided ScrollController. This ScrollController should be
associated with the ScrollView that the Scrollbar is being applied to. When providing your
own
ScrollController, ensure both the Scrollbar and the Scrollable widget use the same one.

When the exception was thrown, this was the stack:
#0      RawScrollbarState._debugCheckHasValidScrollPosition.<anonymous closure>
(package:flutter/src/widgets/scrollbar.dart:1475:9)
#1      RawScrollbarState._debugCheckHasValidScrollPosition
(package:flutter/src/widgets/scrollbar.dart:1500:6)
#2      RawScrollbarState._validateInteractions
(package:flutter/src/widgets/scrollbar.dart:1445:14)
#3      AnimationLocalStatusListenersMixin.notifyStatusListeners
(package:flutter/src/animation/listener_helpers.dart:233:19)
#4      AnimationController._checkStatusChanged
(package:flutter/src/animation/animation_controller.dart:815:7)
#5      AnimationController._startSimulation
(package:flutter/src/animation/animation_controller.dart:749:5)
#6      AnimationController._animateToInternal
(package:flutter/src/animation/animation_controller.dart:612:12)
#7      AnimationController.reverse
(package:flutter/src/animation/animation_controller.dart:494:12)
#8      RawScrollbarState._maybeStartFadeoutTimer.<anonymous closure>
(package:flutter/src/widgets/scrollbar.dart:1630:37)
(elided 11 frames from class _RawReceivePortImpl, class _Timer, dart:async, and
dart:async-patch)

The AnimationController notifying status listeners was:
  AnimationController#72402(◀ 1.000)

A: You may see my old answer here for detail steps : https://stackoverflow.com/a/73279565/12838877
you can modify, but still have some bug when apply the ScrollController
try some alternative from issue#305, its not good enough but you can apply it.
final ItemScrollController itemSctr = ItemScrollController();
...

body: Scrollbar(
  controller: itemSctr.scrollController,
  child: ScrollablePositionedList.builder(

A: Use a ScrollConfiguration:
void main(List<String> args) {
  runApp(
    MaterialApp(
      home: Scaffold(
        appBar: AppBar(),
        body: ScrollConfiguration(
          behavior: _ScrollbarBehavior(),
          child: ScrollablePositionedList.builder(
            itemCount: 100,
            itemBuilder: (context, index) => ListTile(title: Text('$index')),
          ),
        ),
      ),
    ),
  );
}

class _ScrollbarBehavior extends ScrollBehavior {
  @override
  Widget buildScrollbar(BuildContext context, Widget child, ScrollableDetails details) {
    return Scrollbar(child: child, controller: details.controller);
  }
}


text:
Q: Share Database Connection in Servlet I tried to share a Jdbc Connection object in the ServletContext, but it's not a good idea! Now i think to share a Jdbc for each Servlet! in manner that all and only the same Servlet's threads share the connection. Now i've some doubts! Is it an error or is it not enough safe? Finally i use MySql, are there some problem with the connection's timeout property? Thanks all.

A: You need connection pooling. It is a standard way of doing this. Please go read about connection pooling and how to implement it in Java.
You can read this answer to explain it a little more: Opening a database connection in a constructor, when should I close it?


text:
Q: Loading Data From Comma Separated Text File to 2D Array? I am trying to load data from a text file that looks like this:
161,77,88,255
0,44,33,11,111
etc. I have functions to manipulate it, and am ensured that the array is the correct size (which may still vary). Below is my attempt at implementation:
bool loadData(int **imgPix, string fileName) {

ifstream inputFile;

inputFile.open(fileName.c_str());

string tempLineRow; //The resulting line from the text file
string tempElementColumn; //The individual integer element
int numberOfCols = 0;
int numberOfRows = 0;

if (!inputFile.is_open()) {
    return false;
}

imgPix = new int* [numberOfRows];

    while (getline(inputFile, tempLineRow, '\n')) {

        stringstream ss;
        ss << tempLineRow; //Stringstream version of the line

        while (getline(ss, tempElementColumn, ',' )) {
            stringstream ss2;
            ss2 << tempElementColumn;
            ss2 >> numberOfCols;

//Prob?         (**imgPix) = *(*(imgPix + numberOfRows) + numberOfCols);
            numberOfCols++;

        }

        numberOfRows++;

    }

inputFile.close();
return true;

}
I've marked the line with the double pointer assignment with a comment, because I believe it be the source of my error, although there could be others. I'm not sure how to use the while loop structure I've implemented to iteratively update the 2D array.
Can anyone offer any assistance? Would be greatly appreciated!

A: Your code has several issues, mostly I guess because you did not fully understand how built-in arrays work in C++. The main issue here is that those cannot easily grow dynamically, there is no "resize" operation for those arrays (but you will need one here). So I suggest kindly that you try to rewrite your code using std::vector<int> and std::vector< std::vector<int> >, make sure you use of .resize when you store a new row or column and come back and ask again when you run into problems with this new implementation.

A: imgPix = new int* [numberOfRows]

Here numberOfRows = 0, so you don't allocate enough memory. You need to know dimensions of the array before you allocate the memory.
And then you should also allocate a memory for each row in the array:
imgPix[currentRow] = new int [TotalCols];

For a 2-dimensional rectangular array, it would be more efficient to create 1-dimensional array of TotalRows*TotalCols elements, and then access it using formula A(row, col) = A[row*TotalCols + col].

A: Previous answers are valid, but if contiguous memory is not a requirement, std::deques may be a better choice in this case compared to std::vectors to avoid lots of memory reallocations.


text:
Q: What is the difference between "multinomial" and "polytomous"? I would like to know the difference a multinomial model and a polytomous model. Both a multinomial model, for example multinomial logit / probit model, and a polytomous model are used for estimation of quantitative data. But, a polytomous model is seldom used. I think that the difference is whether to estimate parameters for every category. So, in polytomous model, the parameters of each category is the same. Is it correct?
Moreover, I would be interested in understanding the estimation method for the polytomous model. If someone understands it, I would appreciate it someone could point that out to me.

A: The two terms refer to the same model or type of $Y$.


text:
Q: Failed to generate a user instance of SQL Server... Data Source server name property changes to a dot(.) after saving solution We are using SQL Server 2012 Express Advanced Edition with Visual Studio 2010 Professional.
In the Server Explorer we created a connection to a SQL Server .mdf file. We set the Server Name to:
OURSERVER\SQLEXPRESS

and attached the .mdf file. Next I clicked the Test Connection button to ensure everything was working ok. I clicked the OK button thinking everything was ok and clicked the Save All icon. I also looked at the data in the database using the Server Explorer to make sure our app will be able to access it. I exited VS2010.
Later I started up VS2010 and noticed that the database needed to be connected so I click the icon to connect to the database thinking it would start up right away but it did not. Instead we saw a message stating:
Failed to generate a user instance of SQL Server...

We found out through some investigation that VS2010 was trying to use a different Data Source:
.\SQLEXPRESS

Our Server Name had disappeared to a dot(.) so we tried modify the Data Source property in the Advanced Properties dialog window but this particular property was locked so typing anything in there will not be accepted. Also the only choice in the dropdown was .\SQLEXPRESS and not our Server Name.
All help to aid us in locating this dot(.) and replace it with our Server Name and to stop the dot(.) from appearing will greatly be appreciated.

A: Solution Found:
The dot(.) was found by following these steps:

*

*Right-click the project name in the Solution Explorer.

*Click on Properties from the pop-up menu

*Click on the Settings tab on the left side of the window that has opened.

*Locate a row in the Type column that has a ConnectionString with a Scope of Application.

*Click in the Value column of that row and change the Data Source.

After changing the Data Source by removing the dot(.) and replacing it with our server name, the issue went away.
Hopefully this will help someone facing the same issue as we did.


text:
Q: How to plot on R multiple variables on the X axis, and their values on the Y axis? I have this data frame:
df = data.frame(
  ID = c("foo", "bar", "baz"),
  x  = c(0.30,  0.45,  0.06),
  y  = c(1.33,  0.46,  0.04),
  z  = c(1.47,  0.02,  0.01)
)

I want a point plot with variables x, y and z on the x-axis. On the y-axis, I want the values for each variable, colored by ID.  For example, all values for the row with "foo" ID across columns x, y and z could be blue; all values for "bar" could be "red"; and so on.  Is this doable with ggplot2, or any other tool?

A: With ggplot2, you need to reshape your dataframe into a longer format. You can do it by using the function pivot_longer from tidyr:
library(tidyr)

df %>% pivot_longer(-ID, names_to = "Var", values_to = "val")

# A tibble: 9 x 3
  ID    Var     val
  <fct> <chr> <dbl>
1 foo   x      0.3
2 foo   y      1.33
3 foo   z      1.47
4 bar   x      0.45
5 bar   y      0.46
6 bar   z      0.02
7 baz   x      0.06
8 baz   y      0.04
9 baz   z      0.01

In these format, your data can be easily use to get a ggplot graph by doing:
library(dplyr)
library(tidyr)
library(ggplot2)

df %>% pivot_longer(-ID, names_to = "Var", values_to = "val") %>%
  ggplot(aes(x = Var, y = val, color = ID))+
  geom_point()


text:
Q: Link to open a spotlight search? Something like spotlight://launch?thequery that would be clickable like a regular URL and open spotlight on the query term.
Is there any way that you could write a link on the Mac that launch a spotlight query ?


text:
Q: Compass is defining path for sprites in "/image" instead of "/img" Here's my config.yml from Symfony2 :
assetic:
    debug:          %kernel.debug%
    use_controller: false
    bundles:        [ MnpirlMainBundle, MnpirlDashboardBundle ]
    filters:
        cssrewrite: ~
        sass:    ~
        compass: ~

parameters:
    assetic.filter.compass.images_dir:            %kernel.root_dir%/../web/img
    assetic.filter.compass.generated_images_path: %kernel.root_dir%/../web/img
    assetic.filter.compass.http_path: img/

The problem is that when dumping the assets via the compass filter, it's referencing to them in the css files like this :
/* Arrow */
/* line 50, icons/arrow/*.png */
.arrow-sprite, .arrow-breadcrumb, .arrow-min_down {
  background: url('img/images/icons/arrow-s8a519b0bc8.png') no-repeat;
}

The only problem is that the sprite is contained under web/img/icons and not /img/images/icons.
I really don't know why the "images" in the path is added automatically.
Thanks for any help.


text:
Q: Give DateEnd when ServiceId changes Currently, in my table all end dates are null. However, this can sometimes cause duplicates if the ServiceId changes because of a mistake made on the previous entry and we have multiple instances in a column that should be unique.
So what I want to do is rearrange this query to say something like when the ServiceId changes to provide a DateEnd. currently, if you look at the logic it says DateEnd is null. Help is greatly appreciated
right JOIN ods.Service ods ON Convert(NVARCHAR(20),dbo.number) = ods.number
    AND ods.DateEnd IS NULL AND ods.ServiceId = dbo.ServiceNumber


text:
Q: jpa entitymanager contains always returns false I have a simple test case where I save an object and then test if the object is present in db. but the contains method always returns false. The object is saved in the database
 User entity = new User();
    entity.setName("test");
    User result = ObjectManager.save(entity);

    boolean exists = ObjectManager.contains(result);

    assertTrue(exists);

@Override
public boolean contains(T obj) throws DataStoreException {
    try {
        return entityManager.contains(obj);
    } catch (Exception e) {
        throw new DataStoreException(e);
    }
}

A: According to the EntityManager documentation:

Check if the instance is a managed
  entity instance belonging to the
  current persistence context.

So it does not check if its in database. May be you have detached the entity in the save method or somehow its not in the current persistence context.
Use find or get to verify existence in db.


text:
Q: GdalInfo and Mapserver : Difference between data I'm trying to create a generic XML response from DescribeCoverage response. For my tests, i used Mapserver 7.0.7
With gdalinfo, i got this :
Driver: GTiff/GeoTIFF
Files: geostationary_ir-120_20170619083000_c7142d3e384e192461debbe8c32751c1___b8aedb3f.
tiff
Size is 2288, 2288
Coordinate System is:
PROJCS["Geostationary_Satellite",
    GEOGCS["GCS_unnamed ellipse",
        DATUM["D_unknown",
            SPHEROID["Unknown",6378160,298.2539162964669]],
        PRIMEM["Greenwich",0],
        UNIT["Degree",0.017453292519943295]],
    PROJECTION["Geostationary_Satellite"],
    PARAMETER["central_meridian",86.5],
    PARAMETER["satellite_height",35785993.3373],
    PARAMETER["false_easting",0],
    PARAMETER["false_northing",0],
    UNIT["Meter",1]]
Origin = (-5732339.950191651470959,5732339.950191651470959)
Pixel Size = (5010.786669747946689,-5010.786669747946689)
Metadata:
    AREA_OR_POINT=Area
    TIFFTAG_ARTIST=""
        TIFFTAG_DATETIME=2017:06:19 08:30:00
    TIFFTAG_DOCUMENTNAME="TIFF-MF CMS" 126 155 0
    TIFFTAG_HOSTCOMPUTER=REANIM02
        TIFFTAG_IMAGEDESCRIPTION= 126 155 0
    TIFFTAG_RESOLUTIONUNIT=1 (unitless)
    TIFFTAG_SOFTWARE=Pnm2TiffMF v1.2
    TIFFTAG_XRESOLUTION=1
    TIFFTAG_YRESOLUTION=1
Image Structure Metadata:
    COMPRESSION=JPEG
    INTERLEAVE=BAND
Corner Coordinates:
ERROR 1: tolerance condition error
Upper Left  (-5732339.950, 5732339.950)
ERROR 1: tolerance condition error
Lower Left  (-5732339.950,-5732339.950)
ERROR 1: tolerance condition error
Upper Right ( 5732339.950, 5732339.950)
ERROR 1: tolerance condition error
Lower Right ( 5732339.950,-5732339.950)
Center      (   0.0000000,   0.0000000) ( 86d30' 0.00"E,  0d 0' 0.01"N)
Band 1 Block=2288x1 Type=Byte, ColorInterp=Gray

With Mapserver DescribeCoverage response, i got this :
...
    <gml:origin>
        <gml:Point gml:id="geostationary_ir-120" srsName="http://www.opengis.net/def/crs/EPSG/0/4326">
            <gml:pos>5729834.556857 -5729834.556857</gml:pos>
        </gml:Point>
    </gml:origin>
...

Why there is a difference between these data (Origin Point) ?
Moreover, in XML response, the size of the TIFF is 2287 2287 while in gdalinfo is 2288 2288.

A: When it comes to the origin, there are two things in the play:

*

*If srsName="http://www.opengis.net/def/crs/EPSG/0/4326" then the coordinates in WCS DescribeCoverage are expressed in order Latitude-Longitude.

*In WCS the origin means the centre of the pixel while GDAL reports the origin as the top-left corner of the top left pixel which leads to half-a-pixel shifts in the coordinate values.

Lets examine the longitude coordinate
 (GDAL Lon_coordinate) + (Lon_pixel_size/2) = WCS Lon_coordinate

-573233995 + (5010.78667/2) = -5729834.557

For latitude the equation is
(GDAL Lat_coordinate) - (Lat_pixel_size/2) = WCS Lat_coordinate

So far everything looks fine. However, you have obviously configured the service somehow whong because WCS is adverticing the coverage to be in EPSG:4326 which is obviously not true (EPSG:4326 is from -90 to +90 degrees N and from -180 to +180 degrees E while in your data the numbers are much higher). Unfortunately I do not know how your Geostationary_Satellite CRS should be configured correctly for MapServer.
I can't guess the reason for the output size of 2287 2287 vs. 2288 2288 in the source data. For my mind that should not happen. I would prepare a test case with source data and complete mapfile and send to question to the mapserver-users mailing list.


text:
Q: How to find the principal components of a matrix?
Find the two principal components of the covariance matrix

$$ \Sigma= \pmatrix{6,~-1\\2,~~~~~3}$$

I have found the eigenvectors as $\lambda_1=4,$ and $\lambda_2=5$ with corresponding eigenvectors $\pmatrix{1\\2}$ and $\pmatrix{1\\1}$.I think if we concatenate the eigenvectors together in descending order we can then get the PCs as
$Y=\pmatrix{1,1\\1,2}\pmatrix{6,~-1\\2,~~~~~3}=\pmatrix{8,2\\10,5}$
is this right? I'm not sure...
Also, if I were to calculate the principal components from the correlation matrix, would the steps be identical?

A: The two eigenvectors that you obtained are the unit vectors i.e axis of your principal components.
The vector with the higher eigen value is the the first principal component i.e. its the direction towards which the variance has been maximised


text:
Q: WPF Binding ViewModel So I am currently trying to learn WPF with MVVM and I was following some tutorials online. Now that I have a simple Project, I tried to do it on my own but somehow the ListBox stays empty. It doesn't get bound to the ViewModel, I think. What am I missing here?
ViewModel:
public class PersonViewModel
{
    ObservableCollection<Person> Personen { get; set; } = new ObservableCollection<Person>();

    public PersonViewModel()
    {
        Personen.Add(new Person { Vorname = "My", Nachname = "Name", Email = "my@name.com" });
        Personen.Add(new Person { Vorname = "Max", Nachname = "Mustermann", Email = "max@mustermann.de" });
        Personen.Add(new Person { Vorname = "John", Nachname = "Doe", Email = "john@doe.com" });
        Personen.Add(new Person { Vorname = "Jane", Nachname = "Doe", Email = "jane@doe.com" });
    }
}

}
Also, I'm setting my DataContext like this:
public PersonenView()
{
    InitializeComponent();
    this.DataContext = new ViewModel.PersonViewModel();
}

A: You just need to give a public accessor to ObservableCollection Personen in your ViewModel.
You should also make the property readonly (or fire a property change notification from its setter):
public ObservableCollection<Person> Personen { get; }
    = new ObservableCollection<Person>();


text:
Q: Android Virtual Device state is offline after saving to snapshot and starting again I've seen a couple of similar problems on SO, but none of the solutions has worked for me.
Until a couple of weeks ago, saving / starting Android Virtual Devices from snapshot worked perfectly, but not any more. I have an AVD that works the first time I start it up, but, when I close the window and start it a second time, the state is "offline" and the target platform is "unknown".
Restarting adb doesn't help, and neither does restarting Eclipse. I can wipe the user data and it will work, but then I have the same problem the next time I start it.
I could wipe the user data every time, and not use snapshots, but loading up the emulator from scratch is very slow.

A: After taking a long break from Android development, I started again. I've been using Android Studio for a while and I haven't had any issues like this. If you're using Eclipse and are having this issue, try switching to Android Studio and see if that helps.


text:
Q: Rotary switch for bench supply ammeter I plan to build a bench supply using a used ATX desktop computer PSU, with 3.3v, 5v and 12v binding posts as well as a cheap voltmeter-ammeter combo module (DSN-VC288). I know it's going to be inaccurate and have terrible ripple, but it would still be a nice addition to the variable bench supply I already have.
Now, I would like to add a rotary band switch to toggle the voltmeter-ammeter module between the three outputs. However, passing the output current through the band switch is not an option, as the switch is only rated for 300 mA, and the supply should go up to at least 5A (will be adding fuses on each of the outputs).
I have a bunch of IRFZ44N MOSFETs lying around which can handle 35A continuous DC, so my first instinct is to use those to switch the currents when the rotary switch is turned. However, I wonder if I am overcomplicating it - or using the wrong tool for the job?
I am fairly new to electronics so it's very possible that there is a standard way to do this that I'm just not familiar with. Or is the MOSFET route a viable solution?

A: Another option is to get a current meter that can use an external shunt, then place one shunt on each output and route the shunt connections through the rotary switch. This way, you are not going to be switching the current path at all, which not only simplifies the design, it also ensures that the supply to the load is not interrupted when switching the meter to a different output.

A: The easiest solution would probably be to use relays. If you're concerned about the switching delays or even the sound produced during switching, use solid state relays. They are quite fast, and essentially employ FETs for switching purposes. So you're just replacing your MOSFETs for better packed versions of the same.
However, in my experience, I've found that both of them heat up quite often. This might provide a more detailed view-https://www.ia.omron.com/support/guide/18/overview.html


text:
Q: Find and classify the critical points of the system $x'=2-xy, y'=2x-y$ Question: find the critical points of the system and their stability.
$\frac{dx}{dt}=2-xy$
$\frac{dy}{dt}=2x-y$
Solving this system where each equation is set to $0$, I receive critical points of $(1,2)$ and $(-1,-2)$. To find the stability of each point, I was taught to find the eigenvalues of the matrix where the entries are the coefficients of $x$ and $y$, and that the stability depends on whether the eigenvalues are real, distinct, etc. However I'm not sure what to do in this case, as $\frac{dx}{dt}$ does not have $x$ and $y$ separated.

A: You have the right idea, but making the matrix from the coefficients of $x$ and $y$ is an oversimplication that, as you noted, fails in this case.
What you're really trying to do is construct the Jacobian by taking the derivative of each equation. Note that for a linear system, the derivative is just the coefficients, hence the simplification. For the system you provided:
$$J=\left[\begin{matrix}\left(\frac{{\rm d}x}{{\rm d}t}\right)_x&
\left(\frac{{\rm d}x}{{\rm d}t}\right)_y\\
\left(\frac{{\rm d}y}{{\rm d}t}\right)_x&
\left(\frac{{\rm d}y}{{\rm d}t}\right)_y
\end{matrix}\right]=
\left[\begin{matrix}-y&-x\\2&-1
\end{matrix}\right]$$
From there you can plug in the critical points $(x,y)$ that you found above and find the eigenvalues to determine the type of critical point.


text:
Q: Restrict images in scroll view to stretch when iPhone moved to landscape orientation I have imageViews as content for in the UIScrollView. If a user is viewing a potrait picture (320x480) and moves the iPhone in landscape orientation - the image stretches to occupy full screen. I want to restrict the image to stretch. I want a functionality similar to the photos app where image is scaled down and shows black strips in left and right.
Anyone with any suggestion how I can achieve this - would be a great help!

A: When you rotate, instead of letting your UIIMageView expand, resize its frame to be what you want it to be...that should take care of it.


text:
Q: Where OpenCSV creates the .csv files? I'm working with opencsv librarie in Eclipse and when I write something in a .csv I don't know in which folder is created. I should say that I need that the .csv file is not deleted when i turn off the app, so I can store in the assets folder, right?
My code is this:
try {
    String csv = "data.csv";
    CSVWriter writer = new CSVWriter(new FileWriter(csv));

    //Create record
    String [] record = "hello,world".split(",");
    //Write the record to file
    writer.writeNext(record);

    //close the writer
    writer.close();

} catch (IOException e) {}

A: May be you can find it file at "/data/data/your_project_package_structure/files/data.csv"
Still don't find the You can do like this. file.getAbsolutePath() gives you full path there you can identify where your file getting stored:
try
{
File file = new File("data.csv");

  // creates the file of name data.csv
  file.createNewFile();

  //you can print absolute path of file
  System.out.println(file.getAbsolutePath());

  // creates a FileWriter Object
  FileWriter writer = new FileWriter(file);

  //pass to csv writer
  CSVWriter writer = new CSVWriter(new FileWriter(csv));

              //Create record
              String [] record = "hello,world".split(",");
              //Write the record to file
              writer.writeNext(record);

              //close the writer
              writer.close();

        } catch (IOException e) {
        }


text:
Q: iOS SDK for logging to Social Media like Facebook, Twitter, linkedin,google +? I am developing new iPhone app in which i have provide users a option to login to application using Facebook,twitter,linked in and Google+.
Can some please let me know do we have any single API/sdk which supports all the social Media because its easy to implement and will not be confused with using different API/sdk's.
Thanks,
Kishore

A: I think you can use it, ''mob'' offers services in China.
It integrates the world's leading social media, including Facebook Google+ Twitter ...
To give you a link, it supports English enter link description here
But I do use Facebook, Twitter to login is very simple, official API written in great detail.


text:
Q: O que é fazer bind? Não consigo achar o significado de Bind, que me explique o que é isso.
Gostaria de um exemplo de Bind com a linguagem java, mesmo.

A: Bind ou binding são termos usados em diferentes aplicações, porém em geral fazem referência em como o Java ou qualquer linguagem faz a ligação entre determinadas coisas.
Data binding
Define como dados em diferentes formatos são mapeados de e para objetos. Existem inúmeras possibilidades, onde as mais comuns são:
Binding de requisição HTTP
Consiste em mapear atributos em requisições HTTP para objetos ou mapas. A forma como isso é feito depende do framework.
JSF por exemplo usa tags especiais como <h:inputText/>:
<h:inputText value="#{userController.username}" />

O exemplo acima iria mapear o campo no HTML com um atributo String username na classe UserController.
Frameworks como Spring MVC ou compatíveis com JAX-RS geralmente mapeiam cada parâmetro da requisição diretamente para um atributo. Por exemplo:
<input type="text" name="nome" />

Seria ligado da seguinte forma:
class Usuario {
    String nome;
    public void setNome(String nome) { ... }
}

class UsuarioController {
    @GET
    @Path("/usuario/incluir)
    public String incluir(Usuario usuario) { ... }
}

Binding de JSON e XML
Dados representados em JSON e XML podem também ser ligados com objetos usando bibliotecas como Jackson (JSON) e JAXB (XML).
Exemplo com Jackson:
ObjectMapper mapper = new ObjectMapper();
String json = "{'nome' : 'Maria'}";
Pessoa pessoa = mapper.readValue(json, Pessoa.class);

Binding de bancos de dados
Os exemplos mais conhecidos são frameworks JPA como Hibernate e Eclipselink, onde você pode configurar uma classe de forma que os dados dos campos de uma tabela sejam ligados aos atributos de uma classe, sendo possível enviar e recuperar dados sem escrever cláusulas SQL ou recuperar campo a campo.
Exemplo do mapeamento de uma entidade JPA:
@Entity
public class Pessoa {
    @Id
    long id;
    String nome;
    String endereco;
    ...
}

Method binding
Outro exemplo é o method binding ou ligação de métodos, que significa como a linguagem faz para determinar qual é o método correto que deverá ser chamado de acordo com diversos fatores:

*

*Hierarquia de classes, por exemplo quando uma subclasse sobrescreve um método ou quando uma classe implementa o método de uma interface.

*Sobrecarga de métodos, por exemplo quando métodos de mesmo nome recebem parâmetros de diferentes tipos um possuem um número diferente de parâmetros

Em alguns casos é possível determinar o método correto na hora da compilação, por exemplo, se ele for estático ou final. Nos demais vasos o método correto é determinado em tempo de execução, o que em teoria é mais lento já que inclui processamento a mais durante a execução do programa. Na verdade, a JVM inclui uma séria de otimizações que tornam o impacto do desempenho praticamente desprezível na maioria dos casos.
Outros
Outros exemplos de binding incluem:

*

*Como frameworks web MVC decidem qual método chamar de acordo com os parâmetros da requisição e configurações.

*Como frameworks de Injeção de Dependências decidem qual classe injetar baseado em critérios como hierarquia de classes, anotações e configurações.

A: Existe o Bind dinâmico e o Bind estático.
No bind estático, você tem métodos dentro de sua classe principal e os chama direto no main (os métodos tem que ser estáticos), ex:
public class Main{
    public static void varType(float var){
        System.out.println("Is an float!");
    }

    public static void varType(int var){
        System.out.println("Is an int!");
    }

    public static void varType(String var){
        System.out.println("Is an string!");
    }

    public static void main(String args[]){
        int x = 0;
        float y = 0;
        String z = "0";
        varType(x);
        varType(y);
        varType(z);
    }
}

Resumindo, é feito as chamadas no método estáticos no métodos principal.
O bind dinâmico, é criado uma instancia da classe principal para se usar seus métodos, ex:
public class Main{
    public void varType(float var){
        System.out.println("Is an float!");
    }

    public void varType(int var){
        System.out.println("Is an int!");
    }

    public void varType(String var){
        System.out.println("Is an string!");
    }

    public static void main(String args[]){
        int x = 0;
        float y = 0;
        String z = "0";
        Main m = new Main();
        m.varType(x);
        m.varType(y);
        m.varType(z);
    }
}

Referencia: http://beginnersbook.com/2013/04/java-static-dynamic-binding/


text:
Q: Find Key By Value In Array Inside Array Using Php Hey Dear I am Making Referal System With 11 Level Of Referal So Ho Can I Show All Referals And There Level I Have Tried
Array
(
    [L1] => Array
        (
            [0] => TL422632
            [1] => TL626461
        )

    [L2] => Array
        (
            [0] => TL4321
            [1] => TL191123
        )

    [L3] => Array
        (
            [0] => TL555938
        )

    [L4] => Array
        (
            [0] => TL197752
        )

    [L5] => Array
        (
            [0] => TL835309
        )

    [L6] => Array
        (
            [0] => TL495903
        )

    [L7] => Array
        (
            [0] => TL207447
        )

    [L8] => Array
        (
            [0] => TL427427
        )

    [L9] => Array
        (
            [0] => TL288884
        )

    [L10] => Array
        (
            [0] => TL251399
        )

    [L11] => Array
        (
            [0] => TL284394
        )

)

But I Don't Know Ho To Get L Number By Value For Example I Have TL284394 And I Want To Know Level So It Will Show L11 How Can I Do It

A: you can use two foreach loop inside each other and array_search() like this:
$a = array("L1" => [ 0 => "TL422632" ],"L2"=> [ 0 => "TL422635" ]);

$x = "TL422635";

foreach($a as $key=>$value){

    if($x === $value){

        return $key;
    }else{

        foreach($value as $k=>$v){
           if($x === $v){

               return array_search([$k=>$v],$a);
           }
        }
    }

}


text:
Q: React native two way binding with another component I just learning react native for three weeks and i have difficulty to update custom controller value based on the state in the parent.
Here is the fiddle:js fiddle to react native
In the code, when i type from custom control input, the parent input got updated. But when i type from the parent input, the custom control input is not updated.
Can you point out my mistakes please?
Also here is my code:
var React = require('react-native');
var {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    TextInput
} = React;

var CustomControl = React.createClass({
    propTypes: {
        onChangeTextValue: React.PropTypes.func,
        value: React.PropTypes.string.isRequired
    },

    getDefaultProps: function() {
        return {
            onChangeTextValue: () => { },
            value: ""
        }
    },

getInitialState: function() {
    return {
        text: this.props.value
    };
},

setText: function(value) {
    this.setState({
        text: value
    });
    try {
        return this.props.onChangeTextValue(value);
    } catch (_error) { }
},

render: function(){
    return (
        <TextInput
            style={{ height: 40, borderColor: 'gray',
                     borderWidth: 1 }}
            onChangeText={this.setText}
            value={this.state.text}
            />
        )
    }
});

var SampleApp = React.createClass({
    getInitialState() {
        return {
            'textValue': ''
        }
    },
    render: function() {
        return (
           <View style={styles.container}>
              <Text>
                  Parent Input
              </Text>
              <TextInput
        style={{height: 40, borderColor: 'gray', borderWidth: 1}}
        onChangeText={(text) => this.setState({textValue:text})}
        value={this.state.textValue}
              />
              <Text>
                  Custom control input
              </Text>

              <CustomControl
        onChangeTextValue={(text) => this.setState({textValue:text})}
                value={this.state.textValue}
              />

              <Text style={styles.instructions}>
                  Updating the parent input should update the custom control value too. Right now only when we update the custom control value, the parent input is updated.
              </Text>

          </View>
        );
    }
});

Thank you :)

A: You are storing state in your child component which you shouldn't be, the parent component passes a handler onChangeTextValue which you should be using instead.
Try instead for your child component
var CustomControl = React.createClass({
    propTypes: {
        onChangeTextValue: React.PropTypes.func,
        value: React.PropTypes.string.isRequired
    },

    render: function(){
        return (
            <TextInput
                style={{ height: 40, borderColor: 'gray',
                         borderWidth: 1 }}
                onChangeText={this.props.onChangeTextValue}
                value={this.props.value}
                />
            )
        }
});


text:
Q: SQL Server: Updating rows with dependencies in the same table There is the table CSBaumkontakt and in this table I've contact persons and companies. CSBaumkontakt is a tree structure like this:
[+] master company (Root)
  [+] company (Dad)
    [+] contact person

The company (Dad) of a contact person is connected with its DadPubIndex and the RelPubIndex from the company. And the application works only properly if the Dad and Root of the company are the same as the Root of the contact person. This means the RootPubIndex of the contact person must be the same like the DadPubindex and the RootPubindex of its company. But this is not always the case.
See picture below before the change:
contact person
[RelPubIndex] [9FC6CD387AE91B46A471E1B82963E36A]
[RooPubIndex] [F7BC36A0-AD4F-49D5-B4FC-AD529C7EA738]
[DadPubIndex] [2143640C-3ABF-440C-B094-2128F4495874]
[class] [contact person]

company of the contact person
[RelPubIndex] [2143640C-3ABF-440C-B094-2128F4495874]
[RootPubIndex] [D66035CB-B7AD-4D54-9FC7-AE6E7F32662D]
[DadPubIndex] [D66035CB-B7AD-4D54-9FC7-AE6E7F32662D]
[class] [company]

After the change it looks like this:
contact person
[RelPubIndex] [9FC6CD387AE91B46A471E1B82963E36A]
[RooPubIndex] [D66035CB-B7AD-4D54-9FC7-AE6E7F32662D]
[DadPubIndex] [2143640C-3ABF-440C-B094-2128F4495874]
[class] [contact person]

company of the contact person
[RelPubIndex] [2143640C-3ABF-440C-B094-2128F4495874]
[RootPubIndex] [D66035CB-B7AD-4D54-9FC7-AE6E7F32662D]
[DadPubIndex] [D66035CB-B7AD-4D54-9FC7-AE6E7F32662D]
[class] [company]

Now I need an UPDATE script which sets the RooPubIndex of every contact person to the DadPubindex/RootPubIndex (if the same, but it should usually be so) from its company.
I'm a bit at loss how to connect those rows within the same table to UPDATE the records with the desired values. How can I accomplish this?

A: I think I've made a solution. Still need to review the data, but it seems like it works.
update csbaum1 set csbaum1.rootpubindex = csbaum2.DadPubIndex
from CSBaumKontakt as csbaum1
inner join CSBaumKontakt as csbaum2
on csbaum1.DadPubIndex = csbaum2.RelPubIndex
where csbaum1.Klasse = 'contact person'
and csbaum1.RootPubIndex <> csbaum2.DadPubIndex
and csbaum2.RootPubIndex = csbaum2.dadpubindex

Thanks for reading.


text:
Q: Apache2 - Error 403 forbidden I develop projects that I've located in /home/user/projects directory. This directory is chmod 777. The problem is that I'm always getting Error 403 Forbidden when I try to access this directory or any subdirectory. This is how my /etc/apache2/sites-available/000-default.conf looks like:
<VirtualHost *:80>
    ServerName localhost
    ServerAdmin user@user.com
    DocumentRoot /home/user/projects

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

    Options +FollowSymLinks

    <Directory />
            Options FollowSymLinks
            AllowOverride None
            Order allow,deny
            allow from all
    </Directory>
    <Directory /home/gtakacs/projects>
            Options Indexes FollowSymLinks MultiViews
            AllowOverride all
            Order allow,deny
            allow from all
            Require all granted
    </Directory>
</VirtualHost>

What's wrong with this? When I used /var/www as my document root, everything worked.

A: EDIT : try doing chmod -R 777 /home to make sure all your home is available (note that this solution is NOT RECOMENDED, having your project in /var/www would definitely be a better solution in my opinion)
(Can't comment so post reply)
Isn't there a config file in your project where you're supposed to set who can access the app? Check if you didn't forget to add your ip adress and domain name in this file.
When using Apache2 with Django framework (python), I had the same error, and it was because I forgot to add the domain name to authorized hosts.
You can also check access.log and error.log to have more detailed informations on what caused the error.

A: Command out:
#Order allow,deny

A: I had this issue before, the problem might be that your document root does not contain the described directories.


text:
Q: Ruby on Rails: Sending javascript data to ruby controller I would like to send a javascript array to be processed by a method in my controller.
I think I am doing this way wrong. I am a total RoR, jquery, and ajax noobie. Here is what I have. Please give me some guidelines:

<button>Save!</button>

I get this error:
POST http://10.10.136.244:6500/qtl_table/save 500 (Internal Server Error)

and
Started POST "/qtl_table/save" for 10.64.229.59 at Mon Jun 25 16:58:46 -0500 2012
  Processing by QtlTableController#save as
  Parameters: {"125,0,\"\",\"Ph upt 1-2\""=>{","=>{"125,1,\"\",\"DOR364\""=>{","=>{"125,2,\"\",\"G19833\""=>nil}}}}}
LOGGER WORKS
Completed 500 Internal Server Error in 81ms

ActionView::MissingTemplate (Missing template qtl_table/save with {:formats=>[:html], :handlers=>[:rjs, :rhtml, :erb, :rxml, :builder], :locale=>[:en, :en]} in view paths "/usr/home/benjamin/phavubase/qtl/app/views", "/usr/home/benjamin/phavubase/qtl/ruby/1.8/gems/declarative_authorization-0.5.5/app/views", "/usr/home/benjamin/phavubase/qtl/ruby/1.8/gems/devise_cas_authenticatable-1.1.1/app/views", "/usr/home/benjamin/phavubase/qtl/ruby/1.8/gems/devise-1.2.1/app/views", "/usr/home/benjamin/phavubase/qtl/ruby/1.8/gems/kaminari-0.12.4/app/views"):
  app/controllers/qtl_table_controller.rb:18:in `data'
  app/controllers/qtl_table_controller.rb:25:in `save'

Rendered ruby/1.8/gems/actionpack-3.0.8/lib/action_dispatch/middleware/templates/rescues/missing_template.erb within rescues/layout (0.8ms)

EDIT:
app/controllers/qtl_table_controller.rb
...
  def save
    logger.debug "\nLOOK! WE SAVED! #{params[data]}\n"
    render "index"
  end
...

I added render :layout => false but I am still getting the missing template error. Also, someone suggested I just begin adding logic to my controller but the data parameter looks really funky. Its supposed to be an array of arrays that I turned into a string. Could you guys give me some more help?

A: You should either create a template in app/views/qtl_table/save.html.erb or render something in your controller. If nothing is rendered in the controller action, Rails tries to display default template, and you don't have one.

A: Agreed with Riateche's answer. You'll need to add some logic to the controller to respond correctly.
Looking at your console output, you can see the json data in the parameters hash. You can simply access the values in your controller as such:
params["125,0,\"\",\"Ph upt 1-2\""]
params["125,0,\"\",\"Ph upt 1-2\""][","]

You can just map it your activerecord model and save it.

A: Since you want it to respond in AJAX, you can tell Rails not to render anything by adding
render :layout => false

to the controller action


text:
Q: Где найти описание параметров, которые даются файлам в /etc/X11/trusted. Astra Linux(1.7) Хотел бы поинтересоваться, где найти: что значат параметры, которыми помечаются файлы в файле /etc/X11/trusted?
Например, файл /usr/bin/fly-wm помечен значением WM_R, а fly-vkbd KBD_R и PROP_R. Что они значат?
Вот так это выглядит:
/usr/bin/Xnest(NESTED_R|MAC_R|KBD_R)

Да и вообще где хоть про этот trusted почитать, нашёл только пару мелких упоминаний.

A: Это файл конфигурации xparsec. Документацию к этому наверное надо искать в man parsec


text:
Q: Pandas read_excel returning 'not enough values to unpack (expected 2, got 1)' My problem is pretty simple, I'm just trying to read a locally located excel file into a dataframe using pandas.
filename = 'test.xlsx'
df = pd.read_excel(filename)

The xlsx file has multiple sheets, but I get the same "ValueError: not enough values to unpack (expected 2, got 1)" even when specifying sheetname.

Traceback (most recent call last):
File "", line 1, in
      pd.read_excel(filename)
File
  "C:\ProgramData\Anaconda3\lib\site-packages\pandas\io\excel.py", line
  200, in read_excel
      io = ExcelFile(io, engine=engine)
File
  "C:\ProgramData\Anaconda3\lib\site-packages\pandas\io\excel.py", line
  257, in init
      self.book = xlrd.open_workbook(io)
File "C:\ProgramData\Anaconda3\lib\site-packages\xlrd__init__.py",
  line 422, in open_workbook
      ragged_rows=ragged_rows,
File "C:\ProgramData\Anaconda3\lib\site-packages\xlrd\xlsx.py", line
  833, in open_workbook_2007_xml
      x12sheet.process_stream(zflo, heading)
File "C:\ProgramData\Anaconda3\lib\site-packages\xlrd\xlsx.py", line
  553, in own_process_stream
      self.do_merge_cell(elem)
File "C:\ProgramData\Anaconda3\lib\site-packages\xlrd\xlsx.py", line
  609, in do_merge_cell
      first_cell_ref, last_cell_ref = ref.split(':')
ValueError: not enough values to unpack (expected 2, got 1)

Edit: I created a new Excel file, and copied two of the tabs from the original file over to the new Excel file. Pandas read_excel worked with the new file. However, I want to be able to work from the original.

A: I still don't fully understand the mechanics of this issue, but I was able to work around it. I used urlopen from urllib.requests to download the file locally, and used openpyxl to load the workbook, and then loaded the sheet I wanted. The sheet has 5 rows of merged cells at the top and 5 rows of merged cells at the bottom. I then un-merged just the last 5 rows of merged cells using the unmerge_cells method. I then saved the workbook again with the modified sheet. I was then able to run pd.read_excel with the skiprows=5 parameter. It worked this way.

A: Possible workaround could be as following:
import openpyxl

wb1 = openpyxl.load_workbook('filename.xlsx') ## opening the file
sheets_list = list(wb1.get_sheet_names()) ## getting all sheets' streams
active_sheet = wb1.get_sheet_by_name(sheets_list[0]) ## picking up the first sheet

df1 = pd.DataFrame(active_sheet.values)

df1 = df1.iloc[3 : , :] ## skipping first three rows assuming merged cells are in
                        ## this range


text:
Q: rvalue delegation, or the rvalue equivalent of a const member function struct that
{
    that &frob()
    {
        return *this;
    }
    that frob() const
    {
        return that(*this);
    }

    //that &&frob() && //<-called only if *this is an rvalue
    //{
    //    return move(*this);
    //}

    that()
    {
        // make things
    }
    that(const that &other)
    {
        // copy things
    }
    that(that &&other)
    {
        // move things
    }
};

Obviously the function in comments above is not legal C++, but I need to know if there is a way to accomplish this:
that().frob().frob().frob();

and so on, while each call to frob() would effectively call the "move" version thereof. As this is something that can be determined at compile time, I can't think of any reason for it to not exist in some form.
I can write something like this:
that &&frob(that &&t)
{
    return t;
}

Which would result in this:
frob(frob(frob(that())));

Which is somewhat annoying to read and doesn't accomplish my goal of "spelling things out" with delegation.

A: If you want the && annotated function to play well with others, you should use the & annotation on the others.
that &frob() &
{
    return *this;
}
that frob() const &
{
    return that(*this);
}

A: No, there is no way to determine if an object is an rvalue from within the object. The best you can do is copy it if it is const and move it if its not:
that frob() const
{
    return *this;
}

that frob()
{
    return std::move(*this);
}

EDIT
Further reaserch shows that you actually can, as @Potatoswatter pointed out, but its called ref-qualification and not annotation.


text:
Q: Selenium remotewebdriver stuck before launching browser I'm trying to launch Firefox remotely on a windows machine from UNIX box using remotewebdriver I am also starting the selenium node remotely using ssh(It starts fine) using Cygwin and OpenSSH.
(I've installed firefox in the path c:\cygwin64\home\Administrator\firefox)
I am launching the grid node using:

java -jar selenium-server-standalone-2.53.0.jar -role node -hub http://HUB_IP:4444/grid/register -port 5566 -Dwebdriver.gecko.driver=geckodriver.exe -Dwebdriver.firefox.bin="firefox/firefox.exe"

However, the execution gets stcuk at:

1486534648695   mozprofile::profile     INFO    Using profile path C:\cygwin64\tmp\rust_mozprofile.lpsQghom5pxe
  1486534648699   geckodriver::marionette INFO    Starting browser C:\cygwin64\home\Administrator\firefox\firefox.exe
  1486534648719   geckodriver::marionette INFO    Connecting to Marionette on localhost:57059
  1486534650177   Marionette      INFO    Listening on port 57059

I can see the firefox process starts but browser does not launch and gets stuck.(Tried the same for chrome, getting the same issue)
After waiting for a long time, node throws exception:,

A coding exception was thrown and uncaught in a Task.
  Full message: TypeError: NetworkError when attempting to fetch resource.
  Full stack:

EDIT:
I cannot launch Firefox/Chrome from Cygwin when I manually go to the installation path and give the command firefox.exe. This gets stuck as well but a process is started. This occurs only when I use a remote connection. Though, using Cygwin locally launches the browsers.
Is there a way to enable this?


text:
Q: How can I increase RAM capacity in Colab pro+? How can I  increase RAM capacity in Colab pro + ?
I need RAM > 35 GB but Colab pro+ provide only 12 GB
Regards
Chaiyan S.

A: To set your notebook preference to use a high-memory runtime, select the Runtime > 'Change runtime type' menu, and then select High-RAM in the Runtime shape dropdown.
Then you can check it by running following code in the cell:
from psutil import virtual_memory
ram_gb = virtual_memory().total / 1e9
print('Your runtime has {:.1f} gigabytes of available RAM\n'.format(ram_gb))

if ram_gb < 20:
  print('Not using a high-RAM runtime')
else:
  print('You are using a high-RAM runtime!')


text:
Q: Why does TortoiseSVN still show files in Excluded directories? I'm trying to keep the Expression Web  editing files from showing up in TortoiseSVN.
I added _vti_cnf [folder] to the Ignores List (and disabled the Config File so it didn't overwrite /overule the Tortoise settings)

But files in that folder still shows up in the list.

What's going on here?

A: It looks like you already have added them to the repository, so that they now shows as missing. Select the files in the working copy, do a right click and select TSVN->delete. Now commit this change. Now all new files in the folder are ignored.


text:
Q: Selective XML parsing This the xml file I have
<?xml version="1.0" encoding="UTF-8"?>
<Bank>
      <Account type="saving">
            <Id>1001</Id>
            <Name>Jack Robinson</Name>
            <Amt>10000</Amt>
      </Account>
      <Account type="current">
            <Id>1002</Id>
            <Name>Sony Corporation</Name>
            <Amt>1000000</Amt>
      </Account>
</Bank>

I need to parse this xml and get the contents between <Bank>...</Bank>. My output xml should be
<Account type="saving">
            <Id>1001</Id>
            <Name>Jack Robinson</Name>
            <Amt>10000</Amt>
      </Account>
      <Account type="current">
            <Id>1002</Id>
            <Name>Sony Corporation</Name>
            <Amt>1000000</Amt>
      </Account>

Any ideas on how to achieve this using Java?

A: First of all:
your output XML is not valid XML.
XML must have root element which you try to remove.
As @Seelenvirtuose said, there are tons of ways to do what you want on many levels.
From simple manipulating original XML as String and up to using DOM model, JAXB, XPath/XQuery, or XSLT. It is matter of your choice.
As example with Apache commons utils:
String resultString = org.apache.commons.lang.StringUtils.substringBetween(originalXMLString,"<Bank>","</Bank>").trim();

Of course your output can be only String, because it is not valid XML. Then you can do with that String whatever you want - print it, store in file or DB etc...


text:
Q: Postgres procedure not updating selected row I'm working on a Django application that uses Stored Procedures on a PostgreSQL database.
I'm stuck in a very strange (for me, at least) problem.
I have the following SP code:
create procedure inbound_550(p_operation_id integer)
    language plpgsql
as
$$
declare

    file_operation record;

    ...

begin

    select
        oo.id,
        oo.file_id,
        ot.transaction_type_id,
        ot.code
    into
        file_operation
    from
        operations_operation oo
    join
        operations_type ot on ot.id = oo.type_id
    where
        oo.id = p_operation_id;

    for line in

        # select some records from other tables using parameter p_operation_id on some FKs

    loop

        # business logic here with some calculations and some inserts
        sum_tax_day = X # some value

    end loop;

    operation_avg_year_tax = ((1 + (sum_tax_day / 100)) ^ 252) - 1;
    update operations_operation set avg_year_tax = operation_avg_year_tax where id = p_operation_id;

end
$$;

The problem is, when I call this procedure from the console it runs fine and the field avg_year_tax gets updated with the operation_avg_year_tax value but, when I call the procedure from my application using Python and psycopg2 the field is not updated, it seems that the update statement is ignored.
Here is the Python code used to call the procedure:
from django.db import connection

class Inbound:

    def __init__(self, operation):

        self.operation = operation

    def main(self):

        conn = connection
        cursor = conn.cursor()
        cursor.execute('call inbound_550({});'.format(self.operation.id))
        conn.commit()
        cursor.close()

I've tried setting the autocommit both True and False but still no update.
Any ideas? Been stuck in this for a couple of days already.
Thanks in advance.


text:
Q: How to prove the limit exist? Let:
$\displaystyle f=\int_V \dfrac{x-x'}{|\mathbf{r}-\mathbf{r'}|^3}\ dV'$
where $V'$ is a finite volume in space
$\mathbf{r}=(x,y,z)$ are coordinates of all space
$\mathbf{r'}=(x',y',z')$ are coordinates of $V'$
$|\mathbf{r}-\mathbf{r'}|=[(x-x')^2+(y-y')^2+(z-z')^2]^{1/2}$

How to prove that:
$\lim\limits_{\Delta x \to 0} \dfrac{f(x+\Delta x,y,z)-f(x,y,z)}{\Delta x}$ exist

$\text{ }$

MY TRY:
I am not sure whether this method would work. If it doesn't please suggest another method to reach my goal.
\begin{align}
&\lim\limits_{\Delta x \to 0} \dfrac{f(x+\Delta x,y,z)-f(x,y,z)}{\Delta x}\\
=&\lim\limits_{\Delta x \to 0}\dfrac{\displaystyle\int_{V'} \dfrac{(x+\Delta x)-x'}{|\mathbf{r}(x+\Delta x,y,z)-\mathbf{r'}|^3}\ dV' - \int_{V'} \dfrac{x-x'}{|\mathbf{r}(x,y,z)-\mathbf{r'}|^3}\ dV'}{\Delta x}\\
=&\lim\limits_{\Delta x \to 0}\displaystyle\int_{V'}
\dfrac{\left(  \dfrac{(x+\Delta x)-x'}{|\mathbf{r}(x+\Delta x,y,z)-\mathbf{r'}|^3}
-\dfrac{x-x'}{|\mathbf{r}(x,y,z)-\mathbf{r'}|^3}   \right)}{\Delta x}dV'
\end{align}
Now if only I could take the limit inside the integral (with respect to $V′$),I can proceed to show the limit exists.

If we can't do that and this method doesn't work, please suggest another method to show that the limit exists.

A: Assume that $C$ is a $3$-dimensional body with a smooth boundary and ${\rm
vol}\ C<\infty$. Define $f(\textbf{r}) =\int_C\
\frac{x-x'}{|\textbf{r}-\textbf{r}'|^3}\ d{\rm vol}\ (\textbf{r}' ) $
Prove that $f$ is finite.
Proof : $\int_{B_\epsilon (0)}\ \frac{1}{|{\bf r}|^2} \ d{\rm vol}\
({\bf r}) \leq C\epsilon$ for some $l>0$ and note that $
\frac{|x-x'|}{|\textbf{r}-\textbf{r}'|^3}\leq \frac{1}{|
\textbf{r}-\textbf{r}'|^2}$
So $$ |f( \textbf{r} )| \leq \int_{B_\epsilon ({\bf r} )}\
\frac{|x-x'|}{|\textbf{r}-\textbf{r}'|^3}\ d{\rm vol}\ (\textbf{r}')
+\int_{C-B_\epsilon(\textbf{r}) }\ \frac{1}{|\textbf{r}-
\textbf{r}'|^2}\ d{\rm vol}\ (\textbf{r} ')
$$
$$ \leq l\epsilon +\int_{C-B_\epsilon(\textbf{r}) }\ \frac{1}{\epsilon^2} \
 d{\rm vol}\ (\textbf{r} ')
\leq l\epsilon + \frac{1}{\epsilon^2}{\rm vol}\ C $$


text:
Q: preg_match question, how to do this? Say I have the following:
$var = "127.0.0.1 (127.0.0.1) 56(84) bytes of data. 64 bytes from 127.0.0.1: icmp_seq=1 ttl=57 time=19.5 ms --- 127.0.0.1 ping statistics --- 1 packets transmitted, 1 received, 0% packet loss, time 0ms rtt min/avg/max/mdev = 19.548/19.548/19.548/0.000 ms ";

How can I return so it just says
$var2 = "19.5";

So it basically grabs whats in this part: time=19.5 ms ---
Thank you
EDIT
I think I have figured it out myself:
$var = "127.0.0.1 (127.0.0.1) 56(84) bytes of data. 64 bytes from 127.0.0.1: icmp_seq=1 ttl=57 time=19.5 ms --- 127.0.0.1 ping statistics --- 1 packets transmitted, 1 received, 0% packet loss, time 0ms rtt min/avg/max/mdev = 19.548/19.548/19.548/0.000 ms";

$var2 = preg_match("/time=(.*) ms ---/", $var, $matches);
print_r($matches[1]);

I don't know if this is the right way to do it, but it seems to work?

A: Try this:
$var = "127.0.0.1 (127.0.0.1) 56(84) bytes of data. 64 bytes from 127.0.0.1: icmp_seq=1 ttl=57 time=19.5 ms --- 127.0.0.1 ping statistics --- 1 packets transmitted, 1 received, 0% packet loss, time 0ms rtt min/avg/max/mdev = 19.548/19.548/19.548/0.000 ms ";
if(preg_match('/time=(\d+\.\d+)/', $var, $match)) {
  $var2 = $match[1];
  echo $var2;
}

which will echo:
19.5

$match[1] will contain the entire match (time=19.5), in your case, and $match[1] contains match group 1 from the pattern: which is the number 19.5.

A:
preg_match("/time=([\d.]+).ms/",$var,$matches);
//var_dump($matches)
//$match[1] now holds the 19.5
?>

Enjoy

A: This could do it with preg_match:
if (preg_match("/time=(.*?) ms/", $line, $m)) {
  $time = (float) $m[1];
}

Or with explode:
$fields = explode("=", $line);
$time = (float) $fields[4];

A: You could retrieve this with the following pattern:
preg_match('/time=([^ ]+) /',$matches);
echo $matches[1]; // 19.5

Matches after time= at least one character (+) that isn't a space ([^ ]).

A: Use this regex in your preg_match call
time=([\d\.]+)

A: <?php

$var="127.0.0.1 (127.0.0.1) 56(84) bytes of data. 64 bytes from 127.0.0.1: icmp_seq=1 ttl=57 time=19.5 ms --- 127.0.0.1 ping statistics --- 1 packets transmitted, 1 received, 0% packet loss, time 0ms rtt min/avg/max/mdev = 19.548/19.548/19.548/0.000 ms ";

preg_match("/time=([0-9.]+)/", $var, $matches);

$var2 = $matches[1];

echo $var2;

?>

Edit: Or you can edit the regex to:
preg_match("/time\s*=\s*([0-9.]+)/", $var, $matches);

So that it matches "time=xx.x" or "time = xx.x".