Q:

Proving Two Zip file are identical

I migrated some files from one Version Control System to another. I have to prove that content are identical (between source and destination, denote 1 , 2). There are a few zips files (lets call them A B C) each of which contains hundreds of files. I am looking at best way to do CRC comparison between content in old VCS against the new one.
1) Generate CRC on each ZIP file as a whole and compare the CRC of 2 corresponding zips file.  ZIP-ZIP CRC comparison.
Obviously, this approach will be easier. But I don't know what will include in calculation of CRC. Or even if CRC of two zip files with identical file content might be different.(modified date?).
2) Compare CRC of each files in zip against corresponding files. File-File CRC Comparison
with this approach, I will have to write a script that goes through each file in zip (say A1) and extract their CRC. Build a list with [path file name, crc]. do the same for zip(A2). Compare list.
Have anyone ever done something like this?

A:

If you're sure the compression algorithm used to create both zip files is identical then you can just compare the zip files.
Otherwise you will need to decompress the zips and compare contained files.
Hashes generated when compressing could be used to speed up comparisons if you'll accept the chance of collisions causing false positives. This can quickly show files to be different.
But collisions mean the best you can do with a hash is show files to "very likely" be identical. With enough bits and a good hashing algorithm we're talking about odds akin to winning the lottery. In a practical application you'll have to decide if speed is worth the risk.
If you're serious about Proof the files are identical you can't ignore unlikely cases. Quarters sometimes land on their edges. Sometimes hashes collide. But sometimes bits flip on you randomly and go undetected. So don't think a bit by bit comparison of the uncompressed files is guarantied to give you a perfect proof either.  What you get is lots of bits giving you really good odds.
This last is when the CRC is useful. Not as a digest. It's an error check. It makes a bit copy error less likely to go unnoticed. Still not perfect because CRC bits can be badly copied as well.
So there just isn't a perfect proof. Do it right and you can have fantastic levels of confidence, if you have time for that.


Q:

Conditional Formatting with Unequal Row Elements

I have an Excel table. I want to highlight the rows in which at least one element is different from the others for a given row. How can I do that? An example:

 PRODUCT         COLUMN 1   COLUMN 2     COLUMN 3
 Product 1       2,080.30    2,070.00    2,080.30
 Product 2       2,728.20    2,728.20    2,728.20
 Product 3       3.50        3.50        3.50
 Product 4       1,720.00    1,720.00    1,720.00
 Product 5       513.50      513.50      513.50

Row 1 will be highlighted.
Thanks

A:

I would use a slightly different approach to those suggested in the link, a bit simpler I think
If your data is in columns B,C and D starting at row 2 then I would select the whole range and apply this formula in conditional formatting
=OR(B2<>C2,C2<>D2)


Q:

ASIHTTPRequest giving me problems

I have a code that sends POST data to a PHP website. Code:
request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:@"http://www.example.com/Testing/Testing.php"]];
    [request setPostValue:targettype forKey:@"targettype"];
    [request setPostValue:targetmethod forKey:@"targetmethod"];
    [request setPostValue:sourceurl forKey:@"sourceurl"];
    [request setPostValue:filepath forKey:@"filepath"];

    [request setDelegate:self];
    [request startAsynchronous];

This is working perfectly. Once this data is sent and the PHP script outputs some data, the script creates a .txt file. Once the iPhone reads the contents of the .txt file, I want to run ASIHTTPRequest to a different PHP script that is supposed to delete this .txt file. From a PHP end, everything seems to be working, and the data is being received perfectly by the iPhone. However, once the data is received, I have a if...then statement that checks for the data and then once the data is present, I want to call ASIHTTPRequest to delete the .txt. This is the code I used to POST the data to the new PHP location:
{...
    imageView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString: string]]];
            [self deletefile];
   }

-(void) deletefile {
        request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:@"http://www.prajoth.com/Testing/Testing.php"]];
        [request setPostValue:@"hey" forKey:@"targettype"];
        [request setPostValue:@"hey" forKey:@"targetmethod"];
        [request setPostValue:@"hey" forKey:@"sourceurl"];
        [request setPostValue:filepath forKey:@"filepath"];

        [request setDelegate:self];
        [request startAsynchronous];

    }

This is for some reason, throwing up a EXC_BAD_ACCESS. The console does not show any error message though. Please help!

A:

Based on the code you've pasted, it's going to be difficult to figure this out. Where exactly is your app throwing the exception? It could be perhaps one of your global variables doesn't exist any more (filepath, for example), but then again it could also be something elsewhere in your code. EXC_BAD_ACCESS messages, as you can probably guess, occur when you try to access an object that's no longer in memory, so maybe you are releasing something earlier on which you now rely on?


Q:

PHP Warning: Illegal string offset 'error' roundcube plugin

getting an error PHP Warning:  Illegal string offset 'error' in ../roundcube/plugins/vtrc/vtwsclib/Vtiger/WSClient.php on line 93
function in php file (line 93 ends)
function hasError($result) {
        if(isset($result[success]) && $result[success] === true) {
            $this->_lasterror = false;
            return false;
        }
        $this->_lasterror = $result[error];
        return true;

A:

You have two IMPORTANT errors!!
First of all : You need to use ' OR " to get the value of an Array
$value = $array["KEY_HERE"];

Same as
$value = $array['KEY_HERE'];

PHP is friendly with quotes =)

Second : You need to check if "error" Key exists in Array $result like as "success"
function hasError($result) {
    if(isset($result["success"]) && $result["success"] === true) {
        ... CODE ...
    }
    if(isset($result["error"])) {
        ... CODE ...
    }
    ... REST OF METHOD ...
}

What does it mean "Illegal string offset 'error'? Exactly that not exists Index 'error' for Array $result. Please be careful, because the script had tried to access in a memory piece that is not declared (initialized - set) for this array. It's dangerous !!
$myArray = array();                /** Empty array **/
$myArray["error"] = "";            /** set index "error" with "" value **/

echo isset($myArray["error"]);     /** echo TRUE **/
echo isset($myArray["success"]);   /** echo FALSE **/
echo $myArray["success"];          /** throw exception "Illegal string offset 'success' ..." because not set in Array **/


Q:

Find port number where HDFS is listening

I want to access hdfs with fully qualified names such as :
hadoop fs -ls hdfs://machine-name:8020/user

I could also simply access hdfs with
hadoop fs -ls /user

However, I am writing test cases that should work on different distributions(HDP, Cloudera, MapR...etc) which involves accessing hdfs files with qualified names.
I understand that hdfs://machine-name:8020 is defined in core-site.xml as fs.default.name. But this seems to be different on different distributions. For example, hdfs is maprfs on MapR. IBM BigInsights don't even have core-site.xml in $HADOOP_HOME/conf.
There doesn't seem to a way hadoop tells me what's defined in fs.default.name with it's command line options.
How can I get the value defined in fs.default.name reliably from command line?
The test will always be running on namenode, so machine name is easy. But getting the port number(8020) is a bit difficult. I tried lsof, netstat.. but still couldn't find a reliable way.

A:

Below command available in Apache hadoop 2.7.0 onwards, this can be used for getting the values for the hadoop configuration properties. fs.default.name is deprecated in hadoop 2.0, fs.defaultFS is the updated value. Not sure whether this will work incase of maprfs.
hdfs getconf -confKey fs.defaultFS  # ( new property )

or
hdfs getconf -confKey fs.default.name    # ( old property )

Not sure whether there is any command line utilities available for retrieving configuration properties values in Mapr or hadoop 0.20 hadoop versions. In case of this situation you better try the same in Java for retrieving the value corresponding to a configuration property.
Configuration hadoop conf = Configuration.getConf();
System.out.println(conf.get("fs.default.name"));

A:

fs.default.name is deprecated.
use : hdfs getconf -confKey fs.defaultFS

A:

I encountered this answer when I was looking for HDFS URI. Generally that's a URL pointing to the namenode. While hdfs getconf -confKey fs.defaultFS gets me the name of the nameservice but it won't help me building the HDFS URI.
I tried the command below to get a list of the namenodes instead
 hdfs getconf -namenodes

This gave me a list of all the namenodes, primary first followed by secondary. After that constructing the HDFS URI was simple
hdfs://<primarynamenode>/


Q:

Widening the stone entrance into a crawlspace

I've got a 200 year old house with a crawl space under one corner of the house. The entrance to that crawl space is very tight (pictured below), and I am a large man. I want to expand the entrance to the crawl space a couple of inches downward, and potentially a couple of inches to the left. The wall is granite stone construction, so i was planning on breaking down the mortar on the flat surface and removing a layer of stone. I need to repoint the walls on the inside of the crawl space, and it's currently very difficult for me to get in.
Can I lengthen or widen the hole a few inches without worrying about structural integrity?
EDIT: Added more photos for clarity. Apologies if it's still not clear, there's a lot of ductwork in the way that makes getting a good shot of it all difficult.

A:

Widening this opening to any width less than a foot shouldn't be any issue. Even if there's a bearing wall resting above the bottom plate from the story above, it looks like the bottom plate matches the floor joist sizes and it will have plenty of capacity for spanning such a short opening. Just make sure you notch the opening as vertically as possible and the base of the cut into the wall is not cut back more than the top.


Q:

Publishing posts to Twitter and social networks

It's good to see that I am getting quality answers from Stack Exchange websites for the programming questions instantly. To promote the question more widely, the Twitter and Facebook post links are also there.
The fundamental problems with this is, most of the corporate proxies have blocked the social networks. It would be helpful if the Stack Overflow/Stack Exchange websites can implement the Twitter/Facebook APIs themselves and post the post questions without redirecting to the social network websites.
For example, Quora has implemented this feature, which I found really good.

A:

Wouldn't this imply that we have the user's login credentials on Twitter and Facebook -- to authenticate on their behalf and post something?
We have no such information, nor do we want it. In fact, I would violently object to us having that information.

A:

Not possible.
Facebook and Twitter both require apps to use OAuth, which is an authentication method explicitly created to allow login without sharing login credentials with the third-party.
Practically, what this means is that any app (including mobile) which wants to "log in as you" must pop up a frame with a login window (or, if, through cookies, you are already logged in, it will simply close automatically and return the new token).
This means that your computer needs to be able to make a connection to Facebook or Twitter to perform the authentication.  If these sites are blocked, whether StackExchange uses the APIs or not doesn't help you at all, because they can't get an authentication token — unless of course, you recently authenticated outside the blocked network.
Facebook explicitly disallows storing of a username and password and provides no (public) API for gaining an authentication token with these credentials, even if you had them.


Q:

Difference between throw and $pscmdlet.ThrowTerminatingerror()?

In PowerShell, what is the difference between throw $ErrorMsg and $PScmdlet.ThrowTerminatingError($ErrorMsg)?
Are they same or different? If they are different which one is preferable?

A:

Throw creates a script-terminating (runspace-terminating) error, whereas $PScmdlet.ThrowTerminatingError() creates a statement-terminating error.
Note: These aren't official terms (the docs currently only vaguely reference terminating errors in the abstract, without scope), but they're useful for describing the de-facto behavior.
In short: By default,

a script-terminating error terminates the entire runspace, i.e., the running script and all its callers, with no further statements getting executed.

The only way to intercept them is by using a try / catch statement (or, less commonly, a trap statement).

whereas a statement-terminating error terminates only the current statement (the function calling $PScmdlet.ThrowTerminatingError() and the statement it is a part of, which is often a pipeline), with execution continuing with the next statement.

They too can be intercepted with try / catch (or trap), or ignored with the $ErrorActionPreference preference variable set to SilentlyContinue; by contrast, the -ErrorAction common parameter has no effect on them.

Conversely, you can promote them to script-terminating errors with $ErrorActionPreference = 'Stop', despite the docs claiming that $ErrorActionPreference pertains only to nonterminating errors, the 3rd error type.

For more information, see this (unofficial) overview of PowerShell's error handling.
As for guidance when to use which type of error:

There is little guidance as to when to use Throw in the about_Throw help topic; an example use case is given in which Throw is used to abort a function/script in the absence of a mandatory parameter, as an alternative to PowerShell's default behavior of prompting for it.

Just be aware that Throw, i.e., throwing a script-terminating error terminates the entire runspace (the running script and any of its callers), unless caught.

The Cmdlet Error Reporting article only discusses cmdlet-internal use with respect to when to report statement-terminating (called just "terminating" in the article) vs. nonterminating errors.

A concise summary of the article can be found in this answer of mine.

Given the latter, you could argue that advanced functions - since they're like cmdlets - should at most report statement-terminating errors and that Throw (script-terminating errors) should be limited to scripts, but note that that contradicts the use of Throw to enforce mandatory parameters.
Perhaps the problematic distinction between script-terminating and statement-terminating errors is ultimately unintentional and perhaps the original intent was to only ever have script-terminating ones, which would explain why all the current documentation only ever talks about terminating errors in the abstract, without even mentioning the distinction.


Q:

How to instantiate generic class which has a private constructor with an argument

I'm creating a java application with 3rd-party library, and want to instantiate its class. However, the class is generic and only has a private constructor.
I've tried to create an instance by Guice injection.
Test<T> can't be modified, so I did neither annotate with @Inject nor add a zero-argument constructor that is not private.
public class Test<T> {
    private final T value;

    private Test(T value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return this.value.toString();
    }
}

Injector injector = Guice.createInjector(new AbstractModule() {
    @Override
    protected void configure() {
        bind(new TypeLiteral<Test<String>>() {
        });
    }
});
Test<String> test = (Test<String>) injector.getInstance(Test.class);
System.out.println(String.format("%s", test));

1) Could not find a suitable constructor in com.example.app.Test. Classes must have either one (and only one) constructor annotated with @Inject or a zero-argument constructor that is not private.

I want to know how can I put an argument to the constructor of Test class, and how to instantiate it.

A:

You can (but probably you should not) do this using reflections:
    Constructor<Test> declaredConstructor = Test.class.getDeclaredConstructor(Object.class);
    declaredConstructor.setAccessible(true); // or if (declaredConstructor.trySetAccessible()) on java 9+
    Test<String> obj = declaredConstructor.newInstance("value of first parameter");

Generics are ignored in runtime so you just need to use lower bound here Object.class. If it would be class Test<T extends Something> then you would look for Something.class but otherwise it is Object by default.
If that test class is from some library maybe there is method that creates it... so you could avoid using reflections.


Q:

Does $f(0)=0$ and $\left|f^\prime(x)\right|\leq\left|f(x)\right|$ imply $f(x)=0$?

Let $f:\mathbb{R}\to\mathbb{R}$ be a function such that $f(0)=0$ for all real numbers $x$, $\left|f^\prime(x)\right|\leq\left|f(x)\right|$. Can $f$ be a function other than the constant zero function?
I coudn't find any other function satisfying the property. The bound on $f^\prime(x)$ may mean that $f(x)$ may not change too much but does it mean that $f$ is constant?
I thought for a while and found that $f^\prime(0)=0$ and by using mean value theorem, if $x\neq0$ then there's a real number $y$ between $0$ and $x$ such that $\left|f(x)\right|=\left|xf^\prime(y)\right|\leq\left|xf(y)\right|$. Anything further?

A:

Let $F(x)=|f(x)|$. Then if $x>0$
$$
F(x)=\Bigl|\int_0^xf'(t)\,dt\Bigr|\le\int_0^x|f'(t)|\,dt\le\int_0^x|f(t)|\,dt=\int_0^xF(t)\,dt.
$$
From here we get
$$
\Bigl(e^{-x}\int_0^xF(t)\,dt\Bigr)'=e^{-x}\Bigl(F(x)-\int_0^xF(t)\,dt\Bigr)\le0.
$$
Thus, $e^{-x}\int_0^xF(t)\,dt$ is decreasing. Since its value at $x=0$ is $0$ and $e^{-x}>0$, we see that $\int_0^xF(t)\,dt\le0$ for all $x>0$. Since $F\ge0$, this implies that $F(x)=0$ for all $x>0$.
A similar reasoning applies if $x<0$.

A:

Suppose $x$ is some real number with $f(x)=0$, and let $y\in [x-1/2,x+1/2]$ be such that $|f(y)|$ is maximized. Then the mean value theorem implies there is some $z$ between $x$ and $y$ such that
$$
2\cdot |f(y)|\leq \frac{|f(y)|}{|y-x|}=\left|\frac{f(y)-f(x)}{y-x}\right|=|f'(z)|\leq |f(z)|\leq |f(y)|,
$$
which implies $f(y)=0$. We have shown that $f(x)$ implies $f$ is $0$ on $[x-1/2,x+1/2]$, so $f$ must be identically $0$.


Q:

What is the independence number of hamming graph?

Hamming graph H(d,q) is  Cartesian product of d complete graphs Kq. We know the independence number of direct product of d complete graphs Kq. What is the independence number of hamming graph?

A:

I take the Hamming graph $H(d,q)$ to be the Cartesian product of $d$ copies of the complete graph $K_q$. Its independence number is $q^{d-1}$.
Proof: The Hamming graph lies in the Hamming scheme, so the clique-coclique bound holds: If $C$ is a clique and $S$ a coclique, then $|C||S|\ne n$, where $n$ is the number of vertices of the scheme - here $q^d$. Clearly we have cliques of size $q$, so $|S|\le q^{n-1}$. To get a coclique of the right size, view the vertices of $K_q$ as integers mod $q$ and let $S$ be the set of $d$-tuples whose coordinates sum to zero. Then no two $d$-tuples in $S$ differ in exactly one position, and so $S$ is a coclique.
Of course the clique-coclique bound is overkill here. The $d$-tuples with first $d-1$ coordinates zero form a subgroup of order $q$ in $Z_q^d$. Hence the cosets of this subgroup form a partition of the vertices of the Hamming graph into cliques of size $q$, and therefore $|S| \le q^{d-1}$.


Q:

Unknown Directory Shortcut File or Mount | VISTA

I have this weird mount icon after a trojan cleanup days ago for a client. The icon when clicked takes you to the My Computer guid. The file properties are Type: File, Location: C:\, Size: 6.76. If we try to delete it will not complete. I search registry for a reference and couldn't find. They ran utility for virus removal 'combofix', sdfix, smithfraud, ect. Im gessing this could be related (mount).
The icon on the file structure in My Computer shows a device similar icon. When this icon is clicked it goes back to my computer browser.
i77.photobucket.com/albums/j65/speedcoder/snap.jpg
How can I take this guy off?

A:

When you need to clean a system infected with malicious code:
1) Archive the user data
2) Some some other system, or at least some kind of rescue CD, to scan the data for traces of malicious code.
3) Clean install the system, including MBR on the disk. For the paranoid, re-flash BIOS code on all components.
4) Restore the scanned/cleaned user data to the rebuilt system.
In my opinion, do not waste time trying to clean a compromised system in place - with today's  malicious code, e.g., root kits, this is impossible.


Q:

Density of the set of the fractional part of sufficiently large irrational numbers in the unit interval $[0,1]$

Is it true that $\forall x \notin \mathbb{Q}: x>1$, the set $A=\{ \operatorname{frac}(x^n): n \in \mathbb{N} \}$ is dense in $[0,1]$?

A:

One of the questions in the first competition I did was to prove that $\{(2+\sqrt{3})^n\}\to1$ as $n\to\infty$.


Q:

Locating resource in Jar

I am having difficulty creating the image icon.  I want to package a jar and have the images available to be displayed in the gui.  Both of the following throw null pointer exceptions.  The path is a path directly to a package in my Eclipse project that contains the necessary images.
ImageIcon icon = new ImageIcon(this.getClass().getClassLoader().getResource(
   "/TicTacToe/src/edu/luc/tictactoe/gui/resources/images/TicTacToeOIcon.png")
   .getPath());

and
ImageIcon icon = new ImageIcon(getClass().getResource(
   "/TicTacToe/src/edu/luc/tictactoe/gui/resources/images/TicTacToeOIcon.png"));

I can't see to be able to access the appropriate package.  Any suggestions?

A:

ImageIcon icon = new ImageIcon(this.getClass().getClassLoader()
    .getResourceAsStream("edu/luc/tictactoe/gui/resources/images/TicTacToeOIcon.png");


Q:

How to insert inactive [timestamp] via function?

C-u C-c !  generates a time stamp like [2015-05-04 Mon 17:13]
I would like to assign a shortcut (e.g F1) to this action.
So far I have:
(defun my/timenow (&optional arg)
 (interactive)
 (let ((current-prefix-arg 4)) ;; emulate C-u
 (org-time-stamp arg 'inactive)
 )
)

But this prompts me for the time and I have to press RET to insert it.
How can I insert the inactive timestamp without any prompts at all?

A:

From the documentation of org-time-stamp:

With two universal prefix arguments, insert an active timestamp
  with the current time without prompting the user.

So eval the below:
(org-time-stamp '(16) t)

'(4) - one prefix arg (4)
'(16) - two prefix args (4 * 4)
'(64) - three prefix args (4 * 4 * 4)

To read more about the universal arguments and arguments in general:

Prefix Command Args - Emacs Manual
Arguments - Elisp Manual
Elisp Universal Args - ergoemacs.org


Q:

lxml install on windows 7 using pip and python 2.7

When I try to upgrade lxml using pip on my windows 7 machine I get the log printed below.
When I uninstall and try to install from scratch I get the same errors.
Any ideas?

Downloading/unpacking lxml from
  https://pypi.python.org/packages/source/l/lxml/l
  xml-3.2.4.tar.gz#md5=cc363499060f615aca1ec8dcc04df331   Downloading
  lxml-3.2.4.tar.gz (3.3MB): 3.3MB downloaded   Running setup.py
  egg_info for package lxml
      Building lxml version 3.2.4.
      Building without Cython.
      ERROR: Nazwa 'xslt-config' nie jest rozpoznawana jako polecenie wewnętrzne l ub zewnętrzne,
      program wykonywalny lub plik wsadowy.
** make sure the development packages of libxml2 and libxslt are installed *

*
Using build configuration of libxslt
D:\software\Python27\lib\distutils\dist.py:267: UserWarning: Unknown distrib ution option: 'bugtrack_url'
  warnings.warn(msg)

warning: no files found matching 'lxml.etree.c' under directory 'src\lxml'
warning: no files found matching 'lxml.objectify.c' under directory 'src\lxm l'
warning: no files found matching 'lxml.etree.h' under directory 'src\lxml'
warning: no files found matching 'lxml.etree_api.h' under directory 'src\lxm l'
warning: no files found matching 'etree_defs.h' under directory 'src\lxml'
warning: no files found matching '*.txt' under directory 'src\lxml\tests'
warning: no files found matching 'pubkey.asc' under directory 'doc'
warning: no files found matching 'tagpython*.png' under directory 'doc'
warning: no files found matching 'Makefile' under directory 'doc' Installing collected packages: lxml   Found existing installation:

lxml 2.3
      Uninstalling lxml:
        Successfully uninstalled lxml   Running setup.py install for lxml
      Building lxml version 3.2.4.
      Building without Cython.
      ERROR: Nazwa 'xslt-config' nie jest rozpoznawana jako polecenie wewnętrzne l ub zewnętrzne,
      program wykonywalny lub plik wsadowy.
** make sure the development packages of libxml2 and libxslt are installed *

*
Using build configuration of libxslt
building 'lxml.etree' extension
D:\software\Microsoft Visual Studio 9.0\VC\BIN\cl.exe /c /nologo /Ox /MD /W3  /GS- /DNDEBUG

-Ic:\users\x\appdata\local\temp\pip_build_x\lxml\src\lxml\inc ludes -ID:\software\Python27\include -ID:\software\Python27\PC
  /Tcsrc\lxml\lxml. etree.c
  /Fobuild\temp.win32-2.7\Release\src\lxml\lxml.etree.obj
      lxml.etree.c
      c:\users\x\appdata\local\temp\pip_build_x\lxml\src\lxml\includes\etree_d
  efs.h(9) : fatal error C1083: Cannot open include file:
  'libxml/xmlversion.h': N o such file or directory
      D:\software\Python27\lib\distutils\dist.py:267: UserWarning: Unknown distrib ution option: 'bugtrack_url'
        warnings.warn(msg)
      error: command '"D:\software\Microsoft Visual Studio 9.0\VC\BIN\cl.exe"' fai led with exit status 2
      Complete output from command D:\software\Python27\python.exe -c "import setu
  ptools;file='c:\users\x\appdata\local\temp\pip_build_x\lxml\setu
  p.py';exec(compile(open(file).read().replace('\r\n', '\n'),
  file, 'exec' ))" install --record c:\users\x\appdata\local\temp\pip-pyyuss-record\install-r ecord.txt
  --single-version-externally-managed:
      Building lxml version 3.2.4.
Building without Cython.
ERROR: Nazwa 'xslt-config' nie jest rozpoznawana jako polecenie
  wewnętrzne lub z ewnętrzne,
program wykonywalny lub plik wsadowy.
** make sure the development packages of libxml2 and libxslt are installed **
Using build configuration of libxslt
running install
running build
running build_py
creating build
creating build\lib.win32-2.7
creating build\lib.win32-2.7\lxml
copying src\lxml\builder.py -> build\lib.win32-2.7\lxml
copying src\lxml\cssselect.py -> build\lib.win32-2.7\lxml
copying src\lxml\doctestcompare.py -> build\lib.win32-2.7\lxml
copying src\lxml\ElementInclude.py -> build\lib.win32-2.7\lxml
copying src\lxml\pyclasslookup.py -> build\lib.win32-2.7\lxml
copying src\lxml\sax.py -> build\lib.win32-2.7\lxml
copying src\lxml\usedoctest.py -> build\lib.win32-2.7\lxml
copying src\lxml_elementpath.py -> build\lib.win32-2.7\lxml
copying src\lxml__init__.py -> build\lib.win32-2.7\lxml
creating build\lib.win32-2.7\lxml\includes
copying src\lxml\includes__init__.py ->
  build\lib.win32-2.7\lxml\includes
creating build\lib.win32-2.7\lxml\html
copying src\lxml\html\builder.py -> build\lib.win32-2.7\lxml\html
copying src\lxml\html\clean.py -> build\lib.win32-2.7\lxml\html
copying src\lxml\html\defs.py -> build\lib.win32-2.7\lxml\html
copying src\lxml\html\diff.py -> build\lib.win32-2.7\lxml\html
copying src\lxml\html\ElementSoup.py -> build\lib.win32-2.7\lxml\html
copying src\lxml\html\formfill.py -> build\lib.win32-2.7\lxml\html
copying src\lxml\html\html5parser.py -> build\lib.win32-2.7\lxml\html
copying src\lxml\html\soupparser.py -> build\lib.win32-2.7\lxml\html
copying src\lxml\html\usedoctest.py -> build\lib.win32-2.7\lxml\html
copying src\lxml\html_diffcommand.py -> build\lib.win32-2.7\lxml\html
copying src\lxml\html_html5builder.py ->
  build\lib.win32-2.7\lxml\html
copying src\lxml\html_setmixin.py -> build\lib.win32-2.7\lxml\html
copying src\lxml\html__init__.py -> build\lib.win32-2.7\lxml\html
creating build\lib.win32-2.7\lxml\isoschematron
copying src\lxml\isoschematron__init__.py ->
  build\lib.win32-2.7\lxml\isoschema tron
copying src\lxml\lxml.etree.h -> build\lib.win32-2.7\lxml
copying src\lxml\lxml.etree_api.h -> build\lib.win32-2.7\lxml
copying src\lxml\includes\c14n.pxd ->
  build\lib.win32-2.7\lxml\includes
copying src\lxml\includes\config.pxd ->
  build\lib.win32-2.7\lxml\includes
copying src\lxml\includes\dtdvalid.pxd ->
  build\lib.win32-2.7\lxml\includes
copying src\lxml\includes\etreepublic.pxd ->
  build\lib.win32-2.7\lxml\includes
copying src\lxml\includes\htmlparser.pxd ->
  build\lib.win32-2.7\lxml\includes
copying src\lxml\includes\relaxng.pxd ->
  build\lib.win32-2.7\lxml\includes
copying src\lxml\includes\schematron.pxd ->
  build\lib.win32-2.7\lxml\includes
copying src\lxml\includes\tree.pxd ->
  build\lib.win32-2.7\lxml\includes
copying src\lxml\includes\uri.pxd -> build\lib.win32-2.7\lxml\includes
copying src\lxml\includes\xinclude.pxd ->
  build\lib.win32-2.7\lxml\includes
copying src\lxml\includes\xmlerror.pxd ->
  build\lib.win32-2.7\lxml\includes
copying src\lxml\includes\xmlparser.pxd ->
  build\lib.win32-2.7\lxml\includes
copying src\lxml\includes\xmlschema.pxd ->
  build\lib.win32-2.7\lxml\includes
copying src\lxml\includes\xpath.pxd ->
  build\lib.win32-2.7\lxml\includes
copying src\lxml\includes\xslt.pxd ->
  build\lib.win32-2.7\lxml\includes
copying src\lxml\includes\etree_defs.h ->
  build\lib.win32-2.7\lxml\includes
copying src\lxml\includes\lxml-version.h ->
  build\lib.win32-2.7\lxml\includes
creating build\lib.win32-2.7\lxml\isoschematron\resources
creating build\lib.win32-2.7\lxml\isoschematron\resources\rng
copying src\lxml\isoschematron\resources\rng\iso-schematron.rng ->
  build\lib.win 32-2.7\lxml\isoschematron\resources\rng
creating build\lib.win32-2.7\lxml\isoschematron\resources\xsl
copying src\lxml\isoschematron\resources\xsl\RNG2Schtrn.xsl ->
  build\lib.win32-2 .7\lxml\isoschematron\resources\xsl
copying src\lxml\isoschematron\resources\xsl\XSD2Schtrn.xsl ->
  build\lib.win32-2 .7\lxml\isoschematron\resources\xsl
creating
  build\lib.win32-2.7\lxml\isoschematron\resources\xsl\iso-schematron-xsl
  t1
copying
  src\lxml\isoschematron\resources\xsl\iso-schematron-xslt1\iso_abstract_e
  xpand.xsl ->
  build\lib.win32-2.7\lxml\isoschematron\resources\xsl\iso-schematron
  -xslt1
copying
  src\lxml\isoschematron\resources\xsl\iso-schematron-xslt1\iso_dsdl_inclu
  de.xsl ->
  build\lib.win32-2.7\lxml\isoschematron\resources\xsl\iso-schematron-xs
  lt1
copying
  src\lxml\isoschematron\resources\xsl\iso-schematron-xslt1\iso_schematron
  _message.xsl -> build\lib.win32-2.7\lxml\isoschematron\resources\xsl\iso-schemat
  ron-xslt1
copying
  src\lxml\isoschematron\resources\xsl\iso-schematron-xslt1\iso_schematron
  _skeleton_for_xslt1.xsl -> build\lib.win32-2.7\lxml\isoschematron\resources\xsl\
  iso-schematron-xslt1
copying
  src\lxml\isoschematron\resources\xsl\iso-schematron-xslt1\iso_svrl_for_x
  slt1.xsl ->
  build\lib.win32-2.7\lxml\isoschematron\resources\xsl\iso-schematron-
  xslt1
copying
  src\lxml\isoschematron\resources\xsl\iso-schematron-xslt1\readme.txt
  -> build\lib.win32-2.7\lxml\isoschematron\resources\xsl\iso-schematron-xslt1
running build_ext
building 'lxml.etree' extension
creating build\temp.win32-2.7
creating build\temp.win32-2.7\Release
creating build\temp.win32-2.7\Release\src
creating build\temp.win32-2.7\Release\src\lxml
D:\software\Microsoft Visual Studio 9.0\VC\BIN\cl.exe /c /nologo /Ox
  /MD /W3 /GS
  - /DNDEBUG -Ic:\users\x\appdata\local\temp\pip_build_x\lxml\src\lxml\include s -ID:\software\Python27\include -ID:\software\Python27\PC
  /Tcsrc\lxml\lxml.etre e.c
  /Fobuild\temp.win32-2.7\Release\src\lxml\lxml.etree.obj
lxml.etree.c
c:\users\x\appdata\local\temp\pip_build_x\lxml\src\lxml\includes\etree_defs.
  h(9) : fatal error C1083: Cannot open include file:
  'libxml/xmlversion.h': No su ch file or directory
D:\software\Python27\lib\distutils\dist.py:267: UserWarning: Unknown
  distributio n option: 'bugtrack_url'
warnings.warn(msg)
error: command '"D:\software\Microsoft Visual Studio
  9.0\VC\BIN\cl.exe"' failed with exit status 2
----------------------------------------   Rolling back uninstall of lxml Cleaning up... Command D:\software\Python27\python.exe -c "import
  setuptools;file='c:\user
  s\x\appdata\local\temp\pip_build_x\lxml\setup.py';exec(compile(open(_
  file_).read().replace('\r\n', '\n'), file, 'exec'))" install --record c:\u sers\x\appdata\local\temp\pip-pyyuss-record\install-record.txt
  --single-versio n-externally-managed failed with error code 1 in c:\users\x\appdata\local\temp \pip_build_x\lxml Traceback (most
  recent call last):   File
  "D:\software\Python27\Scripts\pip-script.py", line 9, in
      load_entry_point('pip==1.4.1', 'console_scripts', 'pip')()   File "D:\software\Python27\lib\site-packages\pip__init__.py", line 148, in
  ma in
      return command.main(args[1:], options)   File "D:\software\Python27\lib\site-packages\pip\basecommand.py", line 169,
  in  main
      text = '\n'.join(complete_log) UnicodeDecodeError: 'ascii' codec can't decode byte 0xa9 in position 72: ordinal  not in range(128)

A:

If you have a compiler installed (tested with VS C++ 2008 Express), you can simply run:
set STATICBUILD=true && pip install lxml

As pointed out on documentation, setting STATICBUILD will tell to lxml's installer to automatically download all its binary dependencies before build.
These lxml binary dependencies, that should be present when installing from source, will be downloaded and build together by the installer:

libxslt
iconv
zlib
libxml2

Bonus: It also works inside a virtualenv.

A:

This question is older but still pops up in google.  I tried the other answers to this question and they did not work for one reason or another and I did't want to track down and install all the dependencies to compile on Windows.
I noticed on pypi some of the lxml releases offer windows wheels and others do not.
So the simplest solution for me was to specify a version that did... i.e. pip install lxml==3.6.0 since 3.6.0 offered a wheel while the newer 3.6.4 did not

A:

For your problem, there is a single line solution. Somehow, this is working  means suppose you are doing scraping at low level then this will work.
After 8 hours of research, I found this as working nothing else
pip install lxml==3.6.0

Nothing else is required.
All things above are applicable for Windows.
Comment if some other type of problem is persisting happy to help.
Here is my success after 8 hours:


Q:

Decrease space between paragraph and header

How can I decrease the white space marked with blue? I tried \vspace with negative marks but to no avail (it normally does the trick but not this time). I am using the 'fancyhdr'-package.
\documentclass[12pt, a4paper]{article}
\usepackage[a4paper]{geometry}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{lmodern, amsmath, amssymb, fancyhdr, eulervm}

\setlength{\parindent}{0in}
\setlength{\headheight}{15pt}
\pagestyle{fancy}
\lhead{Left header, text}
\rhead{Right header, text}

\begin{document}
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
\[
\int \!\! \int f(x,y) \, \text{d}x\text{d}y \quad \text{och} \quad \sum_{n=0}^{\infty}         \Big( n^2 + n + n! \Big)
\]
\end{document}

A:

That distance is given by the headsep key when you use geometry. For example, adding headsep=1sp (just a very small amount) you'll see

\usepackage[...,headsep=1sp,...]{geometry}% http://ctan.org/pkg/geometry

A:

You can simply change the length of \headsep using the \setlength command, for example: \setlength{\headsep}{10pt}.
If I add at the end of your code:
\clearpage
\setlength{\headsep}{1pt}
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

I get the following result:


Q:

selectInput in R fetching data from MySql

I have just started using MySql since couple of days.  Pardon me if this is a very basic query.
I have a table in MySql having four columns: content, media_provider, date and sentimet.  Sentimet has three levels in it viz., pos, neg & neu.
Using a shiny selectInput, I am trying to fetch all the records that are tagged as pos, neg or neu.  The following is the code:
ui <- shinyUI(fluidPage(
    titlePanel("Generic grapher"),
    sidebarLayout(
        sidebarPanel(

            selectInput(inputId = "wafer", label = "Select sentiment", choices = c("pos", "neg", "neu"),
                        multiple = FALSE, selectize = TRUE, width = "40%"),

            actionButton("do", "An action button")
        ),

        mainPanel(
            verbatimTextOutput("value"),
            verbatimTextOutput("que"),
            verbatimTextOutput("wq_print"),
            dataTableOutput(outputId="post")
        )
    )
)
)

server <- shinyServer(function(input, output){

    values <- reactiveValues()
    values$df <- data.frame()

    d <- eventReactive(input$do, { input$wafer })

    output$value <- renderPrint({ d() })

    a <- reactive({ paste("SELECT * FROM apparel WHERE sentimet = ", d(), sep="") })

    output$que <- renderPrint({ a() })

    observe({
        if (!is.null(d())) {
            wq <- reactive({  query( a() ) })

            output$wq_print <- renderPrint({ print(str(wq())) })

            values$df <- rbind(isolate(values$df), wq())
        }
    })

    output$post <- renderDataTable({ values$df })

})

shinyApp(ui, server)

When I run, I got the following error:
Warning: Error in .local: could not run statement: Unknown column 'neg' in 'where clause'

I understand MySql considers the 'factor' neg as column 'neg', so I changed my choices option in selectInput from "pos" to 'pos' = 1, MySql looks for value 1, and returns NULL.  I changed 1 = "pos", "pos" = "pos", nothing worked.  However when I directly provide the query in MySql "SELECT * FROM apparel WHERE sentimet = "pos";"  works flawlessly.  Not sure how to use the selectInput.  Providing a 3 line reproducible example below:
structure(list(CONTENT = c("@myntra Good Morning If you are born poor its not your mistake, But if you die poor its your mistake. -Bill Gates Good Day",
"@myntra i have been mailing my issue daily since past week.All i get in reply is an auto generated assurance mail. 1st time pissed wd myntra",
"@myntra I'm a big Arsenal fan & made a big PUMA collection! ¥Ë_ Shared that collection yesterday. Wanna win... ¥Ë_¥Ë_¥Ë_ #myPUMAcollection"
), MEDIA_PROVIDER = c("TWITTER", "TWITTER", "TWITTER"), PUBLISH_DATE = structure(list(
    sec = c(0, 0, 0), min = c(30L, 22L, 11L), hour = c(7L, 7L,
    7L), mday = c(21L, 21L, 21L), mon = c(10L, 10L, 10L), year = c(115L,
    115L, 115L), wday = c(6L, 6L, 6L), yday = c(324L, 324L, 324L
    ), isdst = c(0L, 0L, 0L), zone = c("IST", "IST", "IST"),
    gmtoff = c(NA_integer_, NA_integer_, NA_integer_)), .Names = c("sec",
"min", "hour", "mday", "mon", "year", "wday", "yday", "isdst",
"zone", "gmtoff"), class = c("POSIXlt", "POSIXt"), tzone = "Asia/Calcutta"),
    sentimet = c("neg", "pos", "neu")), .Names = c("CONTENT",
"MEDIA_PROVIDER", "PUBLISH_DATE", "sentimet"), class = "data.frame", row.names = c(NA,
3L))

A:

The values in your sentimet column are characters so you need to wrap them with single quotes :
a <- reactive({ paste0("SELECT * FROM apparel WHERE sentimet = '", d(), "'") })


Q:

Reading strings in VBScript

I want to modify my function that strips the  tag from the value of a database record in the title of French pages:
Function removeSup(strToRemove)
    strToRemove = Replace(strToRemove,"","(")
    strToRemove = Replace(strToRemove,"",")")
    response.Write(strToRemove)
End Function

so that it can read the contents of the tag. If the contents is a ® or a ™, then do nothing, but if it's MD or MC, then do the replace.
I just haven't figured out how to read strings with VBScript so is this something that I should do with VBScript or have it passed to jQuery to do it?

A:

You could work with Regular Expressions but if i understand what you mean the you can do it as below.
Jquery is javascript only, if this is for web, best not to mix vbscript and javascript unless realy necessary.
Function removeSup(strToRemove)
    strToRemove = Replace(strToRemove,"MD","(MD)")
    strToRemove = Replace(strToRemove,"MC","(MD)")
    response.Write(strToRemove)
End Function


Q:

Navigation bar border

JavaScript
nav{

    width: 100%;
    height: 60px;
    background: linear-gradient(to bottom, #fff, #bbb);
    border-bottom: 1px solid #fff;

    }
    .wrapper{
    max-width:1200px;
    margin:0 auto;

    }

       li{
        float:left;
        width: 15%;
        list-style: none;
        margin-top: 5px;

    }
    a{
        text-decoration: none;
        box-sizing: border-box;
        display: block;
        padding: 10px 10px;
        text-align: center;
        color: #052537;

    }
.nav01,
.nav03,
.nav05{
     border-right: 1px solid #999999;
     border-left: 1px solid #fff;
}
.nav02,
.nav04{
     border-left: 1px solid #fff;
     border-right: 1px solid #999999;
}

go1

go2

go3

go4

go5

Nav bar
Hello, everyone,  I have the problem to design the nav bar very first and the last border. I want to make borders like in the shared picture. I can't figure it out how to design nav01 first border and nav 05 last border because I want a combination of two borders as I did in nav02,nav03 and nav04. Please help me

A:

One way is to use border and use different properties of border to get your desired result. You can experiment and be as creative as you can. Just for once, go through all the possibilities and what CSS is capable of. Then you can easily figure out which properties to combine to make your own prototype into code.

nav {
  width: 100%;
  background: #e4e4e4;
  font-family: 'arial';
}

.navbar-ul a {
  text-decoration: none;
  list-style-type: none;
  display: block;
  float: left;
  font-size: 20px;
  width: 120px;
  border: 1px solid #000;
  text-align: center;
  margin: 10px 0px;
  border-left: none;
  border-top: none;
  border-bottom: none;
  color: #1f1f1f;
}

ul a:last-child {
  border-right: none;
}

li {
  margin: 5px;

}

a:hover {
  text-decoration: none !important;
}

li:hover {
  margin: 5px;
  background: #1f1f1f;
  color: white;
  text-decoration: none !important;
  transition: all .2s;
  border-radius: 4px;

}

.navbar-ul a:hover {
  cursor: pointer;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

Home

Profile

Contact

Blogs


Q:

How to perform SVD of a matrix with symbols?

Let's assume that we have the following matrix:
\begin{pmatrix} 0& 2& 3& 4a& 5a\\
6& 7& 1& 8a& 9a\end{pmatrix}
Can we perform SVD on this matrix and get the output in function of $a$?

A:

Seeing that the Wolfram Alpha solution which @Omnomnomnom posts is unreasonably complicated for any practical purpose, it is justified to search for a simpler and computationally cheaper approximative solution.
Here is one way to approximate the elements in $\bf U$ and $\bf V$ matrices in the SVD.
Considering the matrix ${\bf M = M_1} + a {\bf M_2}$, where:
$${\bf M}(a) = {\bf U}(a){\bf \Sigma}(a) {\bf V}(a)^T$$
$${\bf M_1} = \begin{bmatrix}0&2&3&0&0\\6&7&1&0&0\end{bmatrix}, {\bf M_2} = \begin{bmatrix}0&0&0&4&5\\0&0&0&8&9\end{bmatrix}$$
We first set up the following set of functions (which we have found by experimentation)
$$f_N(a) =\exp\left[\frac{-a N^2}{1.5\cdot N_{max}}\right]$$
Exponential functions are cheap to calculate, they often have very optimized software functions or even hardware instructions in computers. The experiments below are $N_{max} = 8$, so max 8 exponential function evaluations needed for any given $a$.
Then we simply calculate SVD for a range of values, for example linearly spaced $ a \in [0,16]$ and we do linear regression on each element as a function of $a$:
$$\min_{\{c_{klm}\}}\left\| {\bf U}_{lm}(a) - \sum_{k=0}^{N_{max}} c_{klm} f_k(a)\right\|_2^2$$


Q:

Applying img hover to a certain picture only?

I would like to add the img hover specifically to the top banner and no other image. Is there any code that lets you do this? Thank you for any reply.

<TITLE>Cascade Studios™</TITLE>

A:

Give it unique ID and define CSS rule for that ID:

<TITLE>Cascade Studios™</TITLE>


Q:

Trouble parsing data JSON alamofire SwiftJSON

Trying to parse a sample JSON object using alamofire and SwiftlyJSON from http been having trouble to parse it to my product model. It's really strange, I ran the debugger within the for loops, I iterate over and do a "po self.productlist", the value was indeed appended into the array. But when I try to print it outside the loop, then it wasn't working, same thing when I try to do "po self.productlist[0]["product"]" in debugger mode. It's really strange at one point it was working. As you can see I've attached 2 image below in the imgur links.
I've also attach my controller and model, I'm not sure what mistake I done, or maybe there is a bug. Any help would be appreciated. Thanks
Controller
import UIKit
import Alamofire
import SwiftyJSON

class AddProductController: UITableViewController {
    var productlist = [Product]()

    override func viewDidLoad() {
        super.viewDidLoad()

        Alamofire.request("https://api.myjson.com/bins/1f1zop").responseJSON { response in
            let jsondata = JSON(data: response.data!)
            for index in 0..<jsondata["data"].count{

                self.productlist.append(Product(id: jsondata["data"][index]["id"].stringValue, product: jsondata["data"][index]["product"].stringValue, category: jsondata["data"][index]["category"].stringValue, price: jsondata["data"][index]["price"].doubleValue))
            }
        }
        print(self.productlist[0]["id"])

Model
import Foundation

class Product {
    var id:String
    var product:String
    var category: String
    var price: Double

    init(id:String, product:String, category:String, price:Double) {
        self.id = id
        self.product = product
        self.category = category
        self.price = price
    }
}

]2
Update to vadian
Thanks i got it!

A:

No bug, that's the famous async-trap.
Alamofire request works asynchronously, the JSON is returned after the print line.
Just put the print line – and also the code to process the array – into the completion block.
The error occurs, because you try to get id like a dictionary. Use the property .id
By the way: Please don't use index based loops in Swift
    Alamofire.request("https://api.myjson.com/bins/1f1zop").responseJSON { response in
        let jsondata = JSON(data: response.data!)
        for product in jsondata["data"].array! {
            self.productlist.append(Product(id: product["id"].stringValue, product: product["product"].stringValue, category: product["category"].stringValue, price: product["price"].doubleValue))
        }
        print(self.productlist[0].id) // use the property, it's not a dictionary.
    }

Note: If the JSON is loaded from a third party service you should use optional bindings to parse the data safely.


Q:

How to get the child of child using Python's ElementTree

I'm building a Python file that communicates with a PLC. When compiling, the PLC creates a XML file that delivers important information about the program. The XML looks more less like this:
<visu>
    <time>12:34</time>
    <name>my_visu</name>
    <language>english</language>
    <vars>
        <var name="input1">2</var>
        <var name="input2">45.6</var>
        <var name="input3">"hello"</var>
    </vars>
</visu>

The important part is found under child "vars". Using Python I want to make a file that when sending argument "input2" it will print "45.6".
So far I can read all children of "visu", but don't know how to actually tell Python to search among "the child of child". Here's is what I got so far:
tree = ET.parse("file.xml")
root = tree.getroot()
for child in root:
    if child.tag == "vars":
        .......
        if ( "childchild".attrib.get("name") == "input2" ):
            print "childchild".text

Any ideas how I can complete the script? (or maybe a more efficient way of programming it?)

A:

You'd be better of using an XPath search here:
name = 'input2'
value = root.find('.//vars/var[@name="{}"]'.format(name)).text

This searches for a <var> tag directly below a <vars> tag, whose attribute name is equal to the value given by the Python name variable, then retrieves the text value of that tag.
Demo:
>>> from xml.etree import ElementTree as ET
>>> sample = '''\
... <visu>
...     <time>12:34</time>
...     <name>my_visu</name>
...     <language>english</language>
...     <vars>
...         <var name="input1">2</var>
...         <var name="input2">45.6</var>
...         <var name="input3">"hello"</var>
...     </vars>
... </visu>
... '''
>>> root = ET.fromstring(sample)
>>> name = 'input2'
>>> root.find('.//vars/var[@name="{}"]'.format(name)).text
'45.6'

You can do this the hard way and manually loop over all the elements; each element can be looped over directly:
name = 'input2'
for elem in root:
    if elem.tag == 'vars':
        for var in elem:
           if var.attrib.get('name') == name:
               print var.text

but using element.find() or element.find_all() is probably going to be easier and more concise.


Q:

Appending a string to each item of an array

I have an array and when I try to append a string to it the array converts to a single string.
I have the following data in an array:
$Str
451 CAR,-3 ,7 ,10 ,0 ,3 , 20 ,Over: 41
452 DEN «,40.5,0,7,0,14, 21 ,  Cover: 4

And I want to append the week of the game in this instance like this:
$Str = "Week"+$Week+$Str

I get a single string:
Week16101,NYG,42.5 ,3 ,10 ,3 ,3 , 19 ,Over 43 102,PHI,-  1,14,7,0,3, 24 ,  Cover 4 103,

Of course I'd like the append to occur on each row.

A:

Instead of a for loop you could also use the Foreach-Object cmdlet (if you prefer using the pipeline):
$str = "apple","lemon","toast"
$str = $str | ForEach-Object {"Week$_"}

Output:
Weekapple
Weeklemon
Weektoast


Q:

Is the instance of the class equal to the instance of the interface?

The program has the next code:
public class RxTaskHandler<T> implements OnSuccessListener<T>{

   public RxTaskHandler(MaybeEmitter<T> emitter){
        this.emitter = emitter;
    }

     public static void assignTask(MaybeEmitter<T> emitter){
          RxTaskHandler rxTaskHandler = new RxTaskHandler(emitter);
          task.addOnSuccessListenerr(rxTaskHandler);
    }

   @Override
    public void onSuccess(Object o) {
        emitter.onNext();
    }

}

The question about this line - task.addOnSuccessListenerr(rxTaskHandler). We must add OnSuccessListener interface, but instead of this we add the instance of the class which implements OnSuccessListener. It means we can replace instance of the class (implements necessary interface) by instance of the interface?

A:

Yes,
It follows the rule of inheretance.
Here interface acts as parent class and class which implements interface acts as child class.


Q:

AS3 applying a Format via function

I am trying to write a function that applies TextFormats to the TextFields they belong to.
The problem is, that i don't manage it to get it into the right "Form"(if there is even a right form for this).
My function looks like this at the moment
function applyFormat(TextFild:String,Format:String,EmbFont:String,NameInJson:String){

//
//example:applyFormat("myTextField","myTextFormat","myFont","TextStuff")
//
//myData=json object
//all textfields etc. already exist. Just anyone wants to ask if they've been already generated.

//at first i thought it could be as easy as this
this[Format].font=myData.NameInJson.Font //doesn't work obviously

//then I tried this method
this[Format].font=myData.this[NameInJson].Font //doesn't work either

//couldn't find a real solution for this on the internet...
//how it should turn out in the end: myTextFormat.font=myData.TextStuff.Font
}

The related part of myData looks like this:
"TextStuff":
{
"Font":"Arial",
"Size" : "16",
"Bold" : "true",
"Color" : "0xFFFFFF"
}

do I need to change my Json file to make this possible?
am I overlooking a method to handle with this kind of variables/values?

A:

this[Format] will look for a property on the class with the name Format. AFAIK the class has to be dynamic for this to work.
If you keep your TextFormat instances in an object in that class it will be easier to manage:
// this is a property in the class
private var _textFormats:Object = {};

// create and store text formats in the object
var textFormat:TextFormat = new TextFormat();
_textFormats["myTextFormat"] = textFormat;

Now assuming you get a JSON text string like this :
{
"TextStuff":{
    "Font":"Arial",
    "Size" : "16",
    "Bold" : "true",
    "Color" : "0xFFFFFF"
  }
}

The following should work with this call applyFormat("myTextField","myTextFormat","myFont","TextStuff")
function applyFormat(TextField:String, Format:String, EmbFont:String, NameInJson:String):void
{
    var myData:Object = JSON.parse(theJSonString);
    _textFormats[Format].font = myData[NameInJson].Font;
}


Q:

Find x when the function equals 0

I must solve for x for this function.
$e^x-20x=0$
I'm not sure what to do here. I've tried this so far but it makes no sense:
$$\begin{align*}
e^x&=20x\\
x\ln e&=\ln20+\ln x\\
\frac{x}{\ln20}&=\ln x
\end{align*}$$
I tried this as well but I'm not sure if this is right either:
$$\begin{align*}
e^x&=20x\\
\ln e^x&=\ln20x\\
x&=\ln20+\ln x
\end{align*}$$
I've got more confidence in the second try, although I don't know how to solve for an actual number.
The answer is a decimal.

A:

This equation cannot be solved in terms of elementary functions. You can either use numeric methods like Newton's, or solve in terms of Lambert W function:
\begin{align*}
e^x - 20x &= 0 \\
20x &= e^x \\
xe^{-x} &= \frac{1}{20} \\
-x e^{-x} &= -\frac{1}{20} \\
-x &= W\left(-\frac{1}{20}\right) \\
x &= -W\left(-\frac{1}{20}\right)
\end{align*}


Q:

Invalid combination of type specifiers?

This works in xcode, but not visual studio.  The error is
error C2236: unexpected 'enum' 'abc::def::`anonymous-namespace'::'. Did you forget a ';'?
I can't figure out what is wrong.
namespace abc {
namespace def {

namespace {

long long enum {
  aaa = 1L,
  bbb = 2L,
};

}
}
}

A:

That syntax is bizarre, I don't see how it would work anywhere (EDIT: apparently it's a GCC extension -- thanks @PlasmaHH). This is the portable C++11 syntax you want:
enum : long long {
    aaa = 1LL,
    bbb = 2LL
};


Q:

Resizing a DockPanel to DockZone height and width

I am trying to resize a dynamic dock panel to the size of the dock zone in which it's contained in javascript(client-side) at runtime. I am using the Dev Express DockZone and DockPanel. My JScript looks like this:
function setDockPanelFill() {
    var dockPanel = ASPxClientControl.GetControlCollection().GetByName('dockPanel1');
    var dockZone = document.getElementById('zone1');
    dockPanel.SetHeight = dockZone.offsetHeight;
    dockPanel.SetWidth = dockZone.offsetWidth;
}

Any ideas on why this won't work?

A:

Set ASPxDockZone.ClientInstanceName to e.g. dockZone1.
Set ASPxDockPanel.PanelUID to e.g. dockPanel1.
Also, SetHeight and SetWidth are methods, not properties.
So your code should look like this:
function setDockPanelFill() {
    var dockPanel = dockZone1.GetPanelByUID('dockPanel1');
    dockPanel.SetHeight(dockZone1.GetHeight());
    dockPanel.SetWidth(dockZone1.GetWidth());
}


Q:

java Files.readAllBytes(image.png) doesn't work

I was trying to read from file and then write to other file. I use code bellow to do so.
byte[] bytes = Files.readAllBytes(file1);

Writer Writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file2), "UTF-8"));
for(int i=0;i<bytes.length;i++)
     Writer.write(bytes[i]);
Writer.close();

But when I change file1 to picture.png and file2 to picture2.png, this method doesn't work and I can't open picture2.png using image viewer.
What have I done wrong?

A:

Writers are for writing text, possibly in different formats (ie utf-8 / 16, etc). For writing raw bytes, don't use writers. Just use (File)OutputStreams.
It is truly as simple as
byte[] bytes = ...;
FileOutputStream fos = ...;
fos.write(bytes);

A:

The other answers explain why what you have potentially fails.
I'm curious why you're already using one Java NIO method, but not others? The library already has methods to do this for you.
byte[] bytes = Files.readAllBytes(file1);
Files.write(file2, bytes, StandardOpenOption.CREATE_NEW); // or relevant OpenOptions

or
FileOutputStream out = new FileOutputStream(file2); // or buffered
Files.copy(file1, out);
out.close();

or
Files.copy(file1, file2, options);


Q:

ModuleNotFoundError: No module named 'spatial'

I've been faced to Module Not Found Error in a script which all it's requirements has been installed. I'm trying to import spatial library:
import spatial

This library is located here:
C:\Users\ASUS\AppData\Local\Programs\Python\Python37\Lib\site-packages\scipy\spatial
I checked installed packages through pip list and it was okay. I tried to install spatial-lib in Pycharm project environment but it couldn't be done:

Could not find a version that satisfies the requirement spatial-lib (from versions: )
  No matching distribution found for spatial-lib
  You are using pip version 10.0.1, however version 18.1 is available.
  You should consider upgrading via the 'python -m pip install --upgrade pip' command.

It's nonesence, because my pip is up-to-date. Maybe good to say, importing scipy has such probelms too.

A:

It looks like spatial is a sub-package of scipy. Therefore, to import spatial, you should use the following:
from scipy import spatial


Q:

Error occurred :Http failure during parsing for [URL] while calling http Post from angular 7

I am trying to post data from a form into my rest backend server, the data is getting posted, but httpclient.post returns an error response ' Error occurred :Http failure during parsing for [URL]'.
I have tried the fixes suggested by the similar questions, but did not find any suitable one for angular 7
import { Injectable } from '@angular/core';
import * as UrlConstants from './urls';
import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { Book } from './book/book';
import { catchError } from 'rxjs/operators';

const httpOptions = {
  headers: new HttpHeaders().set('Content-Type','application/json')
};
//import { RequestOptions, Request, RequestMethod } from '@angular/http';
@Injectable({
  providedIn: 'root'
})
export class BookService {
  private _getBooksUrl: string = UrlConstants.BOOKS_URL;
  private _postBooksUrl: string = UrlConstants.POST_BOOK_URL;
  constructor(private _http: HttpClient) { }

  getAllBooks(): Observable<Book[]> {
    console.log(this._getBooksUrl);
    return this._http.get<Book[]>(this._getBooksUrl)
      .pipe(catchError(this.errorHandler));
  }

  addBook(book: Book) {
    let body = JSON.stringify(book);
    return this._http.post<Book>(this._postBooksUrl, body, httpOptions)
    .pipe(catchError(this.errorHandlerPost));
  }
  errorHandler(errorHandler: HttpErrorResponse): Observable<Book[]> {
    return throwError(errorHandler.message || "server error");
  }
  errorHandlerPost(errorHandler: HttpErrorResponse) {
    return throwError(errorHandler.message || "server error");
  }
}

bookcomponent.ts
export class BookComponent implements OnInit {
  public books = [];
  public errorMessage;
  book = new Book();
  constructor(private _bookService: BookService) { }

  ngOnInit() {
    this.getBooks();
  }
  getBooks():void{
    this._bookService.getAllBooks()
    .subscribe(
      data => {
        this.books = data;
        console.log(data)
      },
      error => {
        this.errorMessage = error
        console.log(error);
      }
    );
  }

  addBook():void{
    this._bookService.addBook(this.book)
    .subscribe(
      (response) => {
        console.log(response)
      },
      (error) => {
        console.log("Error occurred :" + error);
      }
    );
  }

}

A:

Please try this first. Let me know if you have already tried this approach
Change return this._http.post<Book>(this._postBooksUrl, body, httpOptions)
  to return this._http.post<Book>(this._postBooksUrl, body, {responseType: 'text'})


Q:

How can I escape a sequence of HTML so it can go inside a tags title attribute?

I've been working on this for way too long. I'm trying to put HTML inside the title attribute of a tag. This is for a tooltip. Of course, if this is going to be possible, then I have to escape all of the necessary characters so it doesn't screw up the tag in which it is contained. To be specific, how can I fit the following inside the title attribute of a tag:
test

That is, I want this:
<div title="test">my div

I feel like I've tried everything. Is this even possible?

A:

I googled HTML Escape Characters and found a tool to do it: http://accessify.com/tools-and-wizards/developer-tools/quick-escape/default.php
It produced this string which you can use:
<a href="test">test</a>


Q:

OnClick() with Highcharts in MVC 4

I'm a coop student and I'm working with Highcharts in MVC 4. My employer would like to be able to click on a column on a Column chart and have it take the user to a new page. Does anyone have any ideas on how to do this?
I'm having a hard time finding examples of Highcharts in MVC, so if someone has some good resources please send them my way.

A:

Thanks to the comment and the resource here I was able to solve my own problem. My view takes in a Highcharts object as the model, and when my Controller passes it the following Highcharts object it works:
new Highcharts("chart")
//define the type of chart
.InitChart(new Chart { DefaultSeriesType = ChartTypes.Column})
//overall Title of the chart
.SetTitle(new Title { Text = chartTitle })
//small label below the main Title
.SetSubtitle(new Subtitle { Text = subTitle })
//load the X values
.SetXAxis(new XAxis { Categories = xAxisData })
//set the Y title
.SetYAxis(new YAxis { Title = new YAxisTitle { Text = yAxisTitle } })
.SetTooltip(new Tooltip
{
    Enabled = true,
    Formatter = @"function() { return ''+ this.series.name +'
'+ this.x +': '+ this.y; }"
})
.SetPlotOptions(new PlotOptions
{
    Line = new PlotOptionsLine
    {
        DataLabels = new PlotOptionsLineDataLabels
        {
            // this makes the value of the dot appear above it if it is set to true (for Line charts)
            Enabled = true
        },
        // set to true so that when the user hovers their mouse over a column/dot it's value and name will appear
        EnableMouseTracking = true
    },
    /***********
     * IMPORTANT PART
     ************/
    Series = new PlotOptionsSeries
    {
        Point = new PlotOptionsSeriesPoint
        {
            Events = new PlotOptionsSeriesPointEvents
            {
                // Here you can put code for different event handlers (like Click and MouseOver) in javaScript.
                // The one below makes an alert box pop up with the name of the column and its value when a
                // column is clicked
                Click = "function () {alert('Category: ' + this.category + ', value: ' + this.y);}"
            }
        }
    }
})
//load the Y values
.SetSeries(yAxisData.ToArray());


Q:

Voltages go crazy when using 74LVC8T245

I am using a 74LVC8T245 buffer from Texas Instruments to interface 3.3V to 5V signals with my 3.3V microcontroller, here is my circuit:

The IC is powered by a 3.3v LDO Regulator MCP1702T. Now, when I put a 5V signal on Port B the 3.3V supply goes to 4.2-4.5V! Why is this happening? AFAIK I can go up to 5V with this IC even powering it with 3.3V.

A:

My fault! The DIR control pin was not being set to 0V apparently so B port was an Output instead of Input port.
This IC is 5V tolerant that means you can put 5V signals even if you are powering it with 3.3V. Read about this here: http://e2e.ti.com/support/interface/etc_interface/f/391/p/281884/987616.aspx#987616


Q:

How to know if a file descriptor is opened?

Here I have some questions when using open in a multi-thread case with pthread_cancel(). In the thread I need to open some files to read.
So my first question is that do I need to enclose the fields where I use those opened file descriptors with pthread_cleanup_push() and pthread_cleanup_pop(). I think if the thread is cancelled with the files still opened, it won't be good.
However, as far as I know, the open() function itself is a possible cancellation point. And I don't know if the file descriptor is opened or not if a cancel happened there (or where can I get the information of that?)
At last, is there a Unix interface to tell if the file descriptor is opened or not?

A:

Yes, using pthread_cleanup_push() is a good idea.
If the thread is cancelled in open(), the file descriptor won't be open so the cleanup code simply has to close anything that was opened previously.
You can use fstat() to check if a file descriptor is open. Or you can use one of the other functions that take a file descriptor as an argument, looking for EBADF (bad file descriptor) if the descriptor is not open).  The advantage of fstat() is that it is a pure interrogation function whereas most others try to change something about the descriptor.  fcntl() can do queries too.


Q:

Cannot retrieve "_id" value using mgo with golang

This is my struct definition:
type Article struct {
    Id      bson.ObjectId `json:"id"        bson:"_id,omitempty"`
    Title   string        `json:"title"`
    Author  string        `json:"author"`
    Date    string        `json:"date"`
    Tags    string        `json:"tags"`
    Content string        `json:"content"`
    Status  string        `json:"status"`
}

This is the method I get my data from database:
func AllArticles() []Article {
    articles := []Article{}
    err := c_articles.Find(bson.M{}).All(&articles)
    if err != nil {
        panic(err)
    }

    return articles
}

This is one piece of object stored in database:
{ "_id" : ObjectId( "5281b83afbb7f35cb62d0834" ),
  "title" : "Hello1",
  "author" : "DYZ",
  "date" : "2013-11-10",
  "tags" : "abc",
  "content" : "This is another content.",
  "status" : "published" }

This is the printed result:
[{ObjectIdHex("") Hello1 DYZ 2013-11-10 abc This is another content. published}     {ObjectIdHex("") Hello2 DYZ 2013-11-14 abc This is the content. published}]

It seems that I can't get the real value of _id field, it's always "". What's the problem?

A:

I've found the problem.
In the code:
Id      bson.ObjectId `json:"id"        bson:"_id,omitempty"`

between json: and bson:, I used a tab instead of space so the problem occurs. If I change this line of code to:
Id      bson.ObjectId `json:"id" bson:"_id,omitempty"`

With one space between json: and bson:, it turns out to work just fine.

A:

I had the same issue and was able to figure out that I had my imports mixed up. I have a feeling that Gustavo could not reproduce the problem because you had not included what your imports looked like and he filled them out correctly.
Just to explain briefly how my issue was similar:
This -
err := db.Find(bson.M{"_id": bson.ObjectIdHex(userId)}).One(&user)

was not working for me, it would not get the info from the database and would return this-
{ObjectIdHex("")    }

How I fixed it...we found that
In the server.go page, one of the imports was this.
"gopkg.in/mgo.v2”

Should have been this.
"labix.org/v2/mgo”

The real bug is not the use of the gopkg.in/mgo.v2. It is that the code was mixing labix.org/ and gopkg.in import modules.
So the trick is to use this.
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson”

Or this.
"labix.org/v2/mgo"
"labix.org/v2/mgo/bson”

But not mix them. The top one is the preferred one, as that is what the latest docs use.
Hope this helps.

A:

Your code is fine.
Here is a self-contained example that includes your code, unmodified:

http://play.golang.org/p/7C9roLtL0f

And here is the output:
"R\x94\xa4J\xff&\xc61\xc7\xfd%\xcc" "Some Title"

The issue is elsewhere. The collection may really not have an _id field, for example.


Q:

in regx, is it possible to accurately extract a json scalar value?

wish to extract a scalar value from json.

know JSON uses double quotes.
know datatype of scalar: string, number, date, boolean.
know scalar will be on first level, ie, not an attribute of an embedded object
{ "want": "string" }  => "string"
{ "want": 123 } => 123
{ "not": { "want": "wrong" }, "want": "right" } => "right
{ "nothing": 0 } => null / not found

do not know how to handle the opening/closing quotes, nor do I know how to handle embedded objects.
is this possible?

this is the best I have come up with so far:
// match `want` attribute
(?:"want"\s*:\s*)

// string, number, boolean or null
(((?:")([^"]*)(?:"))|([-0-9][.eE0-9]*)|true|false|null)

// followed by comma or right bracket
(?:\s*(,|}))

it's good because it

can be run in postgres
grabs strings
grabs numbers
grabs boolean and null

it's bad because it

does not ensure want is a first level attribute
string value cannot have quote (") inside

A:

This expression will get you 50% of the way there:
(?<=:\s*)(".*?"(?<!\\")|\-?(0|[1-9]\d*)(\.\d+)?([eE][+-]?\d+)?)(?=\s*})

Or, when written as a multi-line regex:
(?x:
    (?<=:\s*)           # After : + space
    (

        ".*?"(?<!\\")   # String in double quotes

        |               # -or-

        \-?             # Optional leading -ve
        (0|[1-9]\d*)    # Number
        (\.\d+)?        # Optional fraction
        ([eE][+-]?\d+)? # Optional exponent

    )
    (?=\s*})            # space + }
)

This will not match your nested object example ({ "not": { "want" ...) or rather, it will match, but on the wrong thing. Also, your final example ({ "nothing": 0 } => null / not found) is difficult because 0 is a valid number. To work around the this problem, I would just check the result in procedural code and replace a result of 0 with null.
The nested objects problem is a whole different ball game though. It's getting into the realm of lexical analysis rather than simple tokenizing. At that point, you might as well just use a JSON library because you'd be writing a full JSON parser anyway. Fortunately, JSON is a simple enough grammar that it wouldn't be that expensive to use a third party library - certainly no more than doing it yourself.
I think the short answer is: from a simple { "name" : <value> } object, yes, but from anything more complicated, no.
For info on the JSON syntax, see http://www.json.org/.


Q:

aws cli cannot read from dynamodb docker container

i am running dynamodb on a docker container and am able to write to the table using python boto3, which is all fine and good.
now when I query the dynamodb table from outside the container using aws CLI, its give this error and cannot find the table
╰─➤  aws dynamodb --region=eu-west-1 --endpoint-url http://localhost:8000  scan --table-name devApiConfig

A client error (ResourceNotFoundException) occurred when calling the Scan operation: Cannot do operations on a non-existent table

the name of the sqlite db created by dynamodb docker container is
localaccesskey_eu-west-1.db

aws --region=eu-west-1 dynamodb list-tables --endpoint-url http://localhost:8000
{
    "TableNames": []
}

Any ideas or hints, as the tables do exist on the dynamodb when used from Boto3....?

A:

I have answered this in another question:
https://stackoverflow.com/a/40806393/1061798
Check how your docker is starting Dyanmo. If you are using deangiberson/aws-dynamodb-local (as I was), then you will need to change the start parameters to add -sharedDb. Either amend the Dockerfile or run as follows:
docker run -p 8000:8000 -d -it deangiberson/aws-dynamodb-local "-sharedDb"

I haven't tested, so let me know if this doesn't work, but hopefully you get the idea.


Q:

PDO bind parameters

I'm building simple query builder, and I have two questions:

Is it possible to secure mysql queries with normal functions to the similar level as it is done using ->execute(array(':param:' => ... ?
Is it possible to use many variables in one query, give them the same names (the ones after the semicolon), and then bind them one by one?

A:

If I understand you correctly, you would like to know if it possible to replicate the functionality of bindParam with the standard mysql_* functions?
Short answer is no. Please do not use the mysql functions at all, use mysqli or PDO as these provide you with the true security when it comes to prepared statements. They can also provide much better query performance as the SQL is able to be pre-optimised for the database.

You will have to define each parameter separately (even if it is the same value). You could also pass a simple array to the execute() method call, but you do not then have the option to explicitly define the parameter types.

Within your function use some thing like this:
$name = "fred";
$statement = $pdo->prepare("SELECT id FROM contacts WHERE first_name = ? OR last_name = ?");
for ($x = 1; $x <= 2; $x++) {
  $statement->bindParam($x, $name, PDO::PARAM_STR);
}
$statement->execute();


Q:

What is the equivalent of "/tmp/.X11-unix/X0" on Windows when using things like Xming?

I want to know what exactly does the display name like :0.0 mean on Windows. Where does Xming place its listener socket for others to find? When I set the "Display location" in PuTTY, where does it go to connect to it? What is the equivalent of a "unix domain socket" on Windows anyway?
Finally, who exactly sets the standard for how these displays are managed on Windows, and where can I find it?

A:

Xming and PuTTY use TCP sockets on the loopback address; the empty host name equals localhost. The TCP port numbers allocated for X11 start at 6000 for display :0, 6001 for display :1 and so on.
This is not actually Windows-specific behavior – X has been originally designed as a TCP/IP protocol and used that way for decades, which is the reason 'xauth' and even the idea of an "X server" exist. So it is the natural fallback when local sockets are unavailable.

That said, Windows NT has close equivalents to Unix domain sockets. Named pipes on Windows are bidirectional and can be packetized. (However, while they have paths, they only exist in a virtual "pipefs" and not as real filesystem entries, so they're closer to Linux abstract namespace sockets than regular ones.)
Second, Windows 10 has actually added the same AF_UNIX socket type in release 1803, although probably no software uses it yet.
Libraries such as Cygwin or libassuan also emulate Unix sockets via loopback TCP, although not always in a compatible manner.


Q:

c++ performance improvement for a simple function

I have a function in my program that gets called many many times. It is not particularly slow, it is just that it gets called so many times that any little improvement can help a lot.
inline static void addFanVertex(GLfloat x,GLfloat y, GLfloat r, GLfloat g, GLfloat b) {
            tf.push_back(x);
            tf.push_back(y);
            tf.push_back(r);
            tf.push_back(g);
            tf.push_back(b);
            tfe.push_back((tf.size()/5)-1);
        }

tf and tfe are vectors:
std::vector<GLfloat> Renderer::tf;
std::vector<GLuint> Renderer::tfe;

I use std::reserve already to set their correct capacity. (Doesn't have significant performance improvements)
Anyone know something that would speed it up slightly?

A:

I think there is no so many thing to do about your function. A little bit context could help in this case.
For example it could be no necessary push values in the vector in each cycle, or maybe the operator[] could be used.
Anyway just seeing that, I'd say to try something like:

Check in disassemble whether the arguments are passed by stack allocation or by registers (it depend on the compiler). In case of stack you could "compress" your arguments in a struct and pass just that argument to the function. Moreover that struct should be pre-allocated with a static or a member function in the caller.
You could think to use noexcept specifier (in case your compiler support it). That may enable some optimized compiler's operations. This in accordance with the fact the resources are pre-allocated correctly in the program and you trust that code.
Use an profiler to see which micro-operations (also assembly lines) are the bottleneck of the function.


Q:

Website hosted on Wordpress sending request to other servers remotely

I have a WordPress website hosted on Amazon Ubuntu. Amazon reported that my server is sending a WordPress login attempt requests to other servers on Amazon. My website is just a landing page with a contact form (gettightenup.com). How to prevent such incidents?

A:

You can block external http requests check adding
define( 'WP_HTTP_BLOCK_EXTERNAL', true );

in wp-config.php

A:

Since you have already found a bad curl call in your source, I strongly suggest you check the integrity of your Wordpress installation.
If you have WP CLI available you can do this with the command wp core verify-checksums.
If you don't have WP CLI available you can use this excellent solution by Jan Reilink (either directly or as a starting point for your own code).
Either way you'll get output that tells you whether or not additional files have been modified (you could then restore them from the same WP version source). This will not be a catch-all-method in regards to malware, but I think it can be helpful in your specific situation.
Given that the code that's causing these requests is not part of the Wordpress core the answer to your question is some of the general best security practices for Wordpress:

Keep Wordpress and plugins updated
Use strong passwords for users
Add a captcha and brute force protection to your login page if possible


Q:

Graphql returning Cannot return null for non-nullable field Query.getDate. As I am new to graphql I want to know is my approach is wrong or my code?

I have created resolver, schema and handler which will fetch some record from dynamoDB. Now when I perform query then I am getting "Cannot return null for non-nullable field Query.getDate" error. I would like to know whether my approach is wrong or there is any change required in code.
My code : https://gist.github.com/vivek-chavan/95e7450ff73c8382a48fb5e6a5b96025
Input to lambda :
{
  "query": "query getDate {\r\n      getDate(id: \"0f92fa40-8036-11e8-b106-952d7c9eb822@eu-west-1:ba1c96e7-92ff-4d63-879a-93d5e397b18a\") {\r\n        id\r\n        transaction_date\r\n      }\r\n     }"
}

Response :
{
  "errors": [
    {
      "message": "Cannot return null for non-nullable field Query.getDate.",
      "locations": [
        {
          "line": 2,
          "column": 7
        }
      ],
      "path": [
        "getDate"
      ]
    }
  ],
  "data": null
}

Logs of lambda function :
[ { Error: Cannot return null for non-nullable field Query.getDate.
         at completeValue (/var/task/node_modules/graphql/execution/execute.js:568:13)
         at completeValueCatchingError (/var/task/node_modules/graphql/execution/execute.js:503:19)
         at resolveField (/var/task/node_modules/graphql/execution/execute.js:447:10)
         at executeFields (/var/task/node_modules/graphql/execution/execute.js:293:18)
         at executeOperation (/var/task/node_modules/graphql/execution/execute.js:237:122)
         at executeImpl (/var/task/node_modules/graphql/execution/execute.js:85:14)
         at execute (/var/task/node_modules/graphql/execution/execute.js:62:229)
         at graphqlImpl (/var/task/node_modules/graphql/graphql.js:86:31)
         at /var/task/node_modules/graphql/graphql.js:32:223
         at graphql (/var/task/node_modules/graphql/graphql.js:30:10)
       message: 'Cannot return null for non-nullable field Query.getDate.',
       locations: [Object],
       path: [Object] } ],
  data: null }
2019-02-25T10:07:16.340Z    9f75d1ea-2659-490b-ba59-5289a5d18d73    { Item:
   { model: 'g5',
     transaction_date: '2018-07-05T09:30:31.391Z',
     id: '0f92fa40-8036-11e8-b106-952d7c9eb822@eu-west-1:ba1c96e7-92ff-4d63-879a-93d5e397b18a',
     make: 'moto' } }

Thanks in advance!

A:

This is your code:
const data = {
  getDate(args) {
    var params = {
        TableName: 'delete_this',
        Key: {
        "id": args.id
        }
    };
    client.get(params, function(err,data){
        if(err){
        console.log('error occured '+err)
        }else{
        console.log(data)
        }
    });
  },
};
const resolvers = {
  Query: {
    getDate: (root, args) => data.getDate(args),
  },
};

You're seeing that error because getDate is a a Non-Null field in your schema, but it is resolving to null. Your resolver needs to return either a value of the appropriate type, or a Promise that will resolve to that value. If you change data like this
const data = {
  getDate(args) {
    return {
      id: 'someString',
      transaction_date: 'someString',
    }
  }
}

you'll see the error go away. Of course, your goal is to return data from your database, so we need to add that code back in. However, your existing code utilizes a callback. Anything you do inside the callback is irrelevant because it's ran after your resolver function returns. So we need to use a Promise instead.
While you can wrap a callback with Promise, that shouldn't be necessary with aws-sdk since newer versions support Promises. Something like this should be sufficient:
const data = {
  getDate(args) {
    const params = //...
    // must return the resulting Promise here
    return client.get(params).promise().then(result => {
      return {
        // id and transaction_date based on result
      }
    })
  }
}

Or using async/await syntax:
const data = {
  async getDate(args) {
    const params = //...
    const result = await client.get(params).promise()
    return {
      // id and transaction_date based on result
    }
  }
}


Q:

Maximum characters in Multiple lines of text Column

How many maximum characters in Multiple lines of text Column can be added in SharePoint 2013 ?
I am not able to find anything on here,
https://technet.microsoft.com/en-us/library/cc262787.aspx#Column

A:

Document libraries and lists have different options available with respect to the multiple lines of text column type.
In document libraries, when you create a new column of type Multiple Lines of Text, you get the option to select the Allow unlimited length in document libraries checkbox.
But, In lists, this option does not exist.
A multi line text field is defined in SharePoint as a Note type, this is stored in the DB as a ntext sql type. In this SQL type you can store 2gb of char data, that's 1,073,741,823 characters.

Note: It is not advisable to store such huge data in SharePoint column
  as it may hamper performance.

Explanation referred from this TechNet
Also if your are working with multi lines text field in Doc libs then this is a nice article to read
I hope this is a helpful information!!

A:

A Multiple lines of text column can store up to 63,999 characters


Q:

Facebook Graph API Comment Doesn't Return From

I have a Facebook comment and I would like to get the user ID of the author of the comment. I am able to get this information when the comment is posted on the page that I own with this query:
https://graph.facebook.com/v2.11/comment_id?fields=from&access_token=access_token
However, the same does not work when I am accessing a comment that is not posted on my own page, the from field is never returned. Is it possible to get the author of a comment that is posted on a different page?

A:

Is it possible to get the author of a comment that is posted on a different page?

No, that information is not available to you any more.
https://developers.facebook.com/docs/graph-api/changelog/version2.11#gapi-90-pages:

/page/* — User information will not be included in GET responses for any objects owned by (on) a Page unless the request is made with a Page access token. This affects all nodes and edges that return data for objects owned by a Page.


Q:

Callback not executing in javascript

I wrote a method that is supposed to execute a callback, but the callback isnt being executed:
buildTable('lt', 'viewltDetails', commonTireColumns, function(error) {
if(error) {
    console.log(error);
} else {
    console.log('calculating');
    calculatedPricing();
}
});

My buildTable function - it essentially creates a datatable using the aldeed-tabular package:
function buildTable(tblName, detailsBtn, columnDetails) {
var columns = [];
for(var key in columnDetails) {
      columns.push({
        data: columnDetails[key].data,
        title: columnDetails[key].title,
        width: columnDetails[key].width
      });
    };
columns.push({
    title: "Quantity",
    tmpl: Meteor.isClient && Template.itemQuantityCell,
    width: "2%"
});
columns.push({
    title: "Details",
    tmpl: Meteor.isClient && Template[detailsBtn],
});
columns.push({
    title: "Action",
    tmpl: Meteor.isClient && Template.addToCartCell,
});

TabularTables[tblName] = new Tabular.Table({
    name: tblName,
    changeSelector: function(selector, userId) {
        return selector;
    },
    collection: Products,
    pub: "tabular_Products",
    columns: columns,
    extraFields: ['priceFET', 'invoicePrice', 'category']
})
};

The buildTable function works fine, but it's not executing the console.log('calculating') and calculatePricing() commands, although the function isn't throwing any errors.
My calculatePricing function looks like:
calculatedPricing: function() {
    var price = 300;
    return price;
};

Can someone help? Thanks!!

A:

Please try like this.
You add a calback function but you don't have it at a parameter so you never call it on your function.
 function buildTable(tblName, detailsBtn, columnDetails, callback) {
         //your code here
         if(typeof callback === "function"){
           callback();
         }
    }


Q:

How to show the current user using ASP MVC and EF

I am developing an ASP .Net MVC 3 application using C# and SQL Server 2005. I am using also Entity Framework with Code First Method.
I have an interface for the LOG ON (connection) which it is related to my base where i have a USER table (contain Login + password).
I am just want to show the Current User which is logged. So, I created a ViewModel Class for the User but i didn't get any result.
This is what I tried to do in my Controller :
public ActionResult LogOn()
        {

            var user = new UserViewModel();
            user.Nom_User = this.User.Identity.Name;
            ViewData["UserDetails"] = user;
            return View();
        }

and this what I add in the master page :
    <% var User = ViewData["UserDetails"] as MvcApplication2.ViewModels.UserViewModel; %>
 Hello : <%: User.Nom_User  %>!

When I execute, I have this error :

Object reference not set to an instance of an object.

A:

You said that you placed this code in your MasterPage. This means that it will run for every view.
But you have set the ViewData["UserDetails"] only inside the LogOn action. So when you navigate to some other action (such as the Home/Index action for example) it will bomb because there's nothing inside this ViewData["UserDetails"] and of course this User variable which you declared in your MasterPage will be null.
I would recommend you using a child action for that.
[ChildActionOnly]
public ActionResult LogedInUser()
{
    if (!Request.IsAuthenticated)
    {
        return PartialView();
    }

    var user = new UserViewModel();
    user.Nom_User = User.Identity.Name;
    return PartialView(user);
}

and in your MasterPage:
<% Html.RenderAction("LogedInUser", "Account"); %>

or if you prefer:
<%= Html.Action("LogedInUser", "Account") %>

And finally you could have the corresponding LogedInUser.ascx partial that will be strongly typed to your view model:
<%@ Control
    Language="C#"
    Inherits="System.Web.Mvc.ViewUserControl<UserViewModel>"
%>

<% if (Model != null) { %>

Hello : <%= Html.DisplayFor(x => x.Nom_User) %>

<% } %>

Phil Haack blogged about child actions in more details here.


Q:

Having an issue finding the right UNIX grep command

This is the assignment:

Write a script that will generate a single sorted list of three- to five-letter words. Input text will be generated from the on-line ls manual pages (output from ’man ls’ command).

This is my code so far:
man ls | sed '!s/ //g' | tr 'A-Z' 'a-z' | tr -s '\040' '\012' | sort | uniq -u

Here is where I get stuck. We are provided with steps to get the desired result however I am having trouble figuring out the proper grep command. These are the directions:

Using a single grep command, extract the 3 to 5-letter words. Keep in mind that each “word” is now on its own line. You will need to use a regular expression that specifies the whole line (not just a pattern found somewhere in the line). We know that the asterisk represents “zero or more of the previous pattern.” What regular expression is used to represent “from three to five instances of the previous pattern on a line by itself?”. [ Whole line match? You have regurar expression “anchor points” that specify the beginning and end of the line. Use them!

I think it should look something like this, but it doesn't work.
grep '{3,5}'

EXTRA INFORMATION

Filter out all characters except spaces and alpha characters (A-Za-z). You can do this by using the stream editor (sed) to remove (substitute with nothing) all characters not in that set. Hint: How do you specify the regular expression to match a single character that is not an alpha or space character?
To avoid duplicates, convert all the letters to the same case. The translate command (tr) should be used to do this (see page 83 of the textbook). For example, ‘The’ and ‘the’ need to be treated as the same word. By making all the text the same case (either upper or lower), you will avoid listing the same mixed-case word more than once.
Modify the remaining text such that each “word” is placed on its own line. Use the tr command to convert all spaces to newlines. Every single “word” is now on a line by itself. Don’t worry about the empty lines. They’ll get filtered out later.
Use the sort command to sort the lines (“words”). Is there an option we can use with sort to remove duplicate lines? Use that option.
Using a single grep command, extract the 3 to 5-letter words. Keep in mind that each “word” is now on its own line. You will need to use a regular expression that specifies the whole line (not just a pattern found somewhere in the line). We know that the asterisk represents “zero or more of the previous pattern.” What regular expression is used to represent “from three to five instances of the previous pattern on a line by itself?”. [ Whole line match? You have regurar expression “anchor points” that specify the beginning and end of the line. Use them! ]

I'm very new to this, and haven't been able to find the right way to do it anywhere, probably because I'm not searching for the right thing. If you are familiar with how to do it, I would appreciate if you could also explain how it works instead of just giving the answer. Thank you so much for the help!

A:

1) Filter out all characters except spaces and alpha characters (A-Za-z). You can do this by using the stream editor (sed) to remove (substitute with nothing) all characters not in that set. Hint: How do you specify the regular expression to match a single character that is not an alpha or space character?
What your teacher probably expects:
sed 's/[^A-Za-z ]//g'

The right way:
sed -r 's/[^[:alpha:][:space:]]+//g'

2) To avoid duplicates, convert all the letters to the same case. The translate command (tr) should be used to do this (see page 83 of the textbook). For example, ‘The’ and ‘the’ need to be treated as the same word. By making all the text the same case (either upper or lower), you will avoid listing the same mixed-case word more than once.
Your teacher:
tr 'A-Z' 'a-z'

The right way:
tr '[:upper:]' '[:lower:]'

3) Modify the remaining text such that each “word” is placed on its own line. Use the tr command to convert all spaces to newlines. Every single “word” is now on a line by itself. Don’t worry about the empty lines. They’ll get filtered out later.
Your teacher:
tr ' ' '
'

better::
tr '[:blank:]' "$'\n'"

4) Use the sort command to sort the lines (“words”). Is there an option we can use with sort to remove duplicate lines? Use that option.
sort -u

5) Using a single grep command, extract the 3 to 5-letter words. Keep in mind that each “word” is now on its own line. You will need to use a regular expression that specifies the whole line (not just a pattern found somewhere in the line). We know that the asterisk represents “zero or more of the previous pattern.” What regular expression is used to represent “from three to five instances of the previous pattern on a line by itself?”. [ Whole line match? You have regular expression “anchor points” that specify the beginning and end of the line. Use them! ]
Teacher:
grep -E '^[a-z]{3,5}$'

Better:
grep -E '^[[:alpha:]]{3,5}$'

Now, figure out which of each of the commands above your notes actually support you using, the differences between them and glue them together with pipes. Good Luck!
BTW here's how you'd do it in UNIX with one command instead of multiple in a pipe, in this case using GNU awk for sorted arrays, with other awks just pipe to sort:
$ man ls | awk '
        {
            gsub(/[^[:alpha:][:space:]]+/," ")
            $0=$0
            for (i=1;i<=NF;i++)
               if ($i ~ /.{3,5}/)
                   words[$i]
        }
        END {
            PROCINFO["sorted_in"]="@ind_str_asc"
            for (word in words)
                print word
        }'


Q:

javascript window closing after 15mins

Now, I have script that works, but only if time interval for closing is small (5mins works), but when I try to set timeout to 15mins, it fails every time. The script I'm using is:
function openClose(){
    my_window = window.open('http://www.somesite.com',
    "mywindow","status=1,width=1010,height=740");  //this should execute closepopup() after 15mins if my math is correct
    setTimeout(closepopup,900000);
    }
    function closepopup(){
        if(false == my_window.closed){
            my_window.close();
        }
    }

A:

Just a thought - could garbage collector dispose unwanted variables? I can see that my_window is a global one, try to persist timer variable as well:
timer = setTimeout(closepopup,900000)

Please, let me know if this works for you.