Q:

Cannot make static reference to the non-static type t

I am trying to create a static method that returns a Generic Object of the same class which the static method is a member of but there is compilation error on the return type as

Cannot make a static reference to the non-static type T

Looking at other solutions on stack overflow I found this
(Generics)Cannot make a static reference to the non-static type T
where a responder has provided an answer which says that for static methods, we must also include the target type  before the return type but even this does not work
public class Condition<T extends Node> {

private boolean isInitialized=false;
private ConditionType type;
private NodeType nodeType;
private String propertyName;
private Predicate<T> onlyIfTest;
private Predicate<T> predicates;

private Condition() {

}

//Here at the return type i get the error Cannot make static...
public static Condition<T> include(NodeType type,String propertyName) {
    Condition<T> condition = new Condition<T>(); //and an error here too
    condition.type = ConditionType.INCLUDE;
    condition.nodeType = type;
    condition.propertyName = propertyName;
    condition.isInitialized =true;
    return condition;
}

The error that i get is Cannot make a static reference to the non-static type T. How can i make it work with a static method.

A:

You've already had your answer:

we must also include the target type before the return type

but didn't apply it.
public static <T extends Node> Condition<T> include(NodeType type, String propertyName)


Q:

Is it permited to download javascript code to iPhone

I have an hybrid application, it's basically a website running from the application folder inside a UIWebview.
The problem is that I was planning to update my website by downloading the whole website from internet and then replacing the old website.
Today I found that Apple now provides the App Store Review Guidelines and among others there are the following rules:

2.7 Apps that download code in any way or form will be rejected
2.8 Apps that install or launch other executable code will be rejected

Because my site has html, css and javascript, does that mean that my app will be rejected or is there any chance to be accepted?
What are your thoughts on that?

A:

From the new text of of the application developer agreement, regarding downloading executable code:

The only exception to the foregoing is scripts and code downloaded and run by Apple's built-in WebKit framework.

This includes javascript and hybrid applications, so you should be fine.
Although, taking all of this into account, why didn't you just allow your app to take advantage of the iPhone webapp stuff? You still get an icon on the home screen, and get rid of the browser chrome without having to get Apple to approve your app.


Q:

Animating KnockoutJS template changes

I'm using a dynamic template name. So I cant change out the template based on some selected values. What I'd like to do is fade out (or any animation for that mater) the old template elements before rendering the new one. There is this concept if you are iterating over a list but not for the root template itself. Has anyone tried this or got this to work?

A:

You could write your own binding handler:
ko.bindingHandlers.fadeTemplate = {
    init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
        return ko.bindingHandlers['template']['init'](element, valueAccessor, allBindings);
    },
    update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
        var value = valueAccessor();
        $(element).fadeOut(function() {
            ko.bindingHandlers['template']['update'](element, valueAccessor, allBindings, viewModel, bindingContext);
            $(this).fadeIn();
        });
    }
};

http://jsfiddle.net/xP7uy/


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:

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:

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:

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:

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:

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:

Why I'm getting Invalid arguments for the function when using double-quotes?

I'm trying to insert a filename into text as below:
:put=expand("%")

but I've the following errors:

E116: Invalid arguments for function expand(
  E15: Invalid expression: expand(

Why this doesn't work?
What's most surprising thing is that it works when using single-quote instead, e.g.:
:put=expand('%')

So I'm trying to understand:

Is there any differences between using double-quotes or single-quotes? If so, what kind?

I'm using Vim v7.4.

A:

From :help :put:

The register can also be = followed by an optional expression. The expression continues until the end of the command. You need to escape the | and " characters to prevent them from terminating the command.

For the difference between " and ' in the context of an expression, see :help expr-quote and :help expr-'.


Q:

Introducing Brevity Into C# / Java

Background
Currently, if I want to create a new object in C# or Java, I type something similar to the following:

List<int> listOfInts = new List<int>(); //C#
ArrayList<String> data = new ArrayList<String>(); //Java

C# 3.0 sought to improve conciseness by implementing the following compiler trick:

var listofInts = new List<int>();

Question
Since the compiler already knows that I want to create a new object of a certain type (By the fact that I'm instantiating it without assigning it a null reference or assigning a specific method to instantiate it), then why can't I do the following?
    //default constructors with no parameters:
    List<int> listOfInts = new(); //c#
    ArrayList<String> data = new(); //Java

Follow Up Questions:

What are possible pitfalls of this approach. What edge cases could I be missing?
Would there be other ways to shorten instantiation (without using VB6-esque var) and still retain meaning?

NOTE: One of the main benefits I see in a feature like this is clarity.  Let say var wasn't limited. To me it is useless, its going to get the assignment from the right, so why bother?  New() to me actually shortens it an gives meaning.  Its a new() whatever you declared, which to me would be clear and concise.

A:

C# saves in the other end:
var listOfInts = new List<int>();

A:

What edge cases could I be missing?

I briefly discussed this possible C# syntax on my blog in January. See the comments to that post for some reader feedback on the pros and cons of the syntax.

Would there be other ways to shorten instantiation (without using VB6-esque var) and still retain meaning?

Possibly, yes.
"var" in C#, however, is nothing like "variant" in VB6. "var" does not mean the same thing as "object", nor does it introduce dynamic typing or duck typing. It is simply a syntactic sugar for eliminating the redundant stating of the type of the right hand side.

A:

In C# 3 there's already the mirror image for local variables, implicitly typing:
var listOfInts = new List<int>();

This doesn't work for non-local variables though.
In Java, type inference takes into the assignment target into account, so using static imports and cunning libraries such as the Google Java Collections you can write code such as:
List<Integer> integers = newArrayList();

Note that that keeps the variable interface-based while specifying the implementation in the construction side, which is nice.


Q:

Fixing Macbook Pro keyboard key

The e key on my keyboard started to feel weird. After some attempts to clean it, I’ve decided to remove it and noticed the membrane is the middle was loose. I’ve only noticed this is atypical because the instructions I found on removing keys mentioned it should be held in place.

After cleaning the key, it’s (considerably) better but not perfect, and I wonder if the loose membrane is to blame. Is there a safe way to fix it?
By “safe” I mean a method that is unlikely to break it. The key isn’t perfect but it is usable, so I won’t follow a method that risks breaking it, as I wouldn’t have the money to send it in for repairs.
This is an older retina Macbook Pro (late 2015 15-inch) with the scissors (not butterfly) switches.

A:

There's a good chance the loose membrane is to blame and affixing it in place would solve the issue. Before continuing, you can verify if the membrane is the issue or it's something else by powering the laptop on with the key and membrane removed, opening some kind of document on the computer, then using a toothpick or other small (non-sharp) object to push down the center location. If that regularly causes an e character (or whatever key is at issue) to be input in to the document, the keyboard electronics are in good shape.
With that done, try holding the membrane down (by its edges) in place over the switch location, while using your fingertip to depress the membrane in the center. You should see  e characters being emitted as before. This is the location you want to affix the membrane.
Additionally, double-check that the scissor-spring part of the key is in good shape. Grit or broken plastic in that part would also explain the key feeling off, so verify that it's in good shape before proceeding. (If it's not obvious, remove a working, known-good key and compare them.)
Putting the Membrane in Place
You might not love this suggestion because of its permanence, but I think your best bet is using cyanoacrylate (super glue). I can't absolutely guarantee it won't harm the membrane, but I think it's very unlikely.

Power off the laptop.
Clean the area that you'll affix the membrane to: isopropyl (rubbing) alcohol or acetone on a Q-tip should do the trick. You likely also want to clean the rubber membrane.
Run a small bead of cyanoacrylate around the outer edge of the membrane.
Carefully place the membrane in the centered location you found above when testing the keyboard. Gently hold in place for a minute or so until the super glue has set.
Wait for it to fully cure. Overnight should be enough, a day should be absolutely safe. This might be overkill, but it would really suck to bump it out of alignment by rushing this part.
Power the laptop on, test it out by gently depressing on center of membrane: it should register keystrokes like before when you tested the keyboard.
Reassemble the key, you're done!

The upside to the above approach is that it (should) result in a permanent fix. But that also makes it feel risky, because if something goes wrong, it's extremely difficult to undo. A modified approach would be to put the membrane down in place without cyanoacrylate on it, then carefully put a bead around the edge, touching the outer edge of membrane and the metal where you're affixing it. If it turns out things went bad, acetone (nail polish remover) can break down cyanoacrylate, so you could carefully undo the process with some Q-tips and patience. But I think this approach would be less strong and easier to mess up, even if it has the upside of being (semi-)reversible.
Also, be careful when you're using the cyanoacrylate that it doesn't drip down off the metal (I think it's metal, not 100% sure, whatever the cross bar the membrane/switch sits on) and into the area below. Keep some acetone and Q-tips handy in case you need to clean up any accidents quickly.
Finally, I can't guarantee this will work and won't have an impact on the membrane -- I just don't know the exact chemical interaction. But I'm pretty sure you'll be okay and solidly affixing the membrane in place is the best chance of solving the issues you're seeing. But, you know, you follow instructions at your own risk, etc, etc.
Good luck!


Q:

SQL - Adding a blank row

I'm dealing with software that will use the query I'm building to get data from the database. The problem is that the software doesn't have tools to determine the table size, so I need to add a blank row after the last row of data, so the software can recognize the end of the table.
Here's an example of what the query would give:

And here's an example of what I need to get from the query:

I know it would be better to solve it in the application, but in this case I need to change my query. Is it possible?
Edit: I'm using SQL Server 2014, the database name is Test and the table name is Table2.

A:

Use UNION ALL after your query to add the blank row:
select t.* from (
  select FieldA, FieldB
  from Table2
  ..........
  union all
  select null, null
) t
order by case when coalesce(t.FieldA, t.FieldB) is null then 1 else 0 end

or:
select t.FieldA, t.FieldB from (
  select 0 as isblankrow, FieldA, FieldB
  from Table2
  ..........
  union all
  select 1, null, null
) t
order by isblankrow


Q:

Smaller operator gives error in javascript code

I have a javascript code in my xhtml file. Here it is:
<h:head>
    <h:outputStylesheet library="css" name="styles.css"  />
     <script>
            function dataTableSelectOneRadio(radio) {
                var id = radio.name.substring(radio.name.lastIndexOf(':'));
                var el = radio.form.elements;
                for (var i = 0; i < el.length; i++) {
                    if (el[i].name.substring(el[i].name.lastIndexOf(':')) == id) {
                        el[i].checked = false;
                    }
                }
                radio.checked = true;
            }
        </script>
</h:head>

The problem ist, inside the for loop it gives error for "<" operator saying that "The content of elements must consist of well-formed character data or markup.". I think it sees "<" as an html element i.e. "body, html etc. but i am not sure. How can i fix this?
Thanks
Edit: I now tried this but still an error. Is there a syntax error you see?
<script>
            function dataTableSelectOneRadio(radio) {
                var id = radio.name.substring(radio.name.lastIndexOf(':'));
                var el = radio.form.elements;
                for (var i = 0; i < el.length; i++) {
                    if (el[i].name.substring(el[i].name.lastIndexOf(':')) == id) {
                        el[i].checked = false;
                    }
                }
                radio.checked = true;
            }
        </script>

The error says that:
myaccounts.xhtml:5:52 Expected ) but found ;
                for (var i = 0; i < el.length; i++) {
                                                ^

myaccounts.xhtml:5:57 Expected ; but found )
                for (var i = 0; i < el.length; i++) {
                                                     ^

A:

Try using CDATA for the XML parser not to read the javascript content, your code would be like this:
<h:head>
    <h:outputStylesheet library="css" name="styles.css"  />
    <script>
        // <![CDATA[
        function dataTableSelectOneRadio(radio) {
            var id = radio.name.substring(radio.name.lastIndexOf(':'));
            var el = radio.form.elements;
            for (var i = 0; i < el.length; i++) {
                if (el[i].name.substring(el[i].name.lastIndexOf(':')) == id) {
                    el[i].checked = false;
                }
            }
            radio.checked = true;
        }
        // ]]>
    </script>
</h:head>


Q:

Replacing selected shapes with symbols in Illustrator

I have these rectangles placed at different places on the file to indicate bus stands. I want to now replace each one of these rectangles with a bus symbol.
How do I do that without dragging the symbol to each place, deleting the rectangle, and making sure that the symbol is in the "bus stand" sub layer?
Thanks.

A:

There is a great script that does exactly what you want.
It was written by @Loic Aigon, it's called SymbolReplacement and will cost you only a Thank you Email ^^


Q:

Uses for volume form on a pseudo-Riemannian manifold

I was thinking about a possible use for the volume form on pseudo-Riemannian manifold. In Riemannian context we can use it to define minimal surfaces. Is there some physical or geometric interpretation in pseudo-Riemannian context?

A:

One can define the volume functional for a pseudo-Riemannian manifold, and prove that a non-degenerate submanifold is a critical point of the volume functional if and only if its mean curvature vector vanishes, $H = 0$. However, one loses the geometric interpretation from the Riemannian case, namely, that surfaces with $H=0$ locally minimize the volume, with respect to variations keeping the boundary fixed. For example, in Minkowski space $\Bbb R^n_1$, spacelike hypersurfaces (i.e., hypersurfaces for which the restriction of the standard Lorentzian metric is actually Riemannian) maximize volume.
That said, one can study:

What happens to non-degenerate submanifolds with $H = 0$, finding conditions for when does it in fact maximize of minimize volume -- see for example Minimal Submanifolds in Pseudo-riemannian Geometry by Henri Anciaux.
when do we obtain some Calabi-Bernstein like results in the pseudo-Riemannian case (there are some results about that in Minkowski space, e.g. here.
What can one say about submanifolds satisfying the closest purely pseudo-Riemannian condition to $H = 0$: just having $H$ be a lightlike vector ($H \neq 0$ but $g(H,H)=0$). Such submanifolds are called marginally trapped, and can be used to represent surfaces of black holes in some $4d$ spacetime models, in physics (see relativity books, e.g. Hawking & Ellis, etc.).


Q:

How to insert normal text right below a block of text in Windows?

In programs such as Microsoft Word, Wordpad or even Evernote, it is possible to insert tables, lists or code block. If that block appear on the last line of the document, how to insert a normal text below it?
Here a document with a table in Microsoft Word, where the table is the last item on the document. If try to place my cursor at the furthermost possible place, I will end right after B. If I press enter, I may just insert a new row but I won't escape the table.
.------.------.
|  A   |   B  |
'------'------'

What I want to know, is how I can insert normal text right after the table like this:
.------.------.
|  A   |   B  |
'------'------'
Normal text here...

What I usually do is:
1. Select the whole table
2. Cut
3. Insert plenty of new lines
4. Paste my table above empty lines
5. Click on one empty line below the table
6. Insert my normal text.

I also encounter this issue with Evernote.

A:

In Microsoft Word:
Click somewhere in the last row of the table and press the right arrow on your keyboard until the cursor moves outside the table:

Now, instead of pressing Enter, hold the Shift key and press Enter. This will create a line break below the table instead of a new table row.


Q:

Unemployed person applying for UK visa

I live with my mom here in the Philippines. She owns a sari sari store and shes a pensioner. She pays me monthly. And I don't have a bank account as a proof of my financial status.My sister and her husband want me to visit them in the UK since she's going to have a baby and she really needs someone to be with her since my brother in law is working. My brother in law would like to sponsor my trip. What documents will I comply since I don't have a proof of employment?
And what to do to prove that I'm going to the Philippines after my visit for 6 months in the UK.   Surely, I have to return home since my 74 mom needs me. Will making a letter help to prove that I will go back home after my visit to the UK?

A:

You have no official income, and would like to get a visa to come to UK to stay for six month, and asking which documents need to be submitted.
Unfortunately, in my opinion, no document you can submit in those circumstances would qualify you for a 6 month stay (but see below).
First, for UK it seems that good financial standing of a potential visitor is one of the most important criteria to receive the visa (unlike USA, where past travel history seems to be more important). You have no official income and can leave for six months, which means to ECO that you have really no real ties to Philippines. The logic is that people with ties to the country (family, job, weddings to attend, studies to finish) can't really leave for six months, and in your situation you are more likely to overstay. A promise from you not to overstay is unfortunately useless. Please read this excellent answer of why bank statements are asked for - it covers your case too.
Second, considering that you have no resources of your own and totally depend on sponsor family, the potential for you to end up being abused (for example forced to work illegally) is high. This is not taken lightly, and it is another concern you need to overcome.
So the only way I could see it possibly working is if your sister's husband is really, really rich (not just "doing well" - we're talking a millionaire here). In this case it would be relatively easy to overcome a presumption you're coming as a free babysitter - especially if he provides support document which confirms that he already retained a babysitter agency. Then he should be able to find a solicitor which would help to prepare your application - this is also expensive and thus would serve as further evidence you are not coming to earn money illegally. In this case you have some chances - but still no guarantee.
Unless this is the case, I would recommend not to apply. This may sound harsh, but if you apply and are refused now, you will have more difficulty applying later, even if your circumstances improve.


Q:

cin keyword not working in text editor

I'm using the scite text editor (I cannot make use of any IDE or compiler since I'm required to also utilize Makefiles which is only possible if I use some sort of text editor) for all of my coding in c++. However, I'm consistently facing the same challenge; the text editor (I've attempted this on multiple ones including codepad and sublime text) isn't reading any input from the keyboard. Here is the source code:
#include <iostream>
#include <iomanip>
using namespace std;

const int SIZE_OF_ARRAY = 5;

int main(){
int x, y;
int counter = 0;
int elements[SIZE_OF_ARRAY];
cout << "Please enter a number ";
cin >> x;
cin.ignore();
cout << "Please enter a choice ";
cin >> y;
if(y == 1){
 for(int i = 0; i < SIZE_OF_ARRAY; i++)
  elements[i] = -1*SIZE_OF_ARRAY + x;

 for(int j = 0; j < SIZE_OF_ARRAY; j++)
  cout << elements[j] << " ";
}

 else if(y == 2){
  for(int i = 0; i < SIZE_OF_ARRAY; i++){
   if(i == 0)
    elements[i] = -1*x;
   else{
    elements[i] = elements[i-1] + 1;
   }
}

for(int j = 0; j < SIZE_OF_ARRAY; j++)
 cout << elements[j] << " ";
}

else if(y == 3){
 for(int i = 0; i < SIZE_OF_ARRAY; i++){
  counter++;
  elements[i] = 7*x*counter;
 }

for(int j = 0; j < SIZE_OF_ARRAY; j++)
 cout << elements[j] << " ";
}
}

The program is supposed to take as an input any number from the user and, depending on a numeric choice (between one and three) entered by the user, manipulate the value first entered somehow.
Choice one (User picks first choice)
The program negates the size of the array and adds the number which the user first entered and fills the array with the resulting value.
Choice Two (User picks second choice)
The program negates the number entered by the user, places this in the first array location then each successive element is added one unit more than the previous one.
Choice Three (User picks third choice)
Fills the array with the first five multiples of seven. Then shifts each number by a factor equivalent to the number the user had first entered.
I've ran it on an IDE (Codeblocks) and it works perfectly well. However, on any text editor, the 'cout' statements are printed with the variables x and y taken to each be equal to zero rather than being set to the value entered from the keyboard. It doesn't even allow any keyboard input. Any answer regarding how I can fix this would be immensely appreciated.

A:

Hoosain, continuing from the comments above, when you use an IDE, you must configure the path to your compiler as well as all compiler options you wish to use, and the location for the resulting executable and object files, etc. When you used CodeBlocks on windows, you essentially got lucky that CodeBlocks will automatically detect whether MinGW is installed and set its compiler configuration to allow you to build and run your code without you having to configure the compiler details. Geany is another editor that does a good job auto-detecting and using MinGW.
For the remaining IDE's it is up to you to configure them to find and use the compiler you have installed (MinGW), as well as configuring all desired compiler options (at minimum enable compiler warning with -Wall -Wextra).
That is where new programmers who have only used an IDE configured for them run into problems... Before you can tell an IDE where your compiler is located and which compiler options you want to use, you have to know where you compiler is located and understand what minimum set of compiler options you should use.
The way you learn to use a compiler is with the good old command line. (yep, that's cmd.exe on windows, often labeled as the "DOS Prompt" in earlier versions) An IDE is just a front-end to your compiler that executes the same commands you can simply enter on the command line to compile your program.
Learning how to use your compiler will save you an incredible amount of time when learning to code. You can simply open a command prompt and compile any file you wish, without setting up a project, etc.. When learning to code, trying to shoehorn small examples into an IDE is much more time consuming and often more trouble than it is worth. Rather than worry how to use an IDE, focus on "how to use your compiler" first.
Since you have MinGW installed on windows, all you have to do to be able to compile from the command prompt is add the path to the MinGW bin directory to your User Environment. You do that by adding the PATH as an Environment Variable here:
Start Menu-> (rt-click on Computer)-> Properties->
Advanced System Settings-> (Advanced tab)-> Environment Variables

In the Top window (your user variables), click to add (or edit) the PATH "Variable name". Generally, if you installed MinGW in the default location, you simply add the path as the "Variable value":
c:\MinGW\bin;c:\MinGW\mingw32\bin

(verify the path on your computer)
(note: windows separates path components by the semi-colon, so if there is already a PATH variable set, just add a semi-colon between what is there and what you add. Also if you already have a command prompt open, you must close it and open it again for the new path to take effect) Just open Start Menu-> Accessories-> Command Prompt (you can rt-click on the icon (top-left) and choose Properties to set the font (recommend Lucida Console 12) and height/width)
Now you have configured your command prompt to allow you to compile any file at any location within your filesystem. For example, I tested with the code you posted (I modified it to add prompts for the information). Compiling it is a piece of cake. I keep my executables in a bin directory to keep sources and binaries separate.
I named your file array_get.cpp.
Compile
Then just enter the normal g++ compiler command, and at minimum use -Wall -Wextra options to enable compiler warnings (you can add -pedantic and whatever additional warnings you want, I would recommend at least adding -Wshadow so your compiler will warn on any variables you declare in multiple scopes that could conflict). The -o option allows you to specify the location of the executable (I just use a separate bin directory as explained above). So to compile and link your code into bin\array_get.exe all I have to enter is:
C:\Users\david\Documents>g++ -Wall -Wextra -o bin\array_get array_get.cpp

(do not accept code until it compiles without warning -- read any warning (it gives line of problem), understand what it is telling you, and go fix it)
Example Use/Output
C:\Users\david\Documents>bin\array_get.exe
Please enter a number: 21
Please enter a choice (1-3): 3
147 294 441 588 735

That's it. Since MinGW uses gcc, the compiler commands you use on windows are the exact same you would use in Linux, so learning to compile from the command line pays double-benefit.
Now you have the luxury of using any text-editor to edit your code while you have the command prompt simply and easily re-compile as you wish until your code is correct. No project dialogs, no mess of a different folder for every file, just the freedom to compile any file you wish -- right from the command line. (I actually separate my sources in directory by type, e.g. c, cpp), you find what works best for your. I also use a simple bat file that takes the exename and source.cpp names as arguments and then compiles with the options I set -- it just cuts down on typing :)
Further, since you now where your compiler is located, and which options to use, you can open the Settings window on any IDE and set the appropriate compiler command and compiler options to allow the IDE compile your code for you.  Give it a try, and let me know if you have further questions.


Q:

Multiple Language Website PHP

I want to make my PHP website into a multiple language website, with exactly two languages (English, Turkish).
At the top of the web page, there are two icons, one for English and the other for Turkish. When a user clicks on Turkish icon how can I detect that Turkish is selected?

How can I do that?
I have two files for languages,  one for English language and then another one for Turkish.
$arrLang['alert_admin_email_wrong']='kullanci email yanliştır '
$arrLang['alert_admin_email_wrong']='your email is wrong  '

I must use session or cookies for this problem

A:

The easiest way to do that is to create an cookie when the user clicks on the wanted language.
As for the array i would split it per language
$arrLang['en']['alert_admin_email_wrong'] = 'text here';
$arrLang['tr']['alert_admin_email_wrong'] = 'text here turkish';

As for language selection would do this on the webpage
EnglishTurkish

On the language selection page :
$defaultLanguage = isset($_COOKIE['lang']) ? $_COOKIE['lang'] : 'en'; //default to english language
if(isset($_GET['langSelect'])){
    //allow only 2 for now ( english / turkish)
    $langForSelection = "";
    switch($_GET['langSelect']){
        case 'en':
        $langForSelection = 'en';
        break;
        case 'tr':
        $langForSelection = 'tr';
        break;
        default:
        break;
    }
    if(isset($langForSelection)){
        setcookie('lang',$langForSelection,time()+24*7*60*60);//set cookie to expire in 7 days
    }
}

After to show the variables
echo $arrLang[$defaultLanguage]['alert_admin_email_wrong'];


Q:

Angular input event is not fired by setting the value with the model

I use a input field which calls a method when the value in it changes. But when I set the value in the input field by the ngModel (not typed by hand) the "value changed" event of the input field will not be fired.
Input field:
<div>
  <input type="text" id="orderNumberFilter" (input)="updateOrderNumberFilter($event)" [(ngModel)]="orderNumberFilterValue">
</div>

component:
public updateData(evt: any): void {
  .finally(() => {
    this.orderNumberFilterValue = "test"
  })
  .subscribe(
    //get data from backend
  });
}

public updateOrderNumberFilter(evt: any): void {

 //do stuff with the event

}

A:

And it will not be fired, because input event will be fired only during user interaction.
You can work with Reactive Forms instead of Template Driven Forms and using its valueChanges function you can listen to changes of the value of the controls.
Another answer about Reactive Form value changes you can read here
UPDATED
You can declare your function to get the value of the input
public updateOrderNumberFilter(value: any): void {

}

In the markup attach it with $event.target.value
<input type="text" id="orderNumberFilter" (input)="updateOrderNumberFilter($event.target.value)" [(ngModel)]="orderNumberFilterValue">

and also call it in the finally and pass the value.


Q:

How do I fetch translated strings?

I have a progressively decoupled Reactjs application running on top of Drupal. Its a multilingual application.
I need to fetch the translated strings from the Drupal itself and handle the translations editor and everything in Drupal itself, rather than maintaining a separate translation system for react.
How is it possible? A simple Drupal.t() doesn't work. I checked.
Any examples I can refer?

A:

Drupal.t() works in this case. Have to to compile the javascript and clear the Drupal cache in order for strings to appear.
For props way:
On get_sample_props():
function getsampleprops() {
  return ['sampleval' => t('Hello World!!!')];
}

On the controller,
$build = [
  '#theme' => 'sample_react',
  '#props' => json_encode($this->get_sample_props()),
];

On the template, I did:

On the React side, I used
$val = this.props.labels.sampleval;

Volia, its done. Its bit inconvenient, but work gets done.


Q:

Why there are so many tags without any question related to them?

Why do these tags exist if they have no associated questions?
Tags: reinterviewing, self-employment, singapore, supplies, untagged, visa, workers-compensation, workplace-routine, phone, quitting, promises, outside-of-workplace, paperwork, multicultural, mexico, masters, library, it-departments, it-industry, inmigration, job-title, jury-duty, customer-relations, demotion, departments, germany, hardware, health, illness, hours, exercise, exit-interview, charity, cliches, assessment, alertness, banking, batna, accommodations, complaint, boss, bosses, headhunter, recruiters and reference.
In my opinion, some of the tags seem like duplicates (like bosses and boss), some seem off topic (like hardware, mexico, singapore, germany), some too specific (like batna) and finally, google told me that inmigration should be immigration.

A:

Let's categorize these tags so that it's easier to identify areas that might need action...
Tags with just 1 question:
Ideally, we should determine if these tags are needed. If they don't have any value, they can be removed and replaced with a better tag. But if the tag is something that could come up again or that could help people find this information, then the tag should remain.

reinterviewing
self-employment
singapore
supplies
visa
workers-compensation
workplace-routine
phone
quitting
promises
outside-of-workplace
paperwork
multicultural
mexico
masters
library
it-departments
it-industry
immigration (fixed spelling)
jury-duty
customer-relations
demotion
departments
germany
hardware
health
hours
exercise
exit-interview
charity
cliches
assessment
alertness
banking
batna  (Possibly meaning Best Alternative to a Negotiated Agreement )
accommodations
complaint

Tags that are synonyms of other tags:
These tags are synonyms of other tags. This means that the question can be tagged with either tag and still show up in the same tag search. For instance, searching for the tag "boss" or "bosses" shows me the same 122 results as if I searched for the "management" tag.
Tag synonyms are often used when different people try to use different tags that really identify the same groups of questions.

Boss and Bosses are a synonym of Management. 122 questions hold this tag.
job-title is a synonym of title. There are 13 questions with these tags.
illness and sickness are synonyms. There are 5 questions with these tags.
headhunter and recruiter are synonyms of recruitment. There are 58 questions with this tag.
reference is a synonym of references. There are 22 questions with this tag.

Untagged Questions:

"untagged" is a special tag that is used on questions that do not have a tag. Ideally, we should find tags that apply to these posts. Currently, there is only 1 question that has no tags.


Q:

JQuery/Jscript string manipulation with varying lengths

I wrote a very basic jquery script to obtain the src attribute from my img elements. Long story short, based on the number contained in the src attribute of my thumbnails, the code then uses that same id number to fetch the corresponding main image:
sample thumb src value: catalog/p1-t1.png | where p = piece and 1 = id, t1 = thumb 1
sample mainpic src value: catalog/p1-1.png | where p = piece and 1 = id, 2nd 1 = main pic for thumb 1
It all worked nicely up until single digit numbers became double digits and thus, using something like:
$string = $string.substring(12,13);

ceased to work (obvious yes).
I want to get from my thumb's 'catalog/p1-t1.png' src value the '1' after the 't', whether its t1 or t33 or t999.
Thanks in advance
G.Campos

A:

A wild Regular Expression appears!
var string = 'catalog/p1-t666.png',
    re = /\/p(\d+)-t(\d+)/
    result = re.exec(string),
    piece = result[1], // 1
    thumb = result[2]; // 666

Oh and later a slightly less wild demo appears, I guess.


Q:

Object Reference Handling in C#

I was working on a c# program today and ended up having to chase a bug for quite some time.
I was trying to make a copy of an object change a few fields and send it on as well as the original
for example
Function(Object A)
{
    Object B = new Object();
    Object B = A;

    B.foo = "bar";

    Send(A);

    Send(B);
}

My program started treating A and B as the same object meaning that any changes to A would also change B and vise versa.
I know that the Object A and B are both referencing the same memory.
Is there a short hand way to ensure the line Object B = A references new memory thus creating different objects. Or is the only way to create a copy constructor in my Object and create B with Object B = new Object(A)
eg:
Object(Object a){
   foo = a.foo;
   ...
}

Basically i just what to know more about how C# handles object references and memory allocations. Big subject i know.

A:

You can call the protected MemberwiseClone method, which will make a shallow copy of all the object. If you can modify the class of the object, you can even create a public Clone method that delegates to this. And if you're willing to use structs instead of classes, any assignment will create a copy. This is because structs are value types, and assigning one value type variable to another creates a copy.
With regard to MemberwiseClone, note the part where I said "shallow." Value type fields will be copied, but reference type fields will still refer to the same underlying objects.


Q:

CqlEngine - sync_table() KeyError: 'cqlengine'

I am just starting to work with Cassandra in python using cqlengine.
I tried following this link and tried ran this script:
from cqlengine import columns
from cqlengine import Model
from cqlengine import connection

from cqlengine.management import sync_table

import uuid

class ExampleModel(Model):
    example_id = columns.UUID(primary_key=True, default=uuid.uuid4)
    example_type = columns.Integer(index=True)
    created_at = columns.DateTime()
    description = columns.Text(required=False)

connection.setup(['127.0.0.1'], 'cqlengine')

sync_table(ExampleModel)

But it throws up this error:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/zopper/Desktop/django-cassandra/local/lib/python2.7/site-packages/cqlengine/management.py", line 92, in sync_table
    keyspace = cluster.metadata.keyspaces[ks_name]
KeyError: 'cqlengine'

My pip freeze is:
Django==1.7.3
argparse==1.2.1
blist==1.3.6
cassandra-driver==2.1.3
cqlengine==0.21.0
django-cassandra-engine==0.2.1
djangotoolbox==1.6.2
futures==2.2.0
six==1.9.0
wsgiref==0.1.2

Please help me understand and solve this issue.
Thanks.

A:

This was overlooked on my end - I'm fixing it now.  create_missing_keyspace would rarely "do the right thing", and it's very difficult and time consuming to fix a keyspace created with the wrong parameters.  You must now explicitly create a keyspace with the parameters you want.


Q:

How to Make Separate Space in VB.Net

How to make a separate space?
Example: I want make ASCII to Hex

Hello - 48656C6C6F

But I want it formatted like this

Hello - 48 65 6C 6C 6F

A:

You can use Encoding.ASCII and the BitConverter class.
Dim asciiBytes = Encoding.ASCII.GetBytes("Hello")
Dim hex = BitConverter.ToString(asciiBytes).Replace("-", " ")

hex is now 48 65 6C 6C 6F

A:

Or on one line
Dim hex = String.Join(" ", "Hello" _
    .Select(Function(c) Convert.ToByte(c).ToString("x2")))

without the Replace.

If you want to show the high bytes (because each Char is actually two Bytes because strings are Unicode)
Dim hex = String.Join(" ", "Hello" _
    .SelectMany(Function(c) BitConvertor.GetBytes(c)) _
    .Select(Function(b) b.ToString("x2")))


Q:

Stash Merge 2 Repositories with complete History

I want to merge 2 Repositories in the Same Project in Stash. The complete History should be merged too. Is there any way to do this?

A:

Stash developer here. This is really a Git question. Depending on how you want/need the repository merged I would recommend you first check out Git Subtree:
http://blogs.atlassian.com/2013/05/alternatives-to-git-submodule-git-subtree/
Alternatively you can just run git pull ../other_git_dir in your first repository, and that will fetch all the commits on the default/current branch (eg. master) into your second repository. Note that this only works for one branch at at time. Some more reading:
http://scottwb.com/blog/2012/07/14/merge-git-repositories-and-preseve-commit-history/
If you're actually talking about creating a pull request then you can't (currently) do this across two unrelated (eg. non forked) repositories in Stash. You could however pull the history from one repository into another (as above) and then create the pull request that way.


Q:

Playing the man, not the board

A recent thread used this term. Which notable GMs are known to have 'played the man'?
This is interesting because hindsight and computers are wonderful things. They should allow us to pick out "blunders" that didn't lead to losses.
Is chess a game against a person? If so, why do we look down our noses when we hear "playing the man"?

A:

Being the one who said that, it's probably fitting I answer.
It all depends on your definition of 'playing the man and not the board.' If by that you mean ignoring your opponent's moves and the demands of the position, gambling on an unsound attack, no good player does that, certainly no Grandmaster.
OTOH, every player has preferences for typical positions, and in preparing for a game against a known opponent, most top players will 'slant' their work a little, aiming to get positions they're comfortable playing that might be uncomfortable for their opponents.
The classic case of this has got to be Kramnik's revival of the Berlin Defense against Kasparov in their world title match. Kramnik knew Kasparov well, knew he didn't like queenless middlegames with lots of maneuvering. So he added the Berlin to his arsenal for that match, and he won.
Note the subtlety, though. Kramnik didn't play bad moves; the Berlin is a perfectly playable defense that only fell out of favor because it tended to draw far more than other lines.
In my coaching I've run into too many youths who use 'playing the player, not the board' as an excuse to play "hope chess," making bad moves to generate a silly attack that in reality has no hope of succeeding against anyone with more than two synapses firing.
My advice to them has always been: "Learn how to play the board, first. Then, when you're good enough to understand what positions you're comfortable in and how to tell when someone else isn't, and only then, start to consider playing the player. Because only then will you be able to do so with any real hope of success."


Q:

DropDownListFor() help please

I've been farting around with this HTML Helper for awhile now, following all sorts of examples which in theory accomplish the same end result.  However, I can't seem to produce the end result...
Maybe someone can see what I'm doing wrong before I go back to iterating out select options with a foreach.  It would be nice to lock in how this helper works, less code than a select with a foreach().  Thanks in advance.
Edit controller;
public ActionResult Edit(string id)
    {
        if (id != "")
        {

            UserViewModel user = (from u in db.Users.Where(u => u.Id.Equals(id))
                                  from ur in u.Roles
                                  join r in db.Roles on ur.RoleId equals r.Id

                                  select new UserViewModel
                                  {
                                      UserId = u.Id,
                                      DisplayName = u.DisplayName,
                                      Role = r.Name,
                                      RoleId = r.Id

                                  }
                       ).FirstOrDefault();

            //Select List items for select list
            var roles = db.Roles.Select(r => new SelectListItem { Value = r.Id, Text = r.Name });

            //select list with selected value
            user.Roles = new SelectList(roles,"Value", "Text", user.RoleId);

            return View(user);
        }
        return View();
    }

View;

   @Html.LabelFor(model => model.Role, htmlAttributes: new { @class = "control-label col-md-2" })

      @Html.DropDownListFor(model => model.Role, Model.Roles, null, new { @class = "form-control" })

      @Html.ValidationMessageFor(model => model.Role, "", new { @class = "text-danger" })

A:

Your code
var roles = db.Roles.Select(r => new SelectListItem { Value = r.Id, Text = r.Name });

creates IEnumerable<SelectListItem>.
user.Roles = new SelectList(roles,"Value", "Text", user.RoleId);

just creates another identical IEnumerable<SelectListItem> from it so its just pointless extra overhead and since your binding to a property in your model, the last paramater (user.RoleId) is ignored and also pointless
It should be just
user.Roles = db.Roles.Select(r => new SelectListItem { Value = r.Id, Text = r.Name });

When your create this SelectList you setting the value to the Id property of Role but you then attempting to bind to the Role property of UserViewModel instead of the RoleId property. Because the value of Role will not match one of the option values the first option in the dropdownlist will always be selected (because something has to be).
Change the code in your view to
@Html.DropDownListFor(model => model.RoleId, Model.Roles, null, new { @class = "form-control" })

If the value of RoleId matches one of the option values, then it will be selected.
Side note: your Role property in your view model seems unnecessary, as does the need to create a join to the Roles table in your query.


Q:

Embedded C: Registers Access

Suppose we want to write at address say 0xc000, we can define a macro in C as:
#define LCDCW1_ADDR       0xc000
#define READ_LCDCW1()     (*(volatile uint32_t *)LCDCW1_ADDR)
#define WRITE_LCDCW1(val) ((*(volatile uint32_t *)LCDCW1_ADDR) = (val))

My question is that when using any micro-controller, consider an example MSP430, P1OUT register address is 0x0021.
But when we use P1OUT=0xFFFF; // it assigns P1OUT a value 0xFFFF.
My question is how does it write to that address e.g. in this case 0x0021.
The IDE is IAR. I found in header msp430g2553.h below definition:
#define P1OUT_              (0x0021u)  /* Port 1 Output */
DEFC(   P1OUT             , P1OUT_)

I suppose it is defining the address, but where are the other macros to write or read.
Could anyone please explain the flow that how P1OUT writes at that particular address location? Also do let me know what does u mean in 0x0021u ?
Thanks

So far the details I have found are :
in msp430g2553.h
#ifdef __IAR_SYSTEMS_ICC__
#include "in430.h"
#pragma language=extended

#define DEFC(name, address) __no_init volatile unsigned char name @ address;
#define DEFW(name, address) __no_init volatile unsigned short name @ address;
#define DEFXC  volatile unsigned char
#define DEFXW  volatile unsigned short

#endif  /* __IAR_SYSTEMS_ICC__  */

#ifdef __IAR_SYSTEMS_ASM__
#define DEFC(name, address) sfrb name = address;
#define DEFW(name, address) sfrw name = address;

#endif /* __IAR_SYSTEMS_ASM__*/

#define P1OUT_              (0x0021u)  /* Port 1 Output */
DEFC(   P1OUT             , P1OUT_)

The io430g2553.h says
__no_init volatile union
{
  unsigned char P1OUT;   /* Port 1 Output */

  struct
  {
    unsigned char P0              : 1; /*  */
    unsigned char P1              : 1; /*  */
    unsigned char P2              : 1; /*  */
    unsigned char P3              : 1; /*  */
    unsigned char P4              : 1; /*  */
    unsigned char P5              : 1; /*  */
    unsigned char P6              : 1; /*  */
    unsigned char P7              : 1; /*  */
  }P1OUT_bit;
} @0x0021;

Can some one explain what the above definition does? The details I found in MSP430 IAR C/C++ Compiler:
Example of using __write and __read
The code in the following examples use memory-mapped I/O to write to an LCD
display:
__no_init volatile unsigned char LCD_IO @ address;
size_t __write(int Handle, const unsigned char * Buf,
size_t Bufsize)
{
size_t nChars = 0;
/* Check for stdout and stderr
(only necessary if file descriptors are enabled.) */
if (Handle != 1 && Handle != 2)
{
return -1;
}
for (/*Empty */; Bufsize > 0; --Bufsize)
{
LCD_IO = * Buf++;
++nChars;
}
return nChars;
}
The code in the following example uses memory-mapped I/O to read from a keyboard:
__no_init volatile unsigned char KB_IO @ 0xD2;
size_t __read(int Handle, unsigned char *Buf, size_t BufSize)
{
size_t nChars = 0;
/* Check for stdin
(only necessary if FILE descriptors are enabled) */
if (Handle != 0)
{
return -1;
}
for (/*Empty*/; BufSize > 0; --BufSize)
{
unsigned char c = KB_IO;
if (c == 0)
break;
*Buf++ = c;
++nChars;
}
return nChars;
}

Does any one know?

A:

This is "how does the compiler generate the code from what I've written", and only the compiler writers will actually be able to answer that for you.
Clearly, there are several non standard C components in the code above __no_init, the use of @, etc. In my reading of this, it tells the compiler that "this is a HW port, that provides an unsigned char, and it's address is 0xd2". The compiler will produce the right kind of instructions to read and write such a port - exactly how that works depends on the compiler, the processor that the compiler is producing code for, etc.
The P10out structure defines bitfields, which is part of the C standard. Google is your friend here.


Q:

How do I apply a patch from gnus to a git repo?

I've got an email with a dozen .patch files attached in gnus. I can save them to e.g. ~/Downloads and then apply them with magit-patch-apply-popup, but considering that I've got gnus open on the left (and I can open the patch in its own buffer by putting my cursor over it and pressing c) and the magit summary buffer on the right, I would think that I could just apply the patch right there. But I cannot figure out how to do this.

A:

Found the answer via this blog post: Use Gnus to apply patch sent by git send-email.
Basically, I put point on the email in the gnus Summary buffer, then do O m and save the email somewhere. Then in magit I do w m and it will apply the patch.
Unfortunately for me this lost some commit info because the patches were sent from Gmail which formats patches incorrectly. So I just saved all the attached patches into the root of the git repo, selected them all (C-SPC) in the magit buffer, then did w w to apply them all individually. Then deleted the .patch files.


Q:

Can an interface have more than one IPv6 link-local, ULA, public address?

In Contiki OS,
Can a node have more than one IPv6 link-local address?
Can a node have more than one IPv6 Unique Link Address (ULA)?
Can a node have more than one public IPv6 address?

A:

Yes, yes and yes.
Having multiple addresses on one interface is quite common with IPv6. When using SLAAC your device will probably configure multiple addresses per prefix. Multiple prefixes may be advertised in the Router Advertisement, for example both a normal prefix and a ULA prefix. You can of course also configure addresses manually.
Operating system commonly configure one address per prefix that is stable and doesn't change over time, and then regularly add some temporary addresses that will expire after a while. Those temporary addresses are usually used for outgoing connections so the server you are connecting to can't trace you based on your address.
Although usually an interface only has one link-local address, you can have multiple if you want.
PS: to keep this relevant to StackOverflow, please indicate the programming issue you are trying to solve with this information.


Q:

When compiling the Linux Kernel, what is the purpose of `make randconfig`?

In what scenario would one want to use this tool? It would seem to make less work, but the upshot is, of course, that you don't know what configuration options will be used for your kernel, which could very well mess things up.

A:

The messing things up is the point.
It's used for what's called "fuzz testing" - making sure the kernel config can't be put in a state where the kernel can't compile. Rather than rely on pure human ingenuity to break things, they enlist the help of entropy.


Q:

Ui thread blocked but only on 1st call to Webclient asynch methods

Per a client's request I have written a communication class that inherits from webclient. They want to be able to "Pass in a custom windows form as a progress bar" rather than that I created an interface that implements 3 properties. Anyway the problem I am having is the app starts and i click the start button so to speak and the first time i do this the ui thread is frozen, after a few seconds it unfreezes and the progress bar and data begin coming down.
After this initial freeze though , any subsequent presses of the start button work perfectly and do not block the thread any ideas?
Here are the relevant pieces of code from form 1
private void btnSubmit_Click(object sender, EventArgs e)
    {
        txtResponse.Text = "";
        progressForm = new ProgressFormTest();
        myCommunication = new CommunicationClient(progressForm);
        myCommunication.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_RequestComplete);
        // myCommunication.DownloadProgressChanged += new DownloadProgressChangedEventHandler(wc_DownloadProgressChanged);
        myCommunication.Timeout += new EventHandler(wc_TimeOut);
        myCommunication.Cancelled += new EventHandler(myCommunication_Cancelled);

        progressForm.Show();
        myCommunication.TimeoutValue = (int)numConnectionTimeout.Value * 1000;

        myCommunication.DownloadStringAsync(new Uri(txtUrl.Text));

    }

Here is the communication class
    public class CommunicationClient:WebClient
    {
    private int step = 1000;
    private long bytesReceived;
    private long bytesSent;
    private Status status;
    private System.Timers.Timer _timer;
    private IProgress myProgressForm;

    /// <summary>
    /// Sets the timeout value in milliseconds
    /// </summary>
    public int TimeoutValue { get; set; }
    public int TimeElapsed { get; set; }
    public long BytesReceived
    {
        get
        {
            return bytesReceived;
        }
    }
    public long BytesSent
    {
        get
        {
            return bytesSent;
        }
    }

    public event EventHandler Timeout;
    public event EventHandler Cancelled;

    public CommunicationClient(IProgress progressForm)
    {
        myProgressForm = progressForm;
        _timer = new System.Timers.Timer(step);
        _timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
    }

    protected override void OnDownloadStringCompleted(DownloadStringCompletedEventArgs e)
    {
        _timer.Stop();
        if (status == Status.Completed)
        {
            myProgressForm.PercentComplete = 100;
            base.OnDownloadStringCompleted(e);
        }
    }

    protected override void OnDownloadProgressChanged(DownloadProgressChangedEventArgs e)
    {
        bytesReceived = e.BytesReceived;
        myProgressForm.BytesReceived = bytesReceived;
        if (e.TotalBytesToReceive == -1)
            myProgressForm.PercentComplete = calculateFakePercentage();
        else
            myProgressForm.PercentComplete = e.ProgressPercentage;
        base.OnDownloadProgressChanged(e);
    }

    protected virtual void OnTimeout(EventArgs e)
    {
        if (Timeout != null)
        {
            CancelAsync();
            this.Dispose();
            Timeout(this, e);
        }
    }

    protected virtual void OnCancelled(EventArgs e)
    {
        if (Cancelled != null)
        {
            this.Dispose();
            Cancelled(this, e);
        }
    }

    /// <summary>
    /// Cancels a pending asynchronous operation and raises the Cancelled Event
    /// </summary>
    /// <param name="Event">Set to true to raise the event</param>
    public void  CancelAsync(bool Event)
    {
        CancelAsync();
        if (Event)
        {
            status = Status.Cancelled;
            OnCancelled(new EventArgs());
        }
    }

    private void initialize()
    {
        status = Status.Completed;
        TimeElapsed = 0;
        _timer.Start();
    }

    new public void DownloadStringAsync(Uri url)
    {
        initialize();
        base.DownloadStringAsync(url);
    }

    private void timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        TimeElapsed += step;

        if (TimeElapsed >= TimeoutValue)
        {
            _timer.Stop();
            status = Status.Timeout;
            OnTimeout(e);
        }
    }

    //used when the website in question doesnt provide the content length
    private int calculateFakePercentage()
    {
        return  (int)bytesReceived * 100 / 60000 ;
    }
}

And here is the simple Interface IProgressForm
public interface IProgress
{
    int PercentComplete
    {
        get;
        set;
    }
    long BytesReceived
    {
        get;
        set;
    }
    long BytesSent
    {
        get;
        set;
    }
}

A:

Fixed it , I set the Proxy property from the webclient class to null and that seemed to fix it


Q:

Search for field name in access table then update relevant fields names with values delphi 7

I have an Access database table named ReceiptTable with the following field names: item name, buying price, selling price, goods total, cash, change. I am using an Adoquery and datasource to connect to the access database. When I want to update records to receiptTable, I use the following code to locate an item name from the database then update all the records with similar item name in the database with  the values from edit box field values:
procedure TReceiptForm.BitBtn1Click(Sender: TObject);
begin
with ADOQuery1 do
ADOQuery1.Open;
ADOQuery1.Locate('item name',Edit1.Text,[]) ;
ADOQuery1.edit;
ADOQuery1.FieldValues['goods total']:=edit3.Text;
ADOQuery1.FieldValues['cash']:=edit4.Text;
ADOQuery1.FieldValues['change']:=edit5.Text;
ADOQuery1.Post;
end;

The problem I have is that only one row with the item name is updated but the other rows with similar item name are not updated. What code should I add above so that all the rows which have similar item names are updated with values from edit boxes?

A:

This simple code answers your question:
procedure TReceiptForm.BitBtn1Click(Sender: TObject);
var
    itemname, goodstotal, cash, change: string;
begin
    // Execute query
    try
        ADOQuery1.Open;
    except
        on E: Exception do begin
            ShowMessage(E.Message);
            Exit;
        end{on};
    end{try};
    // Values
    itemname   := Edit1.Text;
    goodstotal := Edit3.Text;
    cash       := Edit4.Text;
    change     := Edit5.Text;
    // Find first matching record, then go to the end of resultset.
    try
        ADOQuery1.DisableControls;
        if ADOQuery1.Locate('item name', itemname, []) then begin
            while not ADOQuery1.Eof do begin
                if ADOQuery1.FieldByName('item name').AsString = itemname then begin
                    ADOQuery1.Edit;
                    ADOQuery1.FieldValues['goods total'] := goodstotal;
                    ADOQuery1.FieldValues['cash']        := cash;
                    ADOQuery1.FieldValues['change']      := change;
                    ADOQuery1.Post;
                end{if};
                ADOQuery1.Next;
            end{while};
        end{if};
    finally
        ADOQuery1.EnableControls;
    end{try};
end;

This will work, but you can consider using one SQL statement for updating the table, or
if it is possible order your query by 'item name' and use this:
...
// Find first matching record, then update while next record matches too.
if ADOQuery1.Locate('item name', itemname, []) then begin
    while (not ADOQuery1.Eof) and
          (ADOQuery1.FieldByName('item name').AsString = itemname) do begin
        ADOQuery1.Edit;
        ADOQuery1.FieldValues['goods total'] := goodstotal;
        ADOQuery1.FieldValues['cash']        := cash;
        ADOQuery1.FieldValues['change']      := change;
        ADOQuery1.Post;
        ADOQuery1.Next;
    end{while};
end{if};
...


Q:

field not saved when I change the name attribute of the field form in Yii

when I add the name attribute to a field form in Yii ,  the field content is not saved in DB
the following works,
echo $form->textField($model,'country'); ?>

it generates the html code
<input name="RegistrationForm[country]" id="RegistrationForm_country" type="text" maxlength="50" />

the following does not work,
echo $form->textField($model,'country', array('name'=>'country'); ?>

it generates the html code
<input name="country" id="country" type="text" maxlength="50" />

Any idea?

A:

The field name="RegistrationForm[country]" is required if you are using
$model->attributes = $_POST['RegistrationForm'];

to set the attributes in the controller.
If you want to use a custom name like name="country", you will have to manually set the value of the model yourself:
$model->attributes = $_POST['RegistrationForm'];
$model->country = $_POST['country'];


Q:

JavaScript, jQuery, XML - if statement not executing for unknown reason

I have a 'for' loop which extracts data from an XML document and adds it into some JavaScript objects, each time the loop executes I want it to run a certain function depending on the value of the attribute 'typ' which is being retrieved from the xml.
Currently, the data from the XML is successfully being parsed, which is proven by the first 'alert' you can see which produces the correct value.
However, neither of the 'alert' lines in the 'if' statement lower down are being executed and as a result I cannot test the 'ctyp3' function which is supposed to be called.
Where have I gone wrong?
                      for (j=0; j<arrayIds.length; j++)
                  {
                    $(xml).find("C[ID='" + arrayIds[j] + "']").each(function(){
                        // pass values
                        questions[j] = {
                            typ: $(this).attr('typ'),
                            width: $(this).find("I").attr('wid'),
                            height: $(this).find("I").attr('hei'),
                            x: $(this).find("I").attr('x'),
                            y: $(this).find("I").attr('x'),
                            baC: $(this).find("I").attr('baC'),
                            boC: $(this).find("I").attr('boC'),
                            boW: $(this).find("I").attr('boW')
                        }

                        alert($(this).attr('typ'));

                        if ($(this).attr('typ') == '3')
                        {
                            ctyp3(x,y,width,height,baC);
                            alert('pass');
                        } else {
                            // Add here
                            alert('fail');
                        }
                    });
                  }

EDIT: After your suggestions I commented the ctyp3 function and the if statement proceeded to execute correctly.
Here is the ctyp3 function:
                      function ctyp3(x,y,width,height,baC)
                  {
                      alert('alsdjkfs');
                      document.createElement('rect');
                      this.x = x;
                      this.y = y;
                      this.width = width;
                      this.height = height;
                      this.fillcolor = baC;
                      svgTag.appendChild(this);
                  }

I was attempting to create an object and then a html element, something I have not done before.

A:

The "this" in your ctyp3 function is not going to be what you think it is. You need to assign the result of document.createElement to a variable:
var r = document.createElement('rect');

Then use "r" instead of "this". Similarly, it's not clear what "svgTag" is; if it's not a global variable then you're going to have to pass it to the function explicitly.


Q:

Java Process taking more and more memory

All,
I have a Java Memory Process which starts to take more and more memory with time. To put a Cap on the heap space usage I set -Xmx option to 512M. Slowly over a period of time the Process memory usage reached 2GB.
I have analyzed the code for possible memory leaks using various tools like MAT and YOURKIT and found no such possible leaks in the Java code. The code also makes use of One Native function which looks leak free.
I have the following questions :

Is it possible to cause an upper limit on the total memory a Java Process can use ?
What are the other memory usages of the JVM apart from the Heap ?
Does Linux work on 'Working set' memory model of Windows where a process when put into background releases it's memory.
Even after using -Xmx option with 512M shouldn't the JVM throw an 'Out Of memory' if the heap usage increases. This makes me suspect that the memory is being leaked by something else apart from the Heap space. From the memory dumps it seems that the Heap Memory is not increasing.

thanks for the answer.

A:

How are you measuring memory usage?
Usually there are 3 kinds of memory usage:

VIRT  --  Virtual Memory Size (KiB)
          The  total  amount  of  virtual  memory  used by the task.  It
          includes all code, data and shared libraries plus  pages  that
          have  been swapped out and pages that have been mapped but not
          used.
RES  --  Resident Memory Size (KiB) The non-swapped physical memory a task has used.
SHR  --  Shared Memory Size (KiB) It
simply reflects  memory  that
          could be potentially shared with other processes.

The virtual memory size can become larger (several GB) than what you specified with -Xmx, but this does not do any harm. RES plus SHR is what you should be looking at.
Apart from the heap there is another class of memory usage not affected by -Xmx (permgen). But that is usually capped at a few MB. You might want to read the HotSpot GC Tuning Guide.


Q:

why a pdf document could be not searchable?

I have a pdf document with content in Arabic language and when I try to search inside the document for a specific word, adobe reader returns no results.
it seems a format problem... how can I fix that?
thanks.

A:

There are at least four different ways to get text into a PDF document (in order or likelihood):

Place the text with standard text operators and standard fonts
Place the text with standard text operators with non-standard fonts
Draw one or more images that represent the text
Place the text by manually drawing the glyphs with various PDF graphics commands

Case 1 is typically searchable.
Case 2 is searchable if the font and encoding are sane - if they're not (and this is likely the case for non-Latin fonts) then there is probably no reliable way to map the encoded glyphs back to Unicode (and by the way - PDF is fairly Unicode hostile).
Case 3 is totally unsearchable without knowing more about how the PDF was generated.
Case 4 is totally unsearchable.
That said, all cases cases be read with an OCR engine that understands Arabic.  I understand that the Iris engine does Arabic.


Q:

How to convert Varchar to Int in sql server 2008?

How to convert Varchar to Int in sql server 2008.
i have following code when i tried to run it wont allowed me to convert Varchar to Int.
Select Cast([Column1] as INT)

Column1 is of Varchar(21) NOT NULL type and i wanted to convert it into Int.
actually i am trying to insert Column1 into another table having Field as INT.
can someone please help me to convert this ?

A:

Spaces will not be a problem for cast, however characters like TAB, CR or LF will appear as spaces, will not be trimmed by LTRIM or RTRIM, and will be a problem.
For example try the following:
declare @v1 varchar(21) = '66',
        @v2 varchar(21) = '   66   ',
        @v3 varchar(21) = '66' + char(13) + char(10),
        @v4 varchar(21) = char(9) + '66'

select cast(@v1 as int)   -- ok
select cast(@v2 as int)   -- ok
select cast(@v3 as int)   -- error
select cast(@v4 as int)   -- error

Check your input for these characters and if you find them, use REPLACE to clean up your data.

Per your comment, you can use REPLACE as part of your cast:
select cast(replace(replace(@v3, char(13), ''), char(10), '') as int)

If this is something that will be happening often, it would be better to clean up the data and modify the way the table is populated to remove the CR and LF before it is entered.

A:

you can use convert function :
Select convert(int,[Column1])


Q:

Method is not defined - callObserverMethod

After a forced server update to php5.5 we have been faced with this error below:
Method "addLibrary" is not defined in "Meigee_ThemeOptions_Controller_Observer"

#0 /home/user/website.com/app/code/core/Mage/Core/Model/App.php(1340): Mage::throwException('Method "addLibr...')
#1 /home/user/website.com/app/code/core/Mage/Core/Model/App.php(1317): Mage_Core_Model_App->_callObserverMethod(Object(Meigee_ThemeOptions_Controller_Observer), 'addLibrary', Object(Varien_Event_Observer))
#2 /home/user/website.com/app/Mage.php(447): Mage_Core_Model_App->dispatchEvent('controller_acti...', Array)
#3 /home/user/website.com/app/code/core/Mage/Core/Controller/Varien/Action.php(351): Mage::dispatchEvent('controller_acti...', Array)
#4 /home/user/website.com/app/code/core/Mage/Cms/Helper/Page.php(113): Mage_Core_Controller_Varien_Action->generateLayoutBlocks()
#5 /home/user/website.com/app/code/core/Mage/Cms/Helper/Page.php(52): Mage_Cms_Helper_Page->_renderPage(Object(Mage_Cms_IndexController), 'home')
#6 /home/user/website.com/app/code/core/Mage/Cms/controllers/IndexController.php(45): Mage_Cms_Helper_Page->renderPage(Object(Mage_Cms_IndexController), 'home')
#7 /home/user/website.com/app/code/core/Mage/Core/Controller/Varien/Action.php(419): Mage_Cms_IndexController->indexAction()
#8 /home/user/website.com/app/code/core/Mage/Core/Controller/Varien/Router/Standard.php(250): Mage_Core_Controller_Varien_Action->dispatch('index')
#9 /home/user/website.com/app/code/core/Mage/Core/Controller/Varien/Front.php(176): Mage_Core_Controller_Varien_Router_Standard->match(Object(Mage_Core_Controller_Request_Http))
#10 /home/user/website.com/app/code/core/Mage/Core/Model/App.php(354): Mage_Core_Controller_Varien_Front->dispatch()
#11 /home/user/website.com/app/Mage.php(683): Mage_Core_Model_App->run(Array)
#12 /home/user/website.com/index.php(86): Mage::run('', 'store')
#13 {main}

Obviously it is a theme issue, but what should I be looking at to fix it?
EDIT: In response to the below answer, I can't access admin section either, I get the same error. Here is the relevant config.xml file in case that helps.
<?xml version="1.0"?>
<config>
    <modules>
        <Meigee_ThemeOptions>
            <version>1.0.0</version>
            <depends>

            </depends>
        </Meigee_ThemeOptions>
    </modules>
    <global>
        <models>

            <ThemeOptions>
                <class>Meigee_ThemeOptions_Model</class>
            </ThemeOptions>

        </models>
        <events>
          <adminhtml_controller_action_predispatch_start>
            <observers>
              <Meigee_ThemeOptions_observer>
                <type>singleton</type>

                <class>Meigee_ThemeOptions_Controller_Observer</class>
                <method>overrideTheme</method>
              </Meigee_ThemeOptions_observer>
            </observers>
          </adminhtml_controller_action_predispatch_start>
        <controller_action_layout_generate_blocks_after>
            <observers>
                <ibanner_layout_generate_observer>
                    <type>singleton</type>
                    <class>Meigee_ThemeOptions_Controller_Observer</class>
                    <method>addLibrary</method>
                </ibanner_layout_generate_observer>
            </observers>
        </controller_action_layout_generate_blocks_after>
        </events>
        <helpers>
            <ThemeOptions>
                <class>Meigee_ThemeOptions_Helper</class>
            </ThemeOptions>
        </helpers>
        <extraconfig />
        <blocks>
            <meigee_themeoptions>
                    <class>Meigee_ThemeOptions_Block</class>
            </meigee_themeoptions>
            <meigee_general><class>Meigee_ThemeOptions_Block</class></meigee_general>
            <meigee_productpage><class>Meigee_ThemeOptions_Block</class></meigee_productpage>
            <meigee_sidebar><class>Meigee_ThemeOptions_Block</class></meigee_sidebar>
            <themeoptions>
                    <class>Meigee_ThemeOptions_Block</class>
                    <rewrite>
                        <bestsellers>Meigee_ThemeOptions_Block_Bestsellers</bestsellers>
                    </rewrite>
            </themeoptions>
        </blocks>
    </global>

    <default>
        <meigee_general>
            <appearance>
                0
                <default_sizes>1</default_sizes>
                <fontsize>14</fontsize>
                <lineheight>24</lineheight>
                <fontweight>400</fontweight>
                <patern>pandora</patern>
            </appearance>
            <layout>
                <sidebar>sidebar_right</sidebar>
                <grid>grid_standard</grid>
                <cartpage>cart_accordion</cartpage>
            </layout>
            <menu>
                <type>menu_wide</type>
                <home>1</home>
            </menu>
            <otheroptions>
                <totop>1</totop>
                <labelnew>1</labelnew>
            </otheroptions>
            <lang_switcher>
                <status>language_select</status>
                0
            </lang_switcher>
            <curr_switcher>
                <status>currency_images</status>
                0
            </curr_switcher>
            <fancybox>
                <fancybox_status>1</fancybox_status>
                <fancybox_home>1</fancybox_home>
                <fancybox_listing>1</fancybox_listing>
            </fancybox>
        </meigee_general>
        <meigee_productpage>
            <productpage>
                <prevnext>prevnext</prevnext>
                <moreviews>moreviews_slider</moreviews>
                <collateral>collateral_tabs</collateral>
                <collateral_related>related_slider</collateral_related>
            </productpage>
        </meigee_productpage>
        <meigee_sidebar>
            <block_categories>
                <status>1</status>
                <option>1</option>
                <option_2>1</option_2>
            </block_categories>
            <block_shop_by>
                <status>1</status>
                <option>1</option>
                <option_2>1</option_2>
            </block_shop_by>
            <block_compare>
                <status>1</status>
            </block_compare>
            <block_compared>
                <status>1</status>
            </block_compared>
            <block_viewed>
                <status>1</status>
            </block_viewed>
            <block_wishlist>
                <status>1</status>
                <option>1</option>
            </block_wishlist>
            <block_tags>
                <status>1</status>
            </block_tags>
            <block_orders>
                <status>1</status>
            </block_orders>
        </meigee_sidebar>
    </default>
</config>

EDIT 2: Tried disabling the module by the Meigee_ThemeOptions.xml file, still getting the same error:
<?xml version="1.0"?>
<config>
   <modules>
      <Meigee_ThemeOptions>
         <active>false</active>
         <codePool>local</codePool>
      </Meigee_ThemeOptions>
   </modules>
</config>

EDIT 3: Developer mode should be off. The index.php file has the below lines:
if (isset($_SERVER['MAGE_IS_DEVELOPER_MODE'])) {
    Mage::setIsDeveloperMode(true);
    ini_set('display_errors', 1);
}
else
{
    Mage::setIsDeveloperMode(false);
    ini_set('display_errors', 0);
}

And .htaccess file has the line SetEnv MAGE_IS_DEVELOPER_MODE "false"
I added the line to htaccess file because I did turn on developer mode (by commenting out the if statement) to get some error logs but don't think it has turned off correctly...Any help with that would be appreciated.

A:

This error is only displayed when you have developer mode on. Leaving developer mode on a production server is really not recommended, since you run the risk of exposing your shop structure and could possibly lead to vulnerabilities, attacks, etc. Make sure you turn developer mode off by making sure the environment variable MAGE_IS_DEVELOPER_MODE is not set.
Please notice: not set means that the variable is not declared, since Magento is checking for its presence, not whethere it's true or false or any value.


Q:

Is it possible to format an USB external HD keeping intact some directories and files?

Maybe it is a nonsense question, but I would like to format my external HD which contains plenty of files and directories, the HD format is NTFS, if it is possible I would like to format to ext4 but keeping one directory and its files intact. I know that I can backup it before formatting. Is it possible ? I'm running Xubuntu 16.04.5 and this external HD was originally recovered from an old netbook running Windows XP. Thanks, Vladi

A:

Nope. If you format a partition that contains files, the operation will clear out all of the files.
What you COULD do is use gparted to shrink the ntfs partition on the external drive, then create a new ext4 partition in the newly created free space (again using gparted), then move the files from the old NFTS partition to the new ext4 partition. Once you've done that, use gparted once again to remove the ntfs partition and to grow the new ext4 partition to fill all of the unused space.


Q:

Apache Samza local storage - OrientDB / Neo4J graph instead of KV store

Apache Samza uses RocksDB as the storage engine for local storage.  This allows for stateful stream processing and here's a very good overview.
My use case:

I have multiple streams of events that I wish to process taken from a system such as Apache Kafka.
These events create state - the state I wish to track is based on previous messages received.
I wish to generate new stream events based on the calculated state.
The input stream events are highly connected and a graph such as OrientDB / Neo4J is the ideal medium for querying the data to create the new stream events.

My question:
Is it possible to use a non-KV store as the local storage for Samza? Has anyone ever done this with OrientDB / Neo4J and is anyone aware of an example?

A:

I've been evaluating Samza and I'm by no means an expert, but I'd recommend you to read the official documentation, and even read through the source code—other than the fact that it's in Scala, it's remarkably approachable.
In this particular case, toward the bottom of the documentation's page on State Management you have this:

Other storage engines
Samza’s fault-tolerance mechanism (sending a local store’s writes to a replicated changelog) is completely decoupled from the storage engine’s data structures and query APIs. While a key-value storage engine is good for general-purpose processing, you can easily add your own storage engines for other types of queries by implementing the StorageEngine interface. Samza’s model is especially amenable to embedded storage engines, which run as a library in the same process as the stream task.
Some ideas for other storage engines that could be useful: a persistent heap (for running top-N queries), approximate algorithms such as bloom filters and hyperloglog, or full-text indexes such as Lucene. (Patches accepted!)

I actually read through the code for the default StorageEngine implementation about two weeks ago to gain a better sense of how it works.  I definitely don't know enough to say much intelligently about it, but I can point you at it:

https://github.com/apache/samza/tree/master/samza-kv-rocksdb/src/main/scala/org/apache/samza/storage/kv
https://github.com/apache/samza/tree/master/samza-kv/src/main/scala/org/apache/samza/storage/kv

The major implementation concerns seem to be:

Logging all changes to a topic so that the store's state can be restored if a task fails.
Restoring the store's state in a performant manner
Batching writes and caching frequent reads in order to save on trips to the raw store.
Reporting metrics about the use of the store.