text:
Q: which and type show different paths to IPython executable in virtualenv, import fails in IPython, succeeds in standard interpreter? (myvirtualenv)[~] sam@iota $ type ipython
ipython is hashed (/usr/local/bin/ipython)
(myvirtualenv)[~] sam@iota $ which ipython
/Users/sam/.virtualenvs/myvirtualenv/bin/ipython

regardless of what which says, it executes /usr/local/bin/ipython
(myvirtualenv)[~] sam@iota $ ipython

WARNING: Attempting to work in a virtualenv. If you encounter problems, please install IPython inside the virtualenv.
Python 2.7.5 (default, Sep  6 2013, 17:51:18)

IPython 1.1.0 -- An enhanced Interactive Python.

In [1]:  import novaclient
---------------------------------------------------------------------------
Exception                                 Traceback (most recent call last)
<ipython-input-1-93e5b70cb5b9> in <module>()
----> 1 import novaclient

/Users/sam/.virtualenvs/myvirtualenv/lib/python2.7/site-packages/novaclient/__init__.py in <module>()
     16
     17
---> 18 __version__ = pbr.version.VersionInfo('python-novaclient').version_string()

/Users/sam/.virtualenvs/myvirtualenv/lib/python2.7/site-packages/pbr/version.pyc in version_string(self)
     70         if self.version is None:
     71             parts = []
---> 72             for part in self.release_string().split('.'):
     73                 if part[0].isdigit():
     74                     parts.append(part)

/Users/sam/.virtualenvs/myvirtualenv/lib/python2.7/site-packages/pbr/version.pyc in release_string(self)
     62
     63         if self.release is None:
---> 64             self.release = self._get_version_from_pkg_resources()
     65
     66         return self.release

/Users/sam/.virtualenvs/myvirtualenv/lib/python2.7/site-packages/pbr/version.pyc in _get_version_from_pkg_resources(self)
     55             # installed into anything. Revert to setup-time logic.
     56             from pbr import packaging
---> 57             return packaging.get_version(self.package)
     58
     59     def release_string(self):

/Users/sam/.virtualenvs/myvirtualenv/lib/python2.7/site-packages/pbr/packaging.pyc in get_version(package_name, pre_version)
    820     if version:
    821         return version
--> 822     raise Exception("Versioning for this project requires either an sdist"
    823                     " tarball, or access to an upstream git repository."
    824                     " Are you sure that git is installed?")

Exception: Versioning for this project requires either an sdist tarball, or access to an upstream git repository. Are you sure that git is installed?

now forcing it to execute /Users/sam/.virtualenvs/myvirtualenv/bin/ipython
(myvirtualenv)[~] sam@iota $ `which ipython`

Python 2.7.5
Type "copyright", "credits" or "license" for more information.

IPython 1.1.0 -- An enhanced Interactive Python.

In [1]: import novaclient
In [2]: print "all is well here"
all is well here

(myvirtualenv)[~] sam@iota $ echo $PATH
 /Users/sam/.virtualenvs/myvirtualenv/bin:/usr/local/sbin:/usr/local/lib:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin
(myvirtualenv)[~] sam@iota $ python

Python 2.7.5 (default, Sep  6 2013, 17:51:18)
[GCC 4.2.1 Compatible Apple LLVM 4.2 (clang-425.0.24)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import novaclient
>>> print "all is well here"
all is well here
>>> exit()

Why do which and type point to different paths? Why, if IPython is installed in my virtualenv, does the system IPython get executed, even though the order of my $PATH would indicate otherwise? In any case, why does import novaclient bomb out with what seems to be a pretty bizarre error?

EDIT
pythonpath from erroneous session
(myvirtualenv)[~] sam@iota $ ipython -c 'import sys;sys.path'
['/Users/sam/.virtualenvs/myvirtualenv/lib/python2.7/site-packages',
 '',
 '/usr/local/bin',
 '/usr/local/Cellar/python/2.7.5/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/setuptools-1.1-py2.7.egg',
 '/usr/local/Cellar/python/2.7.5/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pip-1.4.1-py2.7.egg',
 '/usr/local/Cellar/python/2.7.5/Frameworks/Python.framework/Versions/2.7/lib/python27.zip',
 '/usr/local/Cellar/python/2.7.5/Frameworks/Python.framework/Versions/2.7/lib/python2.7',
 '/usr/local/Cellar/python/2.7.5/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin',
 '/usr/local/Cellar/python/2.7.5/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac',
 '/usr/local/Cellar/python/2.7.5/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages',
 '/usr/local/Cellar/python/2.7.5/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk',
 '/usr/local/Cellar/python/2.7.5/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old',
 '/usr/local/Cellar/python/2.7.5/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload',
 '/Library/Python/2.7/site-packages',
 '/usr/local/lib/python2.7/site-packages',
 '/usr/local/lib/python2.7/site-packages/IPython/extensions']

pythonpath from successful session
(myvirtualenv)[~] sam@iota $ python -c 'import sys;print sys.path'
['',
 '/Users/sam/.virtualenvs/projectx-dev-2/bin',
 '/Users/sam/.virtualenvs/projectx-dev-2/src/pyrax',
 '/Users/sam/.virtualenvs/projectx-dev-2/lib/python27.zip',
 '/Users/sam/.virtualenvs/projectx-dev-2/lib/python2.7',
 '/Users/sam/.virtualenvs/projectx-dev-2/lib/python2.7/plat-darwin',
 '/Users/sam/.virtualenvs/projectx-dev-2/lib/python2.7/plat-mac',
 '/Users/sam/.virtualenvs/projectx-dev-2/lib/python2.7/plat-mac/lib-scriptpackages',
 '/Users/sam/.virtualenvs/projectx-dev-2/lib/python2.7/lib-tk',
 '/Users/sam/.virtualenvs/projectx-dev-2/lib/python2.7/lib-old',
 '/Users/sam/.virtualenvs/projectx-dev-2/lib/python2.7/lib-dynload',
 '/usr/local/Cellar/python/2.7.5/Frameworks/Python.framework/Versions/2.7/lib/python2.7',
 '/usr/local/Cellar/python/2.7.5/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin',
 '/usr/local/Cellar/python/2.7.5/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk',
 '/usr/local/Cellar/python/2.7.5/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac',
 '/usr/local/Cellar/python/2.7.5/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages',
 '/Users/sam/.virtualenvs/myvirtualenv/lib/python2.7/site-packages',
 '/Users/sam/.virtualenvs/myvirtualenv/lib/python2.7/site-packages/IPython/extensions']

A:
Why do which and type point to different paths?

If your shell has hashed ipython's path, type will give you the hashed path without searching $PATH, while which will ignore the hashed path and do the search.
Assuming your shell is bash, the hash command (with no args) will show you the hashed paths, or you can look at the BASH_CMDS associative array. But you already know that ipython is hashed, because type just told you.
Usually you can fix this by just starting a new shell, using the hash -r command (to wipe the cache without restarting anything else), or hash -d ipython (to remove just ipython from the cache—but make sure you don't also have, e.g., python in the cache). With different shells, the two commands may be different (e.g., in *csh and zsh, it's rehash and rehash ipython, respectively), but starting a new shell should always works.
For more details, see the Command Search and Execution in the bash reference manual, or the bash(1) manpage on your system, or the numerous easier-to-understand blog posts that will show up if you google something like "bash hash cache" (like this one).

Why, if IPython is installed in my virtualenv, does the system IPython get executed

If your shell has hashed ipython's path, ipython will run from the hashed path, without searching $PATH.
Again, starting a new shell, etc., should fix this.

In any case, why does import novaclient bomb out with what seems to be a pretty bizarre error?

Most likely it's getting the PYTHONPATH from your environment, which causes the venv's site-packages and dist-packages to come become the system Python's, and the packages in those locations don't work with the system Python.
You can verify this by printing out sys.path. But the fact that it's complaining about files in /Users/sam/.virtualenvs/myvirtualenv/lib/python2.7/site-packages/ implies that this path must be on sys.path. And (since you're running from a different directory) not just because the default . is picking it up, but because it's there explicitly. So, all that sys.path could tell you is whether it's an absolute or relative path.


text:
Q: How to route URL in a same way like stackoverflow does This is how I think that this works
http://stackoverflow.com/questions/12333706/how-to-bla-bla-question

I think that there should be a controller action and link
@Html.ActionLink("how-to-bla-bla-question", "Questions", "Controller", new{questionId=12333706})
...
public ActionResult Questions(questionId)
{
    ...
}

Normally url should be
http://stackoverflow.com/questions/12333706/

Now is this handled by javascript or there is some other method how to make url with ID and title after it?

A: I have done exactly that like this.
Global.asax snippet:
routes.MapRoute(
        "GotoPostOrPage",
        "p/{dataItemTypeId}/{dataItemId}/{ignored}", // This allows you to append a random slug if you like
        new { controller = "DataItem", action = "Details", ignored = UrlParameter.Optional }
        );

And then something like this in the controller:
public PartialViewResult Details(int dataItemTypeId, int dataItemId)
{
    IDataItemView dataItem = _dataItemService.SelectDataItem(dataItemTypeId, dataItemId);
    DataItemViewModel vm = MappingFunctions.DataItemToViewModel(dataItem);

    return PartialView("_Details", vm);
}

Note that this allows you to append a random slug which is exactly what stackoverflow does. However, stackoverflow then corrects your slug to the one stored in the database. This would be trivial to implement.
Also note that I have shown you my real code; you'd obviously need to tweak it a little bit (but not much) to fit your scenario. The important point is to append an optional url parameter in the route table. In my case I ignore it completely, which is actually what SO does too on the way in, hence you can navigate to this daft URL and still get here: https://stackoverflow.com/questions/12051094/i-like-to-eat-cake

redpajama_set_name: RedPajamaStackExchange


text:
Q: Linear Layout add scrollView in programmatically
everything ok but I could not add Scrollview because I'm getting an error in scrollView.addView(mainlinearLayout);
There are similar questions but i didnt find the answer. I would be glad if you help me. Thanks
This is error

java.lang.IllegalStateException: The specified child already has a
  parent. You must call removeView() on the child's parent first.

This is activity_main.xml's Code
  <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/LinLay"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

    </LinearLayout>

This is MainActivity's Code
public void drawer() {
        String[] word=s.split(" ");
        scrollView=new ScrollView(this);
        mainlinearLayout = (LinearLayout) findViewById(R.id.LinLay);
        mainlinearLayout.setVerticalScrollBarEnabled(true);
        scrollView.addView(mainlinearLayout);
        childLinearLayout = getLinearLayout();

        for (int i = 1; i < word.length; i++) {
            final TextView textView = new TextView(this);
            textView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            textView.setTextSize(17);
            textView.setPadding(5, 5, 5, 5);
            textView.setText(word[i-1].toString());
            childLinearLayout.addView(textView);

            if (i % separatorNum == 0 && i != 0) {
                mainlinearLayout.addView(childLinearLayout, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
                setContentView(mainlinearLayout);
                childLinearLayout=getLinearLayout();
            }

            textView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Toast.makeText(getApplicationContext(), textView.getText().toString(), Toast.LENGTH_LONG).show();
                }
            });
        }
     }

A: If you have activity_main.xml as your Activity's content view:
setContentView(R.layout.activity_main)

then you are attaching your view to the activity, hence giving it (and the LinearLayout with id=LinLay) a parent.
If you want to make the ScrollView the main UI element in your Activity, then you should do
setContentView(scrollView)

or better yet do that in XML. Once the ScrollView is the parent, you can add your LinearLayout.

A: You are adding a scroll view in layout.
if you are adding layout in scroll view then always remember you can add only one layout a scroll view. you can alternatively add linear layout in a scroll view and then can add number of layouts in the same.

A: try below code it will check if child has parent or not,if there then remove the view,this will help you.
 public void drawer() {
                String[] word=s.split(" ");
                scrollView=new ScrollView(this);
                mainlinearLayout = (LinearLayout) findViewById(R.id.LinLay);
                mainlinearLayout.setVerticalScrollBarEnabled(true);
                scrollView.addView(mainlinearLayout);
                childLinearLayout = getLinearLayout();

                for (int i = 1; i < word.length; i++) {
                    final TextView textView = new TextView(this);
                    textView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                    textView.setTextSize(17);
                    textView.setPadding(5, 5, 5, 5);
                    textView.setText(word[i-1].toString());
    if (textView.getParent() != null) {
                            ((ViewGroup) textView.getParent()).removeView(textView);
                        }
                    childLinearLayout.addView(textView);

                    if (i % separatorNum == 0 && i != 0) {
                        mainlinearLayout.addView(childLinearLayout, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
                        setContentView(mainlinearLayout);
                        childLinearLayout=getLinearLayout();
                    }

                    textView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Toast.makeText(getApplicationContext(), textView.getText().toString(), Toast.LENGTH_LONG).show();
                        }
                    });
                }

            }

A: You can try this, and try to set setContentView(R.layout.activity_main) before calling this.
The problem is your LinearLayout already attached to activity view same Layout you are trying to add to scrollview so it was giving error.
public void drawer() {
    //String s = "sdfsdfsdf sdfsdfsd sdfsdf sdfs sdf sdf sdf sdfdsfsdf sfsdf ssdfdsf sdfsd";
    int separatorNum = 5;
    String[] word = s.split(" ");
    scrollView = new ScrollView(this);
    mainlinearLayout = (LinearLayout) findViewById(R.id.LinLay);
    mainlinearLayout.setVerticalScrollBarEnabled(true);

    mainlinearLayout.addView(scrollView);

    LinearLayout linearLayout = new LinearLayout(this);
    linearLayout.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
    linearLayout.setOrientation(LinearLayout.VERTICAL);
    scrollView.addView(linearLayout);

    LinearLayout childLinearLayout = getLinearLayout();

    for (int i = 1; i < word.length; i++) {
        final TextView textView = new TextView(this);
        textView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        textView.setTextSize(17);
        textView.setPadding(5, 5, 5, 5);
        textView.setText(word[i - 1].toString());
        childLinearLayout.addView(textView);

        if (i % separatorNum == 0 && i != 0) {
            linearLayout.addView(childLinearLayout, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
           // setContentView(mainlinearLayout);
            childLinearLayout = getLinearLayout();
        }

        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(getApplicationContext(), textView.getText().toString(), Toast.LENGTH_LONG).show();
            }
        });
    }

}

private LinearLayout getLinearLayout() {
    LinearLayout childLinearLayout = new LinearLayout(this);
    childLinearLayout.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
    childLinearLayout.setOrientation(LinearLayout.HORIZONTAL);

    return childLinearLayout;
}

A: your trying to add exiting layout to scroll-view its giving error, so try to add scroll-view to your existing layout
don't know it will serve your requirement or not .
Try this method
public void drawer() {
        String[] word=s.split(" ");
        ScrollView  scrollView = new ScrollView(this);
        mainlinearLayout_ = (LinearLayout) findViewById(R.id.LinLay);
        mainlinearLayout_.removeAllViews();
        scrollView.removeAllViews();
        mainlinearLayout_.addView(scrollView);
        LinearLayout  verticalLinearLayout = new  LinearLayout(this);
        verticalLinearLayout.setOrientation(LinearLayout.VERTICAL);
        for (int j = 0; j < 3; j++) {
            LinearLayout horizontalChildLinearLayout = new LinearLayout(this);
            horizontalChildLinearLayout.setOrientation(LinearLayout.HORIZONTAL);

            for (int i = 1; i < word.length; i++) {
                final TextView textView = new TextView(this);
                textView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                textView.setTextSize(17);
                textView.setPadding(5, 5, 5, 5);
                textView.setText(word[i - 1].toString());

                textView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Toast.makeText(getApplicationContext(), textView.getText().toString(), Toast.LENGTH_LONG).show();
                    }
                });
                horizontalChildLinearLayout.addView(textView);
            }
            verticalLinearLayout.addView(horizontalChildLinearLayout, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        }
        scrollView.addView(verticalLinearLayout);
    }

Thank you.


text:
Q: How to add custom property on electron js browsel window? I tried adding a custom property on the main browser window, but when tried to access i am just getting undefined.
Upon the creation of the main window I add a custom property.
let win = new electron.BrowserWindow();
win.sampleProperty = 'sample value';

But when accessing it cant retrieve the value of the sampleProperty.
let bw = browserWindow.getFocusedWindow();
console.log(bw.sampleProperty) // This is undefined

I'd used the getFocusedWindow() because it will be triggered on menu click.
What I am missing here why bw.sampleProperty is undefined.
Thanks.

A: I just end app adding the property to the browserWindowOptions
This is how to do it:
Upon on creation of the browserWindow just add your property on the constructor.
let win = new electron.BrowserWindow({
  show: false,
  customProperty: 'sample' // And here it is.
});

Then you can access it on the browserWindowOptions
let customProp = BrowserWindow.getFocusedWindow()
                 .webContents
                 .browserWindowOptions.customProperty;


text:
Q: Allow single-line accessor (getter/setter) syntax with Checkstyle We'd like to have trivial Java property accessors using a single line syntax, so they take up much much less space, and are more readable (in terms of 'seeing' the set of accessors quickly). But we do want to enforce multi-line method syntax for everything else in our checkstyle configuration. But I'm not sure how to make this exception for accessors in Checkstyle config and suspect it may not be possible.
So we'd like our accessors to look something like this:
public String getFoo() { return foo; }
public void setFoo(String foo) { this.foo = foo; }

[In fact we'd rather not have trivial accessors at all and instead just annotate the private member variables with @Property or something and have the accessors generated for us, since writing endless get and set code delivers no real benefit, but that's a general Java frustration and an aside as far as this question goes.]

A: If you want to solve this using Checkstyle, then you must write one or more custom checks. Your check would be a subclass of the check you are modifying. Then, for all checks that are affected, you would enter your own subclassed check into the checkstyle configuration (and remove the original one).
You might be able to cannibalize some code from the JavadocMethodCheck, which already detects trivial accessors. This sounds like a lot of work, but it's not much code because the modification you make in your subclass is always the same and can thus be put into a helper class.
I honestly don't think that Checkstyle can do it out of the box, sorry!

A: I would recommend using the SuppressionCommentFilter to disable Checkstyle checks for a block of code.
It would then be possible to do the following to turn off Checkstyle like the following:
// CHECKSTYLE_OFF: ALL
public String getFoo() { return foo; }
public void setFoo(String foo) { this.foo = foo; }
// CHECKSTYLE_ON: ALL


text:
Q: Why is my groupby returning incorrect values for the 'product' column? I am trying to get the maximum price paid by each user, as well as which product was purchased, into a dataFrame. When I run the below code, it returns exactly what I'd expect, but the 'product' column is incorrect.
Original data:
df = pd.DataFrame([[123,'xt23',20],
                   [123,'q45',2],
                   [123,'a89',25],
                   [77,'q45',3],
                   [77,'a89',30],
                   [92,'xt23',24],
                   [92,'m33',60],
                   [92,'a89',28]], columns=['userid','product','price'])
df

which generates this original dataFrame:
    userid  product price
0   123     xt23    20
1   123     q45     2
2   123     a89     25
3   77      q45     3
4   77      a89     30
5   92      xt23    24
6   92      m33     60
7   92      a89     28

This is what's not working:
df.groupby('userid').max()

EXPECTED OUTPUT:
userid  product price
77      a89     30
92      m33     60
123     a89     25

ACTUAL OUTPUT:
userid  product price
77      q45     30
92      xt23    60
123     xt23    25

The values in the product column are incorrect. If I add 'product' to the groupby, the max prices are still correct, but I only want to see one price & product per user. I also tried setting numeric_only=True but that did not solve the issue.
Does anyone know why the product values don't align with the original data?

A: Use this to get the desired output efficiently.
idx = df.groupby(['userid'])['price'].transform(max) == df['price']
print(df[idx])


text:
Q: Error: Expected one matching request for criteria no parameters I've found several answers to this problem, but all of them involve having parameters and not including them on the call. But my case is different because I do not have parameters.
According to all the material, I have consulted, I cannot find what I'm doing wrong.
Basically, it is this:
in the service I'm testing, I have a call like this:
public getData(): Observable<string[][]> {
    const url = `${this.config.baseUrl}/data/`;
    return this.http.get<string[][]>(url);
  }

in providers of the spec file
{ provide: ConfigService, useValue: { baseUrl: '/base-url', tokenAuth: true } },

and
httpMock = TestBed.inject(HttpTestingController);
service = TestBed.inject(DataService);

and the test
it('should return the values of data when calling the API,' done => {
    const mockValue: [['data1','data2'],['data3','data4'],['data5','data6']];

    const sub = service.getData().subscribe(
      value => {
        expect(value).toHaveLength(3);
        httpMock.verify();
        done();
      },
      error => {
        throw error;
      },
    );
    subs.add(sub);

    httpMock.expectOne('/base-url/data').flush(mockValue);
  });

But when I ran the test, I received the following:
Expected one matching request for criteria "Match URL: /base-url/data/", found none.


text:
Q: String.intern() shows strange result, how does it work I know that String.intern() adds string to pool if it does not contain the object, but how to explain the results.
The code below:
public static void main(String[] args) {

        char[] abc = new char[]{'a','b','c'};
        String str = new String(abc);
        System.out.println(str == "abc");
        str.intern();
        System.out.println(str == "abc");
    }

output is :
false
false
However when code as below:
public static void main(String[] args) {

        char[] abc = new char[]{'a','b','c'};
        String str = new String(abc);
        str.intern();
        System.out.println(str == "abc");
    }

The output is:
true
What's the difference.

A: The difference is that when you use the String literal "abc" before the explicit call to intern, it is implicitly interned.
str.intern() doesn't store the instance referenced by str in the String pool if an equal String is already in the pool.
First snippet:
System.out.println(str == "abc"); // "abc" is interned
str.intern(); // str is not stored in the pool
System.out.println(str == "abc"); // returns false

Second snippet:
str.intern(); // str is stored in the pool
System.out.println(str == "abc"); // returns true

From the Javadoc of intern:

String java.lang.String.intern()
When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned...
All literal strings and string-valued constant expressions are interned.


text:
Q: dial tcp 127.0.0.1:3333: can't assign requested address, getting this error while hitting http request concurrently for 40000 iterations I am getting error:
dial tcp 127.0.0.1:3333: can't assign requested address
whenever i try to hit http request concurrently using go routines for 40000 iterations,
it was working fine till 20-30000 iterations,
Here is the code I am trying to run:
func TestHttp(c *gin.Context) {
    limit, _ := strconv.Atoi(c.Param("limit"))
    for i := 1; i <= limit; i++ {
        url := "http://hostname/merchant" + strconv.Itoa(i) + "/print-test?p=" + strconv.Itoa(i)
        go MakeRequest2(url, i)
    }
}

/*

 * Function to hit url with get method and close the response body
 */
func MakeRequest2(url string, i int) {
    client := &http.Client{}
    req, err := http.NewRequest("GET", url, nil)
    if err != nil {
        fmt.Println(err)
        return
    }
    req.Close = true
    resp, err := client.Do(req)
    if err != nil {
        fmt.Println(err)
        return
    }
    defer resp.Body.Close()
}

func PrintTest(c *gin.Context) {
    a := make(map[string]int)
    for i := 1; i <= 10; i++ {
        a[strconv.Itoa(i)] = i
    }
    fmt.Println(a)
}

I am getting this output:
Get "http://hostname/merchant34096/print-test?p=34096": dial tcp hostname: connect: cannot assign requested address >

I am expecting to run this code for 1 million iterations concurrently.


text: Q: Can we approximate a bounded upper semicontinuous function by increasing continuous sequences? Can we approximate a bounded upper semicontinuous function by increasing continuous sequences? Even though the inverse question is obvious.


text:
Q: populate select options from extra mysql table data hi guys i am trying to populate a select element with options from the data in one of my sql tables heres what i have so far:
 <?
$SQL = "SELECT * FROM pt_country ORDER BY name";
    $rs = $wpdb->query($SQL);
    $nr = mysql_num_rows($rs);
        for ($i=0; $i<$nr; $i++) {
        $r = mysql_fetch_array($rs);
        echo "<OPTION VALUE=\"".$r["countrycode"]."\">".$r["country"]."</OPTION>";
       }
?>

im guessing quite a bit of this is wrong but to start with i cant get wordpress to return the data i just get false what am i missing here ?

A: You should not use mysql_fetch_array()
Use wordpress built-in functions, like this:
$SQL = "SELECT * FROM pt_country ORDER BY name";
$rows = $wpdb->get_results( $SQL );
foreach($rows as $r){
 print_r($r);
}


text:
Q: Where to run tests to check I ran the test server (if I understand correctly) with help of karma. I have a browser window with the message "Karma v0.12.2 - connected". Next I have to run the tests form:
define([
    'app', 'jquery', 'angular',
    'angular', 'angularRoute', 'angularMocks'
],
function() {
    describe('UnitTest: App', function() {
        // just like normal
        it('is defined', function() {
            expect(_.size([1,2,3])).toEqual(3);
        });
    });
});

But I do not understand how to run them.

A: Open your command prompt or terminal depending on the OS you are using.
Navigate to the folder where your test folder and karma.conf.js lives. In your karma.conf.js make sure you specify the location of your test files.
module.exports = function(config) {
    config.set({

        files: [
            // Test cases
            'Tests/unit/**/*spec.js'
        ]

On your terminal, type the command
$ karma start karma.conf.js

And you should see the result of the test on your terminal.
INFO [karma]: Karma v0.10.9 server started at http://localhost:9876/
INFO [launcher]: Starting browser Chrome
INFO [Chrome 33.0.1750 (Windows 7)]: Connected on socket plwJXWX7daiEQHzUabTM
Chrome 33.0.1750 (Windows 7): Executed 20 of 20 SUCCESS (2.565 secs / .891 secs)


text:
Q: Kubernetes apply command produces 'wrong encoding error' I'm trying to execute:
microk8s kubectl apply -f  deployment.yaml

and I am always getting:
error: string field contains invalid UTF-8

No matter which file and string as a file path parameter I'm trying to use. Even if I execute:
microk8s kubectl apply -f  blablabla

Result is the same.

UPD: I resolved the problem by restarting microk8s service. After restart everything is fine, but I still have no idea what it was.

A: I have posted Community Wiki answer for better visibility.
As OP has mentioned in the question, he resolved the problem by restarting microk8s service:

I resolved the problem by restarting microk8s service. After restart everything is fine.

A: This is not a wrong format in the manifest, instead, it's a corrupted cache in $HOME/.kube/
try to delete the cache:
rm -rf $HOME/.kube/http-cache
rm -rf $HOME/.kube/cache


text:
Q: Client Side IPEndPoint can't use IPAddress.Any? I have been learning some socket programming, i have created an asynchornous server which is only listen and return the data.
but i have a problem here, I use IPEndPoint on server with IPEndPoint(IPAddress.any,port), and I do the same with the client side. When running the server and client, I use try catch and the client side returning its exception like this
"The requested address is not valid in its context 0.0.0.0:port"
here below is the code:
Server.cs
      Public void Listen()
      {
        IPEndPoint IpEnd = new IPEndPoint(IPAddress.Any, 11000);

        Console.WriteLine("Create new socket");
        mainSocket = new Socket(AddressFamily.InterNetwork,
                       SocketType.Stream,ProtocolType.IP);

        Console.WriteLine("Bind the socket");
        mainSocket.Bind(IpEnd);

        Console.WriteLine("Listening to socket");
        mainSocket.Listen(10);

        Console.WriteLine("Waiting Connection");
        mainSocket.BeginAccept(new AsyncCallback(AcceptConnect), null);
      }
      protected void AcceptConnect(IAsyncResult ar)
      {
        try
        {
            Socket client = mainSocket.EndAccept(ar);
            SessionData session = new SessionData();
            Console.WriteLine("Connection Accepted, waiting for Data");
            Console.WriteLine("Waiting a new Connection");
            mainSocket.BeginAccept(new AsyncCallback(AcceptConnect), null);
            try{
                session.clientSocket = client;
                client.BeginReceive(session.buffer,0,SessionData.buffersize,0,
                                    new AsyncCallback(ReceiveData), session);
            }catch(Exception e){
                client.Send(ASCIIEncoding.Default.GetBytes(e.Message));
                Console.WriteLine(e.Message);
            }
        }
        catch(Exception e)
        {
            Console.WriteLine(e.Message);
            Console.WriteLine(e.StackTrace);
        }
      }

Client.cs
    public void ClientConnect()
    {

        // Create a TCP/IP socket.
        Socket client = new Socket(AddressFamily.InterNetwork,
                        SocketType.Stream, ProtocolType.Tcp);

        IPEndPoint remoteEP = new IPEndPoint(IPAddress.Any, 11000);

        // Connect to the remote endpoint.
        client.BeginConnect(remoteEP, new AsyncCallback(ConnectServer), client);
    }
    public void ConnectServer(IAsyncResult ar)
    {
        try
        {
            Socket client = (Socket)ar.AsyncState;
            client.EndConnect(ar);

            Console.WriteLine("Socket connected to {0}",
                             client.RemoteEndPoint.ToString());
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
    }

my question is :

*

*Does client need to point at one IPAddress?

*Am I just using the wrong code on the server?

A: The client needs to point to a specific IP address (i.e. 192.168.1.101 or something similar), you can't send packets to IP 0.0.0.0. The reason that the server can accept IP.Any is that it's listening on all IP address on the local machine, which is represented at 0.0.0.0.


text:
Q: How do I include Zend Framework libraries in my domain? Locally, on my xampp installation, the Zend folder is under PEAR\Zend, and Pear is in the include path. So when I do require_once "Zend\Date.php" there is no problem.
However, on my domain (Hostmonster), that's not the case. I have no idea where the Zend folder is, although doing phpinfo(); seems to indicate that Zend Framework is definitely available. I asked the host, and they told me to include zend_extension="/usr/local/Zend/lib/Optimizer-3.3.9/php-5.2.x/ZendOptimizer.so" at the bottom of the php.ini file, which didn't help at all.
Also, I don't know what that statement in the php.ini file even does. Could anyone please help?

A: Perhaps you could upload the Zend library to your shared hosting account in a directory like /home/your_account/public_html/zend.
Then modify (or create if it doesn't exist) a php.ini file in your webroot directory /home/your_account/public_html.  Add the following:
include_path = .:/home/your_account/public_html/Zend

Note: this will override any default include paths set by PHP.  The . represents the current directory and : separates the different paths.
Now in your PHP file you can add at the top:
require_once 'Zend/Date.php';

A: Enabling Zend extension as you mentioned above is not relevant to including ZF classes which you want to do. Download ZF and upload it to wherever you like in public_html folder if that's not available somewhere yet. use set_include_path() and go! sample code below:
<?php
    // Define relative path to ZendFramework in public_html
    define('ZF_PATH', '/../../../lib/php/zendframework');

    // Define path to application directory
    defined('APPLICATION_PATH') || define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));

    // Define real path to ZendFramework if it's not yet included in include_path
    if(!strpos(get_include_path(), 'zendframework'))
        define('ZF_REAL_PATH', realpath(APPLICATION_PATH . ZF_PATH));
    else define('ZF_REAL_PATH', '');

    // Updating include_path
    set_include_path(implode(PATH_SEPARATOR, array(ZF_REAL_PATH, get_include_path(),)));

    // Done! the rest of the code might be unnecessary in your case.
    require 'Zend/Application.php';

    // Create application, bootstrap, and run
    $application = new Zend_Application(APPLICATION_ENV, APPLICATION_PATH . '/configs/application.ini');
    $application->bootstrap()->run();

This might seem kinda complicated for the case of adding a directory to include path but it's the most common way ZF apps use, I think.

A: The zend autoloader makes life easier:
set_include_path(get_include_path().PATH_SEPARATOR.realpath('../path to folder containing zend classes'));
require_once('Zend/Loader.php');
require_once('Zend/Loader/Autoloader.php');
Zend_Loader::registerAutoload();

now you don't need dozens of includes or requires cluttering your code...
as of Zend: 1.11.1 at least


text:
Q: find duplicates with grouped variables I have a df that looks like this:
I guess it will work some with dplyr and duplicates. Yet I don't know how to address multiple columns while distinguishing between a grouped variable.
from  to  group

1     2   metro
2     4   metro
3     4   metro
4     5   train
6     1   train
8     7   train

I want to find the ids which exist in more than one group variable.
The expected result for the sample df is: 1 and 4. Because they exist in the metro and the train group.
Thank you in advance!

A: Using base R we can split the first two columns based on group and find the intersecting value between the groups using intersect
Reduce(intersect, split(unlist(df[1:2]), df$group))
#[1] 1 4

A: We gather the 'from', 'to' columns to 'long' format, grouped by 'val', filter the groups having more than one unique elements, then pull the unique 'val' elements
library(dplyr)
library(tidyr)
df1 %>%
   gather(key, val, from:to) %>%
   group_by(val) %>%
   filter(n_distinct(group) > 1) %>%
   distinct(val) %>%
   pull(val)
#[1] 1 4

Or using base R we can just table to find the frequency, and get the ids out of it
out <-  with(df1, colSums(table(rep(group, 2), unlist(df1[1:2])) > 0)) > 1
names(which(out))
#[1] "1" "4"

data
df1 <- structure(list(from = c(1L, 2L, 3L, 4L, 6L, 8L), to = c(2L, 4L,
 4L, 5L, 1L, 7L), group = c("metro", "metro", "metro", "train",
 "train", "train")), class = "data.frame", row.names = c(NA, -6L
 ))

A: Convert data to long format and count unique values, using data.table. melt is used to convert to long format, and data table allows filtering in the i part of df1[ i, j, k], grouping in the k part, and pulling in the j part.
library(data.table)
library(magrittr)
setDT(df1)

melt(df1, 'group') %>%
  .[, .(n = uniqueN(group)), value] %>%
  .[n > 1, unique(value)]

# [1] 1 4


text:
Q: How to show errors from Web Service in Mule instead of Mule's error messages For example if I make a wrong post/put directly to the web service it will give me this :
<prestashop>
   <errors>
      <error>
         <message><![CDATA[Internal error. To see this error please display the PHP errors.]]></message>
      </error>
   </errors>
</prestashop>

But if I pass by Mule ESB the error doesn't help me at all or the other developpers.
500 Internal Server Error
Unexpected character (R) at position 0.
Response code 404 mapped as failure. Message payload is of type: BufferInputStream

Here's my flow in Mule
<http:request-config name="HTTP_Request_Configuration_PrestaShop4"  host="host.org/api/customers/#[message.inboundProperties.'http.query.string']" port="port" doc:name="HTTP Request Configuration" protocol="HTTPS">
    <http:basic-authentication username="keyU" password="keyP"/>
</http:request-config>

<flow name="prestaShopUpdateCustomerById">
    <http:inbound-endpoint exchange-pattern="request-response" host="localhost" port="8080" path="prestaShopUpdateCustomerById" doc:name="HTTP"/>
    <logger level="INFO" message="#[message.payloadAs(java.lang.String)]" doc:name="Logger"/>
    <http:request config-ref="HTTP_Request_Configuration_PrestaShop4" path="/" method="PUT" doc:name="HTTP">
        <http:request-builder>
        </http:request-builder>
    </http:request>
</flow>

Is it possible to make Mule show the webservice's error instead of this generic message (this question is both for REST and SOAP webservices).
Thanks

A: Try adding a success-status-code-validator that covers all of the cases (you can then be more specific):
<http:request path="path" method="method" config-ref="requestConfig">
        <http:success-status-code-validator values="0..599"/>
    </http:request>
I hope that helps.

A: Extract Error Payload using MEL #[exception]


text:
Q: Error: Cloning a bare git repository I tried to make a new bare git repository but I get this error:
Max:Git-Projekte max$ git clone --bare . ~/Dropbox/Git-Projekte/Mainpage.git
Cloning into bare repository '/Users/max/Dropbox/Git-Projekte/Mainpage'...
fatal: failed to open '/Users/max/Dropbox/Git-Projekte/./objects': No such file or directory

A: I am not sure if you are using the command the right way:
Man for git-clone says:
"Clones a repository into a newly created directory"
command is:
git clone [--template=<template_directory>]
      [-l] [-s] [--no-hardlinks] [-q] [-n] [--bare] [--mirror]
      [-o <name>] [-b <name>] [-u <upload-pack>] [--reference <repository>]
      [--depth <depth>] [--recursive] [--] <repository> [<directory>]

So maybe you should:
git clone --bare ~/Dropbox/Git-Projekte/Mainpage.git .

?


text:
Q: nbdev_build_lib error with Anaconda3 and windows I am just experimenting with nbdev and was following the tutorial. https://nbdev.fast.ai/tutorial.html
However when I tried the command nbdev_build_lib on the terminal it gives me the following error:
'nbdev_build_lib' is not recognized as an internal or external command,operable program or batch file.
I am on Windows10, python 3.6 and Anaconda3. I also did the install with conda install -c fastai nbdev.
Has anyone seen this error before? If so how did you solve it. Thanks in advance!

A: According to this github issue on nbdev, one possible solution is to install nbdev using pip instead of conda.


text:
Q: AngularJS: How to get properties from arbitrary type? I have somewhat of a complex requirement here (a real head-scratcher)... and I'm not sure on the best way to proceed:
Requirement:
Build a page for managing widgets (CMS content blocks) in MVC5 using AngularJS for the frontend (as per the rest of the admin UI). The problem is that each widget has its own specific set of properties. They all share some properties like Title, IsEnabled, etc.. but an HTML Widget for example will have a BodyContent field and a Slider Widget would have a collection of images, etc..
My first thought was using [UIHint] and Html.EditorFor so that each widget type will have its own markup.. I think that's pretty straightforward, but how could we get the properties from any such arbitrary widget into the AngularJS model?
Example Controller
widgetsApp.controller('widgetController', function ($scope, $http) {
    $scope.emptyGuid = '00000000-0000-0000-0000-000000000000';

    $scope.id = $scope.emptyGuid;
    $scope.title = '';
    $scope.order = 0;
    $scope.enabled = false;
    $scope.widgetType = '';
    $scope.zoneId = $scope.emptyGuid;
    // etc
    // how to get properties of ANY widget type?

Is this even possible? Is there a better solution? Note, I might consider changing the code to use Knockout or some other such framework if it can support my requirements.
Edit
Note that the issue is further complicated because of the fact of needing to then pass such a model back to the server and dealing with it there. In regular MVC controllers, I can use Request.Form to inspect what other values are there, but I'm using Web API and not sure if that's possible there.
Edit 2
Okay, so I think I'm on the right track, but still having issues. Firstly, here's my progress:
I found out about .factory and made a test page like this:

        <button class="btn btn-primary" ng-click="showAllInfo()">Show Info</button>

The above test works beautifully.. however, when I use this sort of code in my real application it fails to work and the reason I believe is because the second controller is injected into the DOM later on.. here's what's happening:
I have a div as follows

and after loading the other details, I load the html for this as such:
$http.get("/admin/widgets/get-editor-ui/" + $scope.model.id).success(function (json) {
    $scope.widgetDetails = $sce.trustAsHtml(json.Content);
});

That works.. I can see my the html controls for my new properties there.. the following snippet is the HTML which is injected into the above div:

            @Html.Label("BodyContent", "Body Content", new { @class = "control-label" })
            @Html.TextArea("BodyContent", null, new { @class = "form-control", ng_model = "model.bodyContent", ui_tinymce = "tinyMCEOptions_BodyContent" })

    <button class="btn" ng-click="test()">Test</button>

When I click, the "Test" button, nothing happens...
I tried to load a controller dynamically via the method outlined at this link: http://www.bennadel.com/blog/2553-loading-angularjs-components-after-your-application-has-been-bootstrapped.htm
It doesn't work. To be honest though, I am new to AngularJS and don't really know all the ins out outs of it.. any help would be great.

A: IF you are just looking to get the properties and their values, then on AngularJS or Javascript side you can just iterate over the object properties to get all the properties defined over the object.
for(var key in obj){
      $scope[key]=obj[key];
 }

Once on scope you can bind it to the view using ng-model.
This approach would get you the data but metadata about the data such as control to render for property need would not work.
For advance scenarios you should try to send metadata about each properties that can help render it on the view.
If ng-model is setup correctly all data would be send to server.
On the server you can use the dynamic keyword as input parameter to webapi method and there should be a similar method to iterate over the payload using key value pair.

A: I ended up changing to KnockoutJS, partly because AngularJS ended up being a bit overkill for my needs, but also because it couldn't handle this situation very nicely (or at least there was no obvious and clean way to do it). My KnockoutJS solution is below:
In the main page, I add an html element:
<fieldset id="widget-details"></fieldset>
An example of arbitrary HTML to be injected:

        @Html.Label("BodyContent", "Body Content", new { @class = "control-label" })
        @Html.TextArea("BodyContent", null, new { @class = "form-control", data_bind = "wysiwyg: bodyContent, wysiwygConfig: tinyMCEConfig" })

Then in my script for the main page, I use the following:
$.ajax({
    url: "/admin/widgets/get-editor-ui/" + self.id(),
    type: "GET",
    dataType: "json",
    async: false
})
.done(function (json) {
    var result = $(json.Content);

    var content = $(result.filter('#widget-content')[0]);
    var details = $('
').append(content.clone()).html();
    $("#widget-details").html(details);

    var scripts = result.filter('script');
    scripts.appendTo('body');

    // ensure the function exists before calling it...
    if (typeof updateModel == 'function') {
        updateModel();
        var elementToBind = $("#widget-details")[0];
        ko.cleanNode(elementToBind);
        ko.applyBindings(viewModel, elementToBind);
    }
})
.fail(function () {
    $.notify("There was an error when retrieving the record.", "error");
});

and when I save, I call this code:
// ensure the function exists before calling it...
if (typeof onBeforeSave == 'function') {
    onBeforeSave();
}

Works really well.


text:
Q: Dependency conflicts, while installing qt via conan I have a problem with installing and using qt via conan.
The actual error looks like below:
WARN: glib/2.58.3@bincrafters/stable: requirement zlib/1.2.11 overridden by qt/5.13.0@bincrafters/stable to zlib/1.2.11@conan/stable
WARN: pcre/8.41: requirement zlib/1.2.11 overridden by glib/2.58.3@bincrafters/stable to zlib/1.2.11@conan/stable
ERROR: Conflict in pcre/8.41
    Requirement bzip2/1.0.8 conflicts with already defined bzip2/1.0.8@conan/stable
    To change it, override it in your base requirements

My conanfile.txt:
[requires]
gtest/1.8.1@bincrafters/stable
boost/1.70.0@conan/stable
jsonformoderncpp/3.7.0@vthiery/stable
qt/5.13.0@bincrafters/stable

[generators]
cmake

[options]
qt:with_mysql=False

I managed to resolve this dependency by adding bzip2/1.0.8@conan/stable to [requires] section, but than my application is missing fonts, that are mandatory:
QFontDatabase: Cannot find font directory /home/<user>/.conan/data/qt/5.13.0/bincrafters/stable/package/82f32da7b204a38af07f00f05f94ebbfd7454b77/lib/fonts.
Note that Qt no longer ships fonts. Deploy some (from https://dejavu-fonts.github.io/ for example) or switch to fontconfig.

This fonts directory is actually missing. Please note, that this project builds and run without such problems on other coworkers, same machines.
The question is - what causes those problems and how to resolve them?

A: The dependencies conflict should be solved by switching to qt/5.13.1@bincrafters/stable, because a lot of dependencies have migrated to conan center.
Regarding the fonts issue, I'm in the process of adding an optional dependancy on fontconfig/2.13.1@conan/stable in the qt recipe. In the meantime, you could try to install system version of fontconfig, rebuild the qt recipe, and check the output to see if has "Fontconfig ............................. yes"


text:
Q: Specify different python version for library // RobotFramework I'm using a proprietary library for traffic generator that working only in 2.7.5-32bit. My system is ubuntu-64bit and all other components are using installed python 2.7.6 (64bit).
Is there any way to configure explicitly for this library to use another version of python?

A: You cannot use multiple versions of python when running a test -- a test runs as a single process.
The only work-around is to run this other library as a server process and access it remotely through the remote library interface.

A: Best way to solve it, it's running Remote Library on virtual machine or on other network device.


text:
Q: convert html to pdf with ExpertPdf HtmlToPdf Converter I need to convert html to pdf with base64 and ephtmltopdf.dll. The conversion went well. But I can not select PDF content after conversion saved file as an image. I need to be able to select text after conversion. I have tried to change configuration suggested in other posts but still not able to make it work.

A: There are 2 types of PDF. Raster pdf, which is essentially an image, and vector pdf. You need to create vector pdf. And the software you are using is html-to-pdf has documentation about it
pdfConverter.PdfDocumentOptions.GenerateSelectablePdf = true;

And you can see an example. Also, see if you are not falling victim of this situation


text:
Q: php: file_get_contents encoding problem My task is simple: make a post request to translate.google.com and get the translation.
In the following example I'm using the word "hello" to translate into russian.
header('Content-Type: text/plain; charset=utf-8');  // optional
error_reporting(E_ALL | E_STRICT);

$context = stream_context_create(array(
    'http' => array(
        'method' => 'POST',
        'header' => implode("\r\n", array(
            'Content-type: application/x-www-form-urlencoded',
            'Accept-Language: en-us,en;q=0.5', // optional
            'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7' // optional
        )),
        'content' => http_build_query(array(
            'prev'  =>  '_t',
            'hl'    =>  'en',
            'ie'    =>  'UTF-8',
            'text'  =>  'hello',
            'sl'    =>  'en',
            'tl'    =>  'ru'
        ))
    )
));

$page = file_get_contents('http://translate.google.com/translate_t', false, $context);

require '../simplehtmldom/simple_html_dom.php';
$dom = str_get_html($page);
$translation = $dom->find('#result_box', 0)->plaintext;
echo $translation;

Lines marked as optional are those without which the output is the same. But I'm getting weird characters...
������

I tried
echo mb_convert_encoding($translation, 'UTF-8');

But I get
ÐÒÉ×ÅÔ

Does anybody know how to solve this problem?
UPDATE:

*

*Forgot to mention that all my php
files are encoded in UTF-8 without
BOM

*When i change the "to" language
to "en", that is translate from
english to english, it works ok.

*I do not think the library I'm using is messing it up, because I tried to output the whole $page without passing it to the library functions.

*I'm using PHP 5

A: First off, is your browser set to UTF-8? In Firefox you can set your text encoding in View->Character Encoding. Make sure you have "Unicode (UTF-8)" selected. I would also set View->Character Encoding->Auto-Detect to "Universal."
Secondly, you could try passing the FILE_TEXT flag, like so:
$page = file_get_contents('http://translate.google.com/translate_t', FILE_TEXT, $context);

A: Try to see this post if it can help CURL import character encoding problem
Also you can try this snippet (taken from php.net)
<?php
function file_get_contents_utf8($fn) {
     $content = file_get_contents($fn);
      return mb_convert_encoding($content, 'UTF-8',
          mb_detect_encoding($content, 'UTF-8, ISO-8859-1', true));
}
?>

A: Accept-Charset is not really that optional. You should specify UTF8 there. Russian characters are not valid in ISO_8859-1


text:
Q: Does there exist any causal explainability tool for NNs? Say I have a neural network which has 1,000,000 parameters built using 100 features and I wish to understand the underlying data-generating process for how the model arrived at each prediction. Simply looking at the value of the node will not provide any information. I am looking to implement a solution that will help to explain the model either by means of a structural causal model (which shows me the causal relationship between endogenous variables) or via an explanation that is comparable to human reasoning. I am opposed to using SHAP values or feature importance tools, not least because it doesn't measure causality, but because values of the importance of features can be skewed by the effect of multi-collinearity. Removing collinearity (for example using PCA) to rectify the skewness leads to reduced interpretability of my variables (contrary to my original task).

A: I am afraid that the question you are asking doesn't have an answer that would be satisfactory for you. Causal inference us used for finding causal relations in noisy data. A neural network is a mathematical function. It is deterministic, so it directly causes the result to be what it is. Everybmuktiplication, by every weight, addition of every bias, every other mathematical transformation has some, deterministic, impact on the result, so it "causes" it. Surely some of the parameters have a greater impact than others, but causality is not about the strength of the relationship.
What you could do is you could build a simpler model that approximates the neural network and using it will allow you to understand better how it works and this is exactly what expandability tools like LIME do.


text:
Q: Changing behavior of "uninitialized local variable" error Consider the following code:
#include "stdafx.h"
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
  int count123;
  for (int c = 0; c < 10; c++)
  {
    count123 += c;
  }

    return 0;
}

Upon compilation I get the warning: warning C4700: uninitialized local variable 'count123' used
I know the reason is declaring count123 but not initializing it.
But if I declare count123 as a global variable as in the code below, the warning disappears.
#include "stdafx.h"
using namespace std;

int count123;
int _tmain(int argc, _TCHAR* argv[])
{

  for (int c = 0; c < 10; c++)
  {
    count123 += c;
  }

    return 0;
}

As far as I know declaring count123 as a global variable would change its scope but how does that remove the warning? Please guide.

A: The global variables are zero initialized (by the way, the same applies to statics variables). THis is why you don't get this message.
Here the standard quote:

8.5/10: Every object of static storage duration is zero-initialized at program startup before any other initialization
  takes place. In some cases, additional initialization is done later.

A: Global variables are initialized by zero always, think of a global pointer, initialized with some random value, and you used it in your code mistakenly.
 Global initialization makes it NULL, so you can check it and use accordingly.

— if it has pointer type, it is initialized to a null pointer;
— if it has arithmetic type, it is initialized to (positive or
  unsigned) zero;

A: Global variables are static storage variables and these are by default zero-initialized. For more information, please see the answer here.

A: The global variables are initialized with zero by default, hence you got no warnings.
You can easily get the draft of C++ standards then read the section 8.5 Initializers:

10
  [ Note: Every object of static storage duration is zero-initialized at program startup before any other initialization takes place. In some cases, additional initialization is done later. —end note ]


text:
Q: Can a simultaneously connect via ssh to a linux server running two network adapters each on a different vLAN? I'm not new to linux but I'm not well versed in networking.
I have one single host (server) which uses systemd-networkd to assign interface names and static IP addresses.
Attached to the VM are two separate virtualized Networking Cards - which represent to different VLANS.  One networking card is within 10.0.40.0/255 and the other within 10.0.1.0/255.
I can initially assign each networking card a static address via systemd network files:
Network card eth0
[Match]
MACAddress=02:c0:1f:2b:12:8d

[Network]
Address=10.0.40.115/24
DNS=10.0.40.1

[Route]
Destination=0.0.0.0/0
Metric=1025

Network card eth1
Match]
MACAddress=ee:95:e5:28:21:4c

[Network]
Address=10.0.1.117/24
DNS=10.0.1.1

[Route]
Destination=0.0.0.0/0
Gateway=10.0.1.1
Metric=1024

The routing table looks like this:
ip route show
default via 10.0.1.1 dev eth1 proto static metric 1024
default dev eth0 proto static scope link metric 1025
10.0.1.0/24 dev eth1 proto kernel scope link src 10.0.1.117
10.0.40.0/24 dev eth0 proto kernel scope link src 10.0.40.115

Initially when rebooting I can access the computer via ssh at 10.0.40.115 and 10.0.1.117, however after about 30 seconds the 10.0.40.115 connection I receive  client_loop: send disconnect: Broken pipe
I'm likely doing something I shouldn't be doing however I'm just wondering if this setup is even possible.  I'm assuming packets get sent from the ssh host back to the client get lost since they don't know what interface to pass back out of.
Thanks for any insight on the issue.


text:
Q: Why does my PolyLine keep drawing from origin (0,0)? I'm creating a RandomWalk program. Most of the program is working as it should, however, there is one major issue.
When the PolyLine is being drawn, it keeps being forced back to the origin (0,0) instead of where the last point was. I've been trying to see what I'm missing/doing wrong, but I can't locate the issue.
Any help would be appreciated; if more info is needed, just ask. Thanks.
Main Class
import javax.swing.*;
import java.awt.*;

public class RandomWalk {
    public static void main (String[] args) {

        // Creating main frame
        JFrame main = new JFrame("RandomWalk - Version 1.0");
        main.setSize(800, 800);
        main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        main.setResizable(false);
        main.setLocationRelativeTo(null);

        // Creating content/container panel
        JPanel container = new JPanel();
        container.setLayout(new BoxLayout(container, BoxLayout.PAGE_AXIS));
        main.setContentPane(container);

        // Creating scene/canvas
        Draw canvas = new Draw();
        canvas.setAlignmentX(Component.CENTER_ALIGNMENT);

        container.add(canvas);

        main.toFront();
        main.setVisible(true);
    }
}

Drawing Class
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Draw extends JPanel {

    // Starting value for i
    public static int i = 1;

    // Increment for line length
    public static int inc = 10;

    // Choose amount of lines/moves
    public static int a = 10000;

    // Arrays for polyline points
    public static int[] xPoints = new int[a];
    public static int[] yPoints = new int[a];

    public Timer timer = new Timer(5, new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            xPoints[0] = 400;
            yPoints[0] = 400;

            if (i < a) {

                double r = Math.random();

                if (r < 0.25) {
                    xPoints[i] = xPoints[i - 1] - inc;
                    yPoints[i] = yPoints[i - 1] - 0;
                    i++;
                } else if (r < 0.50) {
                    xPoints[i] = xPoints[i - 1] + inc;
                    yPoints[i] = yPoints[i - 1] + 0;
                    i++;
                } else if (r < 0.75) {
                    yPoints[i] = yPoints[i - 1] - inc;
                    xPoints[i] = xPoints[i - 1] - 0;
                    i++;
                } else if (r < 1.00) {
                    yPoints[i] = yPoints[i - 1] + inc;
                    xPoints[i] = xPoints[i - 1] + 0;
                    i++;
                }
                repaint();
            }
        }
    });

    public void paintComponent(Graphics g) {

        timer.start();

        g.drawPolyline(xPoints, yPoints, xPoints.length);
    }
}

A: You want to use g.drawPolyline(xPoints, yPoints, i); rather than g.drawPolyline(xPoints, yPoints, xPoints.length);.
This is because if you use xPoints.length, you are telling it to use your entire xPoints and yPoints arrays, even when you haven't initialized xPoints[j] and yPoints[j] for all j > i (and so they are both 0). If you use i as the length, it will only read those arrays up to index i, and all is good.


text:
Q: Multivariable Calculus Help Prove that if the function z is defined implicitly by
$$F( x - az, y -bz ) = 0$$
where F has continuous partial derivatives, then
$$a\frac{\partial z}{\partial x}+b\frac{\partial z}{\partial y} = 1$$
I have a hunch that I must somehow use the Implicit Function Theorem, but I am not exactly sure how to apply it in this case. Any suggestions?

A: Differentiating both sides of the equality $$F( x - az,\, y -bz ) = 0 \tag{1}$$ by $x,$ we have
$$\dfrac{\partial}{\partial{x}}\left( {F( x - az, y -bz )} \right)= 0, \\
\left.\dfrac{\partial{F}}{\partial{t}}\right\vert_{t=x-az(x,\,y)}\cdot \dfrac{\partial{}}{\partial{x}}(x-az(x,\,y))+\left.\dfrac{\partial{F}}{\partial{s}}\right\vert_{s=y-bz(x,\,y)}\cdot \dfrac{\partial{}}{\partial{x}}(y-bz(x,\,y))=0.$$
But
$$\dfrac{\partial{}}{\partial{x}}(x-az(x,\,y))=1-a\dfrac{\partial{z}}{\partial{x}},\\
\dfrac{\partial{}}{\partial{x}}(y-bz(x,\,y))=-b\dfrac{\partial{z}}{\partial{x}}.$$
Hence
$$\left(1-a\dfrac{\partial{z}}{\partial{x}}\right)\dfrac{\partial{F}}{\partial{t}}-b\dfrac{\partial{z}}{\partial{x}}\dfrac{\partial{F}}{\partial{s}}=0 .\tag{2}$$
In the same manner, differentiating $(1)$ by $y,$ we obtain
$$-a\dfrac{\partial{z}}{\partial{y}}\dfrac{\partial{F}}{\partial{t}}+\left(1-b\dfrac{\partial{z}}{\partial{y}}\right)\dfrac{\partial{F}}{\partial{s}}=0. \tag{3}$$
Now you can solve the system $(2),\ (3) .$

A: $DF = (D_{1}F\cdot (1 - a\cdot \partial z/\partial x)+D_{2}F\cdot (-b\cdot \partial z/\partial x), D_{1}F\cdot (-a\cdot \partial z/\partial y) + D_{2}F\cdot (1 - b\cdot \partial z/\partial y)) \equiv 0$
So, this reduces to:
$$\begin{pmatrix} 1 - a \frac{\partial z}{\partial x} & -b\cdot \frac{\partial z}{\partial x}\\
-a\cdot \frac{\partial z}{\partial y} & 1 - b \frac{\partial z}{\partial y}
\end{pmatrix} \cdot \begin{pmatrix} D_{1}F \\ D_{2}F \end{pmatrix} = 0.$$
Now we want the matrix to be non-singular; otherwise $D_{1}F$ and $D_{2}F$ must both be identically zero. Why is this a problem?
Then the determinant is $1 - a\cdot \frac{\partial z}{\partial x} - b\cdot \frac{\partial z}{\partial y} + (ab-ab)\cdot \frac{\partial z}{\partial x}\cdot \frac{\partial z}{\partial y} \equiv 0$. Hence, $a\cdot \frac{\partial z}{\partial x} + b\cdot \frac{\partial z}{\partial y} = 1$.


text:
Q: docker swarm easy rolling update without downtime I have a service with just 1 instance on a docker swarm. It exposes a port to the machine.
I want docker swarm easily apply rolling update without downtime. Right now i am running docker service rm and then docker service create
Using just 1 instance / replica as i am using websockets.
What is best strategy and command i should use for rolling update of single instance with exposed port.

A: I tried the order: start-first with replicas: 1.  With this setup, existing docker container is shutdown prior to startup the new docker container.  So it seem that the order start-first or stop-first doesn't really matter, or the start-first didn't work as desire.
If however I set replicas: 2, then one of the existing docker container will be replaced with a new docker container, then after that one succeeds then the second docker container is replacing the other existing docker container

A: A way to achieve this is to use order:start-first in the update_config section of the docker service in the compose file. which will start a new container before terminating the old one when you are applying rolling update or deploying a newer version.
you can check here for more details about update_config :https://docs.docker.com/compose/compose-file/compose-file-v3/


text:
Q: Add class to marker on click On Google Maps I would like to add a class to the marker when clicking on it.
I've searched the API but I can't find a solution.
Do you have any leads?

A: Use addListener:
var marker = google.maps.Marker({
    position: geolocation
});

google.maps.event.addListener(marker, 'click', function() {
    // your code
});

A: in fact, at this level I do not have to worry, but the concern is how to add a class marker.
thank you
google.maps.event.addListener(marker, "click", function (e) {
    var curMarker = this;
    console.log( curMarker );
    curMarker.class = "myClasse"; // Exemple
});

butit does not work

A: google.maps.event.addListener(marker, 'click', function() {
    marker.set("class", "className");
});

u can also do this while creating a marker
marker = new google.maps.Marker({
    position: new google.maps.LatLng(lat, lng),
    map: map,
    class:'className'
    draggable: true
});


text:
Q: Erro de sintaxe - parse_url(getenv("CLEARDB_DATABASE_URL")); Estou tentando conectar o banco de uma aplicação em PHP no herokuapp usando o ClearDB e simplesmente recebo um erro de sintaxe na linha 6 do código e eu não sei exatamente o porquê disso. A aplicação não funciona, somente se eu colocar host, senha e username diretamente, o que não é possível pois a aplicação se encontra no git também.
Segue o código:
    <?php

class Database {

    private $url = parse_url(getenv("CLEARDB_DATABASE_URL"));
    private $host = $url["host"];
    private $db_name = substr($url["path"], 1);
    private $username = $url["user"];
    private $password = $url["pass"];
    public $conn;

    public function getConnection() {

            $this->conn = null;

            try {
                $this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
            } catch (PDOException $exception) {
                echo "Connection error: " . $exception->getMessage();
            }

            return $this->conn;
    }
}

?>

A: Propriedades de objetos devem ser instancias com valores simples definidos em tempo de compilação e não determinados em 'tempo de execução' como chamadas de funções e outros tipos de expressões.
class Database {
   private $url = parse_url(getenv("CLEARDB_DATABASE_URL"));

Jogue essa inicialização no construtor da classe:
public function __construct(){
    $this->url =  parse_url(getenv("CLEARDB_DATABASE_URL"));
    $this->host = $this->url["host"];
    $this->db_name = substr($this->url["path"], 1);
    $this->username = $this->url["user"];
    $this->password = $this->url["pass"];
}

Propriedade - Manual


text:
Q: Redirect a user after the headers have been sent I understand that so long as data has been sent to the browser then the headers cannot be modified.
Is there any way (using PHP) that I can perform a redirect to take a user to another page (obviously not using headers)
If so could you please point me to some documentation?

A: I assume output buffering is not an option, since you mention that data has been sent. Use meta redirects, or output JavaScript that takes care of this.
The former could be implemented by adding the following to the <head> section
<meta http-equiv="refresh" content="0; url=http://example.com/">

For the latter, writing something like the following could help:
<script type="text/javascript">
    window.location = "http://example.com/";
</script>

Replace http://example.com/ with your target URL. Note that the latter might be more wieldly to implement if some data has indeed been sent.
A caveat: Both these methods can be blocked at the client end, but technically, so can 301 and 302 redirects.

A: You can use Javascript or a Meta tag. But if you do not want to fix your code to display output after processing then just turn on output_buffering in the .htaccess file for the site.
php_flag output_buffering on
Is what you would put in your .htaccess file to turn that on. It will allow redirects even if you output stuff while processing. This is because the output buffer saves the buffer to the end, so no data is sent prior to.

A: Decided to write my own php function which implements a javascript redirect. See the code below.
function redirect($url)
{
    $string = '<script type="text/javascript">';
    $string .= 'window.location = "' . $url . '"';
    $string .= '</script>';

    echo $string;
}

A: Maybe you can use the output buffer before you make a decision to redirect the page.
IMHO otherwise there is only the way to use HTML meta redirect or JavaScript redirect.

A: This is the php function i use to redirect. If headers haven´t been sent, uses "header(location)", else, uses javascript function.
 function redirect($url)
{
    $baseUri=_URL_;

    if(headers_sent())
    {
        $string = '<script type="text/javascript">';
        $string .= 'window.location = "' . $baseUri.$url . '"';
        $string .= '</script>';

        echo $string;
    }
    else
    {
    if (isset($_SERVER['HTTP_REFERER']) AND ($url == $_SERVER['HTTP_REFERER']))
        header('Location: '.$_SERVER['HTTP_REFERER']);
    else
        header('Location: '.$baseUri.$url);

    }
    exit;
}

A: PHP doe not offer any other way as far as I remember (limitation of the http protocol), but you can do this with javascript, but it is a completely different process : with js, it is the content of the page that tells the browser to perform a redirection, not the server.

A: In my case worked
ob_start
Javascript solution looks so.. strange


text:
Q: Create a data frame from a text file with a defined width I have quite a large file, For simplicity say it has 5 columns and 100 rows.
The width of each column is 8 characters long. The eight characters are either numerals, text or tab space.
For example: (this without the '|' character)
|Header 1|Header 2|Header 3|Header 4|Header 5|
|0.123456|A word\t|   word |etcetcet|Lastone |
...

where \t is a tab character which fills in the remaining characters of the column
I want to bring this file into R as a data frame. Tell me, what are my options
I currently receive this error:
> test<-read.table(base, header = T)
Error in scan(file, what, nmax, sep, dec, quote, skip, nlines, na.strings,  :
  line 1 did not have 6 elements
In addition: Warning message:
In read.table(base, header = T) :
  incomplete final line found by readTableHeader on 'test.txt'


text:
Q: How to derive the long range behavior of XY model? In a lecture note (Lec 23) by Sachdev (https://canvas.harvard.edu/courses/76589/files/folder/Lectures?), he considers a model
$$Z=\int D\theta(x)\,exp(-\frac{K}{2\pi}\int d^{2}x\,(\nabla_x\theta)^2),$$ and defines an order parameter $\psi(x)=e^{i\theta(x)}$, then calculate the correlation function
$$<\psi(x)\psi^{*}(0)>=exp(-\frac{\pi}{K}\int^{\Lambda}\frac{d^{2}k}{4\pi^2}\frac{1-cos(k\cdot x)}{k^2}),$$ and when $|x|\to\infty$,above equation approximates to
$$<\psi(x)\psi^{*}(0)>\approx exp(-\frac{1}{2K}ln(\Lambda|x|))=1/(\Lambda|x|)^{1/(2K)}.$$
1. How to write down such long range behavior, and it seems that this power law decay behavior is very strange, since the power depends on the tunable interaction parameter K.
2. Is it possible to write down the scaling dimension of $\psi(x)$? Then it is easy to write down the long range behavior, say, we know that if $[\phi]=\frac{d-2+\eta}{2}$, then $$<\phi(x)\phi(0)>\sim 1/r^{d-2+\eta}.$$


text:
Q: Updating firebase database (iOS, swift) with multiple fields without overriding existing data This has been answered with reference to updating single fields but not multiple fields.
When a user registers in my app I write to firebase database a list of fields. The root of the firebase database is users and each user node is a specified unique username.
-users
     -username
        "name"
        "title"
        "date of birth"
        "location"
        "about"
        "height"

In UpdateDetailsController is a user update page where they can update some of these fields:
 let key = model.ref.child("users").child(currentLoggedInUser).key

     let post = [
                        "name": name.text!,
                        "title": title.text!,
                        "about": about.text! ]
            let childUpdates = ["\(key)": post]

            model.ref.updateChildValues(childUpdates)

While the username remains the same using ref.updateChildValues(childUpdates) overrides the whole node so it looks like:
 -users
         -username
            "name"
            "title"
            "about"

Advice would be appreciated!
Thx.

A: Try:
model.ref.child(key).updateChildValues(post)


text:
Q: Proper alignment of select boxes in a line I need to put equal space between three select dropdown boxes (left aligned, center aligned and right aligned).
I am using some pre-defined templets with the following CSS:
.view-display-id-page .views-widget-filter-tid {
  float: left;
  margin: auto;
  width: 30%;
}

.view-display-id-page .views-widget-filter-tid_1 {
  float: left;
  margin: auto;
  width: 30%;
}

.view-display-id-page .views-widget-filter-tid_2 {
  float: left;
  margin: auto;
  width: 30%;
}

I am just wondering what else can I add to the CSS to make it work?

A: margin:auto won't work on a float. Add a specific margin to the center item:
.view-display-id-page .views-widget-filter-tid_1 {
  float:left;
  margin: 0 5%;
  width:30%;
}

A: Here is my code. First centre all the three elements and then add equal left nd right margin to the centre dropdown box
 <html>
<style type="text/css">
/** all the three elements are centred*/
    .main
    {width: 400px;
        height: 100px;
        text-align: center;
        margin: 200px auto 20px auto;}
 /** provide the necessar spacing you need**/
    .centre{margin: 0px 50px 0px 50px;}

    </style>

<body>
<form>

    <div class="main">
   <select class="left">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="opel">Opel</option>
  <option value="audi">Audi</option>
</select>
    <select class="centre">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="opel">Opel</option>
  <option value="audi">Audi</option>
</select>
    <select class="right">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="opel">Opel</option>
  <option value="audi">Audi</option>
</select>
        </div>
    </form>
    </body>

</html>


text:
Q: R: what does it mean by a file being "free formatted" or "fixed formatted"? A website says that

Importing free formatted (delimited) data files using the read.table
  function
The read.table function is very useful when reading in ASCII files that contain rectangular data.

Before reading it, I thought that a free formatted file could contain any thing however organized or unorganized, and ASCII files that contained rectangular data were fixed formatted.
So I wonder what a file being "free formatted" or "fixed formatted" mean?
Thanks!

A: I fould some definitions from this guide:

Delimited, free-format ASCII Files
allow variable field lengths-- each
field is separated by a field delimiter.
Columnar, fixed-format ASCII
Files have fixed field lengths-- data is arranged in columns. Every
record fits into a standard form, so field delimiters are not
required.

So in my opinion each free-formatted file is a delimited file and fixed-formatted is a fixed width file.


text:
Q: A specific way of getting neutral narration endings? There are 12 endings - 3 different narrations for each of the 4 choices... What exactly changes this?
Killing enemies? How many do you need to kill to get the neutral ending? What about "innocents"? Notable NPCs?
How do the quests factor into this (saving people, defusing the bomb near the start)? Dialogue? Does being an a****** factor into this?
I already got the good narrations, so you can drop spoilers here and there.

A: There are four separate endings based on what you choose at the end:

*

*"It was something in the water": follow Bill Taggart's ending and cover up the truth, blaming Neuropozyne poisoning as the reason for everything that happened

*"Terrorists did it": follow David Sarif's request and blame Humanity Front

*"I want to believe": follow Hugh Darrrow's request and reveal the truth about what happened to the public

*"The truth is out there": blow it all up by activating the self destruct mechanism aboard Panchaea

Additionally, the narration changes based on how you played the game:

*

*Evil ending: If you murdered everybody, Jensen will talk about abuse of power

*Neutral ending: If you killed a few people, Jensen will talk about how he tried to do the right thing

*Good ending: If you succeeded at pacifist, Jensen will talk about how the detractors of transhumanisation are wrong in their beliefs

If you're specifically after the neutral endings, don't go crazy with killing people. I'm not sure there are any actual figures available for how many people you have to kill before you're classified as evil, but not purposely going out and murdering everything I saw was how I got the neutral endings.

A: Actually I've got neutral ending after killing every killable NPC I've found, except for 'has to survive' quest-related NPCs, which I've killed after receiving quest reward.
Maybe my methods were wrong? I've mostly gone delicate takedown to get 'merciful soul' and keep quiet, then nailed 'em with silenced pistol. For me it's a really evil playthrough.
Or maybe being bad in-quest boy is required to become indepth evil?


text:
Q: gerrit query - get latest commit hash for repo I am using automation to pull always ref/master from the project
Is there an option to query gerrit to have information about last merged commit (getting only HASG also acceptable) ?
Using git log is not an option

A: The way I found is to query gerrit, the query is :
[gerritURL]/a/projects/[gerritProject]/branches/[gerritBranch]

Using python:
query =[gerritURL]/a/projects/[gerritProject]/branches/[gerritBranch]
changes = rest.get(query)


text:
Q: Java Interfaces and Templates Confusion I was reading through some questions on the differences between templates in some different programming languages. I understand that thanks mostly to this questions: What are the differences between Generics in C# and Java... and Templates in C++?. I did however get a little bit confused towards the end of the accepted answer when he starting talking about interfaces and when adding something. I understand the generals of interfaces mostly from this question: Explaining Interfaces to Students. I was still confused by what was stated in the question. So can someone better explain this last portion:

Because of this, the C++ compiler places no restrictions on what you can do with  templates - basically any code you could write manually,
  you can get templates to write for you. The most obvious example is
  adding things:
In C# and Java, the generics system needs to know what methods are
  available for a class, and it needs to pass this down to the virtual
  machine. The only way to tell it this is by either hard-coding the
  actual class in, or using interfaces. For example:
string addNames( T first, T second ) { return first.Name() +
  second.Name(); }
That code won't compile in C# or Java, because it doesn't know that
  the type T actually provides a method called Name(). You have to tell
  it - in C# like this:
interface IHasName{ string Name(); }; string addNames( T first, T
  second ) where T : IHasName { .... }
And then you have to make sure the things you pass to addNames
  implement the IHasName interface and so on. The java syntax is
  different (), but it suffers from the same
  problems.
The 'classic' case for this problem is trying to write a function
  which does this
string addNames( T first, T second ) { return first + second; }
You can't actually write this code because there are no ways to
  declare an interface with the + method in it. You fail.
C++ suffers from none of these problems. The compiler doesn't care
  about passing types down to any VM's - if both your objects have a
  .Name() function, it will compile. If they don't, it won't. Simple.

I really want to understand the code in this answer as I was very confused how the .Name() method would work in the IHasName interface. Is someone has a better example that can further explain how interfaces can be used to add something like a name to a Person class or something else...
EDIT: I am more interested in the Java code.

A: The reason that '+' compiles in C++ is that C++ templates are (and C++ experts PLEASE PLEASE forgive me for my clumsiness) like huge macros.  It will wait until the template is instantiated to check if every operation is possible (still in compile time, as foo warned me in their comment).
For example this code:
#include "stdafx.h"

#include <stdio.h>

#include <vector>
#include <iostream>

template <class T> class adder {
public:
    adder();
    T add(T t1, T t2);
};

template <class T> adder<T>::adder() {}

template <class T> T adder<T>::add (T t1, T t2) {
        return t1 + t2;
}

using namespace std;

typedef vector<int> int_vector;

int _tmain(int argc, _TCHAR* argv[])
{

    adder<int_vector> vector_adder;
    int_vector v1;
    int_vector v2;

    v1.push_back(1);
    v1.push_back(2);

    v2.push_back(3);
    v2.push_back(4);
    v2.push_back(5);

    // will fail here, in compile time!
    int_vector v3 = vector_adder.add(v1, v2);

    for (int_vector::iterator it = v3.begin(); it != v3.end(); it++) {
        cout << *it;
    }

    return 0;
}

Will work perfectly until I try to add two vectors; in that moment, the C++ compiler will realize that there is no overload for the actual type I am using in the template.  However, I could have defined some other operations in the template and the compiler would have not realized if I had not tried to add the actual types (then it will try to solve the macro).  However something like adder<int> would perfectly work.
Java would not allow you to get to that point since it will allow no real operation with the generic types (it is great to define generic contains such as the classes under java.util.*, but little else).  Your best shot is to go for a bounded type generic just like in the java documentation:
public class NaturalNumber<T extends Integer> {

    private T n;

    public NaturalNumber(T n)  { this.n = n; }

    public boolean isEven() {
        return n.intValue() % 2 == 0;
    }

    // ...
}

Here you can restrict the type of the generic to a certain super-class and there do some operations with it.

A: C++ Templates are very much different. But I don't understand why Java's generics can't do what you quote there.
interface IHasName {
    String getName();
}

class Person implements IHasName {
    private final String name;
    public Person(String name) {
        this.name = name;
    }

    @Override
    public String getName() {
        return name;
    }
}

class GenericUtility {
    public static <T extends IHasName> String addNames(T first, T second) {
        return first.getName() + ", " + second.getName();
    }
}

class Main {
    public static void main(String[] args) {
        Person first = new Person("Peter");
        IHasName second = new IHasName() {
            @Override
            public String getName() {
                return "John";
            }
        };
        String result = GenericUtility.addNames(first, second);
        System.out.println(result);
    }

}

Prints
Peter, John

And I would consider that as working as intended.

You can't actually write this code because there are no ways to declare an interface with the + method in it. You fail.

Java does not allow to override the + operator based on the parameter types. There is no fail here because you would have to take a different approach (that could be written as interface) in the first place.

C++ suffers from none of these problems. The compiler doesn't care about passing types down to any VM's - if both your objects have a .Name() function, it will compile. If they don't, it won't. Simple.

Neither will Java. If you declare that the generic parameter has to extend / implement a certain interface you'll get a compile time error in case a parameter does not.


text:
Q: Apache Mod_Rewrite I'm struggling writing a .htaccess file to basically map the following domains:

*

*dev.domain.com/$1 => index.php/dev/$1

*api.domain.com/$1 => index.php/api/$1

*domain.com/$1 => index.php/front/$1

*www.domain.com/$1 => index.php/front/$1
At the moment, everything is mapping to index.php/$1 with the following configuration:
<IfModule mod_rewrite.c>
    RewriteEngine on

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-f

    RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>

This is what came with the php framework I'm using by default. Any help would be greatly appreciated :-) Thanks!

A: If you want to map the requested paths based on the domain name, then you can use an additional RewriteCond and match the HTTP_HOST first.
You will have to multiply your block of existing RewriteConds and the RewriteRule for each domain - except for the last pair which could just be a default:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{HTTP_HOST} ^dev\.domain\.com
RewriteRule ^(.*)$ index.php/dev/$1 [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{HTTP_HOST} ^api\.domain\.com
RewriteRule ^(.*)$ index.php/api/$1 [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php/front/$1 [L]

Not tested. But see also the article on serverfault Everything You Ever Wanted to Know about Mod_Rewrite Rules but Were Afraid to Ask?, which explains the interactions between conditions and rewrite rules.


text:
Q: I want to learn how to help or contribute to Unity
Possible Duplicate:
How to start contributing to Unity?

I am a college student studying computer science and would one day like to work on operating systems.  The part of ubuntu that really interests me is Unity and I would like to study it and possibly contribute to it.
I was reading the wiki pages about it and it was saying to get a copy of all the required components and then start hacking.  Would it be wise to do this in a virtual machine with ubuntu on it?  Do you have any advice on a good place to start?  Do you know of any common pitfalls?  Should I also post in the irc for this?
Thanks


text:
Q: How To Implement Shared Behavior Between Classes (Without Multiple Inheritance Of Course) in C# UPDATE:
So pretty much everyone here has told me that I just need to start all over again on how I designed my classes (thank you folks for your excellent answers by the way!).  Taking the hint, I started doing extensive reading on the strategy pattern.  I want to create behavior classes (or strategy classes) that inherit from an abstract base class or classes.  The Candidate class would then have properties w/ the different abstract base class/classes as the Type for the behaviors or strategies.  maybe something like this:
public abstract class SalaryStrategy {
    public abstract decimal Salary { get; set; }
    public abstract decimal Min { get; set; }
    public abstract decimal Mid { get; set; }
    public decimal CompaRatio {
        get {
            if (this.Mid == 0) { return 0; }
            else { return this.Salary / this.Mid; }
        }
    }
}

public class InternalCurrentSalaryStrategy {
    public override decimal Salary { get; set; }
    public override decimal Min {
        get { return this.Salary * .25m; }
        set { }
    }
    public override decimal Mid { get; set; }
}

public class Candidate {
    public int Id { get; set; }
    public string Name { get; set; }
    public SalaryStrategy CurrentSalaryStrategy { get; set; }
}

public static void Main(string[] args) {
    var internal = new Candidate();
    internal.CurrentSalaryStrategy = new InternalCurrentSalaryStrategy();
    var internalElp = new Candidate();
    internalElp.CurrentSalaryStrategy = new InternalCurrentSalaryStrategy();
    var elp = new Candidate();
    // elp.CurrentSalaryStrategy can stay null cause it's not used for elps
}

Any comments or suggestions?

ORIGINAL Question:
I am trying to learn and become more proficient at design patterns and principles.  I have am currently working on a design for few classes that has stumped me.  Here's a very condensed version of the code:
public class Candidate {
    public int Id { get; set; }
    public string Comments { get; set; }
    // lots more properties and behaviors...
}

public class InternalCandidate : Candidate {
    public decimal CurrentMid { get; set; }
    public decimal CurrentMax {
         get { return this.CurrentMin * 1.3m;
    }
    // lots more properties and behaviors...
}

public class EntryLevelCandidate : Candidate {
    public string Gpa { get; set; }
    // lots more properties and behaviors...
}

public class InternalEntryLevelCandidate /* what do I inherit here??? */ {
    // needs all of the properties and behaviors of
    // EntryLevelCandidate but also needs the CurrentMin and
    // CurrentMax (and possibly more) in InternalCandidate
}

The InternalEntryLevelCandidate class is primarily an EntryLevelCandidate but needs to share some of the implementations of InternalCandidate.  I say implementations because I don't want the implementations to be different or repeated, otherwise I would use an interface for common contracts and have concrete implementations in each class.  Some of the implementations of the InternalCandidate properties and behaviors need to be common or shared.  I have read about C++ and Ruby mixins, which seem to be something similar to what I want to do.  I also read this interesting blog post that discusses an idea for a behavior type where a class would be able to inherit multiple behaviors while still maintaining a single "is a" relationship: http://www.deftflux.net/blog/post/A-good-design-for-multiple-implementation-inheritance.aspx.  This seems to convey what I am wanting.  Can anyone give me some direction on how I can accomplish this using good design practices?

A: Immutable data value classes.  If any properties in your various Candidate subclasses represent some kind of meaningful data value, create an immutable class for it, with the behaviors you need.  Each of your distinct Candidate subclasses can then use the data type, but your code is still encapsulated in the data classes.
Extension methods.  These could be overloaded to work with any classes.
I'd avoid the decorator pattern and stick with compiled/reflectable functionality.
Composition.  Develop the unique behaviors in separate classes right away, and build your Candidate classes around them, rather than writing unique behaviors in your Candidate classes and trying to pull out their functionality for use in related classes later.
Depending on how you use the classes, you could also implement and make use of explicit and implicit conversion operators to a related type, so instead of reimplementing interfaces (which you wanted to avoid), you could actually cast your object into the type/implementation you need for whatever purpose.
Another thing I just thought of, related to that last paragraph, is to have a leasing system, where your class spawns and object of the appropriate type, allows it to be manipulated, then consumes it later to assimilate the updated information.

A: Here's a scholarly paper on the subject that I think is pretty interesting (PDF link).
But, I think you are trying to impose business logic in your generalizations.  You happen to know that an InternalCandidate will never have his GPA looked at.  But, an InternalCandidate certainly has a GPA.  So, you have cracked out this strange guy called an InternalEntryLevelCandidate because you happen to know that you want to look at this guy's GPA.  Architecturally, I think the EntryLevelCandidate is incorrect.  I would add a "Level" concept to a Candidate and give him a GPA.  It's up to the business logic to decide if they look at the GPA or not.
Edit:  Also, Scott Meyers does a great job of dissecting this issue in his books.

A: Disclaimer:
In my experience needing multiple inheritance is the exception rather than the rule, careful design of class hierarchies can usually avoid needing this feature. I agree with JP that this requirement could be avoided in your sample.
Back to the question, there is no clean solution, however you have a few options:

*

*Use extension methods, has the disadvantage that right click Resolve does not works, also some people really dislike these puppies.

*Create an aggregate object that holds and instance of each class you want composited, re-implement stub methods that delegate.

*Define an interface for each behavior and have the methods in the base check if this is IInterface before executing the behavior. (allows you to pull behavior definitions to the base)
Near duplicate:
Multiple inheritance in C#

A: I agree that inheritance doesn't seem to be the right thing here.  I'm not sure that I know the perfect answer, but perhaps the Decorator pattern is appropriate.
Another, more esoteric idea is to think about aspect-oriented programming.  You can do some pretty amazing things with aspects, but it's a very advanced topic that I still haven't mastered.  The kind of folks who have are like Rikard Oberg and his Qi4J cohorts.

A: I'd just use the Delegation pattern. Ultimately I'd use an interface for each distinct piece of functionality, then have a concrete class as a delegate for each interface. Then your final classes just use the delegates they need and can inherit from multiple interfaces.
public class InternalEntryLevelCandidate : EntryLevelCandidate {
    private  InternalCandidate internalCandidateDelegate
        = new InternalCandidate();

    public decimal CurrentMid {
        get { return internalCandidateDelegate.CurrentMid; }
        set { internalCandidateDelegate.CurrentMid = value; }
    }

    public decimal CurrentMax {
        get { return internalCandidateDelegate.CurrentMax }
    }
}


text:
Q: Not able to connect to AKS Cluster from GitLab Please help me here, I am not able to login to AKS Cluster from GitLab.
I am getting the below error.

I have tried to connect to AKS Cluster, by creating GitLab Agent.
But still I am not able to login.