text:
Q: Angular 2 : How to include a component from one running Angular project to another Angular project? I have two projects both developed in Angular 2, let say first project is test-core and second project is test-sail. Both the project structures have been created using Angular-cli.
test-core structure:

test-sail structure:

If you look at the app.module.ts in the test-sail, where we are importing AppComponent of test-sail, I want to import AppComponent of test-core and I was doing something like this (after running both the application on the local server):
import { AppComponent } from 'http://localhost:4200/test-core/src/app/app.component';

but this didn't work. If I directly hit that url it works.
Is it possible to load a component from one Angular project to another. If yes please help me out.
Thanks in advance.

A: I think the simplest way would be to copy/paste the directory in your new angular project.


text:
Q: python oauth 2.0 new fbsr facebook cookie, error validating verification code I'm trying to use the new fbsr_{{appID}} cookie.
I'm using the following functions to parse it, but when I try to get the access_token afterwards, I get 'error validating verification code' message. Is something wrong with these parsing functions? If not, what could be the problem?
more info:
I managed to log users in without cookies using the oauth link which redirects back into my site with the code as a parameter, so it can't be the app id, app secret or the redirect_uri. Another reason is that these have different error messages.
def base64_url_decode(inp):
    padding_factor = (4 - len(inp) % 4) % 4
    inp += "="*padding_factor
    return base64.b64decode(unicode(inp).translate(dict(zip(map(ord, u'-_'), u'+/'))))

def parse_signed_request(signed_request, secret):

    l = signed_request.split('.', 2)
    encoded_sig = l[0]
    payload = l[1]

    sig = base64_url_decode(encoded_sig)
    data = json.loads(base64_url_decode(payload))

    if data.get('algorithm').upper() != 'HMAC-SHA256':
        logging.error('Unknown algorithm')
        return None
    else:
        expected_sig = hmac.new(secret, msg=payload, digestmod=hashlib.sha256).digest()

    if sig != expected_sig:
        return None
    else:
        logging.debug('valid signed request received..')
        return data

args = {}
args['client_id'] = fbapp_id
args['redirect_uri'] = site_url
args['client_secret'] = fbapp_secret
args['code'] = code
response = urllib.urlopen('https://graph.facebook.com/oauth/access_token?'+urllib.urlencode(args))
# ... here i'm getting the error back from the server: error validating verification code...

A: There is a modified version of the facebook python SDK which supports OAuth 2.0 and parsing of the fbsr_ cookie on github here:
https://gist.github.com/1190267
You can look into the code to see how to parse the cookie or just let that file do the work for you.

A: I had to programetically expire the cookie for my logout to work. The link from facebook does not work but the serverside oauth can do logout without javascript:
class LogoutHandler(webapp2.RequestHandler):
    def get(self):
        self.set_cookie("fbsr_" + facebookconf.FACEBOOK_APP_ID, None, expires=time.time() - 86400)
        self.redirect("/")
    def set_cookie(self, name, value, expires=None):

        if value is None:
            value = 'deleted'
            expires = datetime.timedelta(minutes=-50000)
        jar = Cookie.SimpleCookie()
        jar[name] = value
        jar[name]['path'] = '/'
        if expires:
            if isinstance(expires, datetime.timedelta):
                expires = datetime.datetime.now() + expires
            if isinstance(expires, datetime.datetime):
                expires = expires.strftime('%a, %d %b %Y %H:%M:%S')
            jar[name]['expires'] = expires
        self.response.headers.add_header(*jar.output().split(': ', 1))

Could you update your question to tell us how it went and how we handle the cookies. For facebook-oath, did you get logout to work? I had to add a cookie handling and a logout handler for this to work for me but now after much troubleshooting it works. I login like this:
class OAuthHandler(I18NHandler):
    def get(self):
      args = dict(
        code = self.request.get('code'),
        client_id = facebookconf.FACEBOOK_APP_ID,
        client_secret = facebookconf.FACEBOOK_APP_SECRET,
        redirect_uri = 'http://www.koolbusiness.com/oauth',
      )
      file = urllib.urlopen("https://graph.facebook.com/oauth/access_token?" + urllib.urlencode(args))
      try:
        token_response = file.read()
      finally:
        file.close()
      access_token = cgi.parse_qs(token_response)["access_token"][-1]
      graph = main.GraphAPI(access_token)
      user = graph.get_object("me")
      self.response.out.write(user["id"])
      self.response.out.write(user["name"])

def get(self):
    fbuser=None
    profile = None
    access_token = None
    accessed_token = None
    if self.request.get('code'):
      args = dict(
        code = self.request.get('code'),
        client_id = facebookconf.FACEBOOK_APP_ID,
        client_secret = facebookconf.FACEBOOK_APP_SECRET,
        redirect_uri = 'http://'+self.get_host()+'/',
      )
      logging.debug("client_id"+str(args))
      file = urllib.urlopen("https://graph.facebook.com/oauth/access_token?" + urllib.urlencode(args))
      try:
        logging.debug("reading file")
        token_response = file.read()
        logging.debug("read file"+str(token_response))
      finally:
        file.close()
      access_token = cgi.parse_qs(token_response)["access_token"][-1]
      graph = main.GraphAPI(access_token)
      user = graph.get_object("me")   #write the access_token to the datastore
      fbuser = main.FBUser.get_by_key_name(user["id"])
      logging.debug("fbuser "+fbuser.name)

      if not fbuser:
        fbuser = main.FBUser(key_name=str(user["id"]),
                            id=str(user["id"]),
                            name=user["name"],
                            profile_url=user["link"],
                            access_token=access_token)
        fbuser.put()
      elif fbuser.access_token != access_token:
        fbuser.access_token = access_token
        fbuser.put()

    current_user = main.get_user_from_cookie(self.request.cookies, facebookconf.FACEBOOK_APP_ID, facebookconf.FACEBOOK_APP_SECRET)
    if current_user:
      graph = main.GraphAPI(current_user["access_token"])
      profile = graph.get_object("me")
      accessed_token = current_user["access_token"]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Можно ли в C# присвоить создаваемому элементу стиль из словаря ресурсов (файла стиля wpf)? Например, я могу программно присвоить цвет заливки, могу создать программно стиль и присвоить его кнопке... Но, можно ли присвоить элементу стиль из словаря ресурсов?
Пример:
//Создаётся кнопка
Button b = new Button();
//Присваиваем красный цвет
b.Background = SolidColorBrush(Colors.Red);
//Можно ли сделать наподобие следующего?
//b.Style = ???


text:
Q: Which metrics to measure the efficiency of a MapReduce application? I wrote a MapReduce application which run on 6 nodes of computers.
I am sure that my MapReduce algorithm (run on a cluster of computers) outperforms the sequential algorithm (run on a single computer), but I think this does not mean that my MapReduce algorithm is efficiently enough, right?
I have searched around and found: speedup, scaleup, and sizeup metrics. Is it true that we normally consider these metrics when measuring the efficiency of MapReduce application? Is there any metric that we need to consider?
Thank you a lot.

A: Before specifically addressing your question, let's revisit the map-reduce model and see what's the real problem, it tries to solve. You can refer this answer (by me/ of course you can refer other good answers for the same problem), to get an idea of map-reduce model.
So what it really tries to solve? It deduces a generic model that can be applied to solve vast a range of problems that needs to process a massive amount of data (usually in GBs or even Peta Bytes). And the real deal of this model is, it can be easily parallelized and can even be easily distributed the execution among number of nodes. This article (by me) has some detailed explanation of whole model.
So let's go to your question, you are asking about measuring the efficiency of a map reduce program based on speed, memory-efficiency and scalability.
Speaking to the point, the efficiency of a map-reduce program always depend on how far it enjoys the parallelism given by the underlying computational power. This directly indicates that a map-reduce program runs on one cluster may not be the ideal program to run in a different cluster. So we need to have a good idea of our cluster, if we hope to build up our program to a precisely fine-tuned level. But practically its rare some one needs to get it tuned up to that much level.
Let's take your points one by one:

*

*Speed up:
It depends on how you split your input to different portions. This directly deduces the amount of parallelism (in human control). So as I mentioned above, the speed-up directly depends on how your split logic going to be able to utilize your cluster.

*Memory efficiency:
It mostly depends on how memory efficient your mapper logic and reducer logic are.

*Scalability:
This is mostly out of concern. You can see that the map-reduce model is already highly scalable to a level that one would rarely think about an extra mile.
So speaking as a whole, efficiency of a map reduce program is rarely a concern (even speed and memory). Practically speaking the most valuable metric is the quality of its output. i.e. how good your analytic data are. (in place of marketing, research etc.)


text:
Q: The arclength parametrization of $\gamma(t)=(2t,(t-1)^2,3t^3)$ Find the arclength paramztrization of the curve $$\gamma(t)=(2t,(t-1)^2,3t^3), t\in \mathbb R$$

We have $$s(t)=\int_{t_0}^t\|\dot\gamma(u)\|du=\int_{t_0}^t\sqrt{4+4(u-1)^2+(9u^2)^2}du$$
I couldn't calculate it.
Any help is appreciated !

A: I am almost sure that there is a typo in the question. It could be
$$\gamma(t)=(2t,(t-1)^2,3t^\color{red}{2})$$ If this is the case, then
$$L=\int \sqrt{40 t^2-8 t+8}\,dt$$
$$t=\frac {u+1}{10}\implies L=\frac{1}{5 \sqrt{10}}\int\sqrt{u^2+19}\,du$$
$$u=\sqrt{19} \sinh (v)\implies L=\frac{19}{5 \sqrt{10}}\int \cosh^2(v)\,dv$$
Now, this one is very simple. When done, go back to $u$ and then to $t$.


text:
Q: How to insert comments in lightning aura components that are not shown in the generated HTML? The lightning aura component comment syntax common to HTML <!-- comment --> generates a comment also in the generated HTML.
There is a way to insert comments in the source code of the .cmp file of the lightning aura component that does not generate a corresponding comment in the generated HTML?

A: I am not aware of an "official" way to do this but one quick way to accomplish this would be to wrap your comment in an aura:if tag:
<aura:if isTrue="false">Insert comment here</aura:if>
This is pretty hacky but you could easily create a component called "comment" that accomplishes the same thing and would look better like this:
<c:comment>Insert comment here</c:comment>

A: Insert comments using
< !--This is your comment-- >
Remove the space between the < & the ! at the beginning and end.
https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/components_markup.htm


text:
Q: Regex help, find between : text how i can select with regex this: http://prntscr.com/6dfdzf
Example I have:
my dad sees : aqwe kayak at noon : night

and it should give my only:
sees : aqwe, noon:night

A: \S+\s*:\s*\S+

This simple regex should do it for you.See demo.
https://regex101.com/r/eS7gD7/24


text:
Q: sed: unexpected EOF | bash script broken after sed update Given that bash hasn't a native goto function, I stumbled upon this comment here a while ago.
And while I get, this is a messy solution, it worked very well for my use cases - until now. A few days ago I discovered that the script in which a had such jump marks suddenly quits with an error:
sed: 1: "/myjumpmark:/{:a;n;p;ba};": unexpected EOF (pending }'s)
That's strange, as I didn't touch the script in a while. What I instead discovered, is that brew (I'm running the script on macOS) updated gnu-sed to version 4.8 in the past days. That's about the time, the problems started.
Now my question is: Is there any significant change in sed 4.8 that causes my previously functioning script to crash? And if so, what should I try to get it to work again?


text:
Q: Database every row in different div I try to make for every row in my database a different div. It only doesn't work when I  try to run it, it gives me only two letters. I checked my PHP and it works correctly.
var request = new XMLHttpRequest;
request.open('GET' , 'myurl', false);
request.send();
console.log(request);

if (request.status == 0) console.log(request.responseText);

var firstname, lastname;
var obj = JSON.parse(request.responseText);
console.log(obj);

for (var i = 0; i<obj.length; i++){
    firstname = obj[i].Firstname;
    lastname = obj[i].Lastname;

    console.log(firstname,lastname);

    var divElement = document.createElement("div");
    divElement.id = "myDiv";

    divElement.className = "myDivClass";
    divElement.innerHTML = firstname[i] + " " + lastname[i];
    document.body.appendChild(divElement);
}

A: You seem to be writing only the elements based on the loop.
Why are you doing
 divElement.innerHTML = firstname[i] + " " +  lastname[i];

when it needs to be
 divElement.innerHTML = firstname + " " +  lastname;

A: var request = new XMLHttpRequest;
request.open('GET', 'myurl', false);
request.send();
console.log(request);

console.log(request.responseText);
var firstname, lastname;

var obj = JSON.parse(request.responseText);
console.log(obj);

for (var i = 0; i<obj.length; i++) {
  firstname       = obj[i].Firstname;
  lastname        = obj[i].Lastname;

  console.log(firstname,lastname);

  var divElement = document.createElement("div");
  divElement.id = "myDiv";

  divElement.className = "myDivClass";

  divElement.innerHTML = firstname + " " +  lastname;

  document.body.appendChild(divElement);
}

Try this.


text:
Q: Tiny ssd for two OS? I 've got a new hp laptop with windows 10 preinstalled. It has only 128 gb ssd and i want to dual boot it with ubuntu 16.04.Is there enough space for this and if there is how much space should i give to the partitions?
Thank you anyway.
P.S:And something else.Do i have to make a swap partition ?

A: *

*I suggest that you give Ubuntu 28 GB (and leave 100 GB for Windows).

*You need not have a swap partition, if there is 4 GB RAM (or more). But if you have many tabs open in your web browser or do something that needs a lot of RAM, it is a good idea to have a small swap partition, maybe only 1 or 2 GB. You will notice that the computer gets slow - and you can close some tabs in the web browser. You can also run htop to monitor how the memory is used. It is a bad idea to rely heavily on swap on an SSD due to wear, so you should avoid swapping, only use it as a buffer for unusual situations.
-o-

*

*Shrink the Windows partition with Windows tools (when running Windows). Leave the unallocated space.

*Boot from your Ubuntu install drive 'Try Ubuntu'

*Start gparted and create an ext4 partition (to become the root partition '/' of Ubuntu) and a small swap partition.

*Start the installer, and at the partitioning window, select Something else and install Ubuntu into the partitions that you created for it.

*With Windows 10 preinstalled you are running in UEFI mode, and the bootloader will be installed automatically using the already existing EFI partition.

A: Yes this can be done, technically even on 64GB. But it's very tight in space. I'd give windows at least 25GB and Ubuntu at least 12GB. The rest of the room you can assign how you want, based on what OS you'll wat to sore and install most things on. A swap space of a few gigs is always necessary. You could also make a partition out of the rest for shared storage in exFAT. Or buy a >32GB USB and install Ubuntu on that .

A: i have MacBook with 120 GB Flash storage. Mostly Linux needs at least 5 GB and a fresh Windows 10 should take 20 GB hard disk. If you dont have too heavy apps such as Adobe apps, games or Visual Studio with add-ons it will be no harm to spear 20-30 GB space. Currently i am using Ubuntu 16.04 with 38 GB space and i am using only 5.7 GB space.
Filesystem      Size  Used Avail Use% Mounted on
udev            3,9G     0  3,9G   0% /dev
tmpfs           789M  9,5M  780M   2% /run
/dev/sda2        36G  5,3G   29G  16% /
tmpfs           3,9G  564K  3,9G   1% /dev/shm
tmpfs           5,0M  4,0K  5,0M   1% /run/lock
tmpfs           3,9G     0  3,9G   0% /sys/fs/cgroup
/dev/sda5       196M  4,8M  192M   3% /boot/efi
tmpfs           789M  100K  789M   1% /run/user/1000
/dev/sda1        76G   66G   11G  86% /media/egrimo/Egrimo

My main macOS part is sda1 and my bootloader is sda5. Rest is the Ubuntu.

A: 128 GB SSD is plenty for dual boot. Windows 10 requires 16 GB, while Ubuntu 16.04 requires 5 GB. I would set aside 32 GB for Windows and at least 16 GB for Ubuntu.


text:
Q: How to get list of indexes for unique values? Having a list like this
lst = ['a','b','a','c','a','b','b']

I'd like to get lists of indexes for each unique element to get this:
indexes = {
            'a': [0,2,4],
            'b': [1,5,6],
            'c': [3]
          }

This is my current code, but I'm only getting the first index of each element.
indexes= dict()
for el in lst:
    indexes[el] = [lst.index(el)]

>>> indexes
{'a': [0], 'b': [1], 'c': [3]}

Thanks for any help.

A: The problem with you code is you're overriding the same key again and again but with a different list, so your final dictionary contains only a single list.
you can avoid this behavior by using defaultdict.
from collections import defaultdict

lst = ["a", "b", "a", "c", "a", "b", "b"]
lst = [c for c in lst if c.strip()]  # this will remove empty strings

indexes = defaultdict(list)

for index, char in enumerate(lst):
    indexes[char].append(index)

indexes = dict(indexes)
print(indexes)

Output:
{'a': [0, 2, 4], 'b': [1, 5, 6], 'c': [3]}


text:
Q: Identity Map with Mongoose Is there a native way with Mongoose 4.x to maintain a identity map and avoid returning different object instances for the same entity in the DB?
Users.findOne({_id: ObjectId("XXX")}, function(err, user1) {
  if (err) throw err;
  Users.findOne({_id: ObjectId("XXX")}, function(err, user2) {
     if (err) throw err;
     console.log(user1 === user2); // Return FALSE
  });
});


text:
Q: Is the .NET IList<> (generic IList interface) obsolete or not practical? Well I came across a lot of legacy code that uses IList<> in the function signatures but inside works with List<>.
Now only List<> and arrays (int[] implements IList<>) implement IList<>.
ArrayList implements the non generic IList and since generics were introduced there is no point in using boxable/unboxable collections.
List<> down is still has an array implementation. I do not think is there a point in using arrays in C# anymore.
LinkedList<> does not implements IList<>
And if I think back to the C++ STL containers/collections they did not had interfaces too. From design perspective there was no issue in what to use or make it interchangeable. Or you used an iterator, if you wanted interchangeable, here in C# you can use IEnumerable<> if you want and can be flexible and lazy.
I see no reason to change it to an array and I do not think I can write a better collection class than List<>.
Now out of pragmatism how bad would it be if I would replace all the IList<> with List<>?

A:
Now only List<> and arrays (int[] implements IList<>) implement IList<>

Not true.
For example, if you use NHibernate, it has it's own implementation of IList<T> which it uses to represent lists and if I remember rightly, will throw errors if you expose List<T> in a mapped entity.
In general though, exposing the interface, rather than the implementation in your code leaves things more flexible as someone using your code may want to use their custom implementation of IList<T> and forcing them to use List<T> when they don't have to is restrictive.

Using interfaces instead of concrete implementation is considered good practice: it's an integral part of the D in SOLID.

A: People can (and do) make their own implementations of IList<T>.  If you replace all occurrences of IList<T> with List<T>, then you'll break all those uses.
Linked lists can't implement it because they don't allow random access.  I think IList<T> is a good interface, and use it regularly.


text:
Q: CSS fade-in / ease effect on page load I'm looking for the best way to ease-in/fade elements on page load.
I really like how it looks on http://alpha.musicinfo.fi/ when you do a search and the contents kinda slide/fade in.
was wondering how they are achieving it as it's working pretty slick across browsers and mobile.
Thanks!

A: For the simplest animation, you'll want to use CSS3 transitions, which are supported on everything except opera mobile.
transition: top 0.2s ease-in, opacity 0.2s ease-in
-webkit-transition: top 0.2s ease-in, opacity 0.2s ease-in
opacity: 0.0;
position: relative;
top: 20px;

And then with javascript or jQuery you can set the new state on load.
$('#element').css({opacity: 1.0, top: '0px'})

But for the most flexibility and control, you'll want to use jQuery's .animate() function.  Then you can do something like
$('#element').animate({
opacity: '1.0',
top: '0px'
}, 200)
Have the default CSS set to opacity: 0; top: 20px; position: relative;

A: CSS3 animation is probably the easiest and way to accomplish this, but it is not very well supported.  I think your most realistic option, balancing ease of implementation and browser support, would be using the jQuery's .fadeIn() function.

A: Here's another method using jQuery's addClass function.
The example is kind of ugly, but it you get the idea.  Also to smooth things out use CSS3 transitions like transition etc.
Also add more than one class to change to collapse the box.
This is just another method, maybe not the best, but still another way.
Here's the fiddle:
http://jsfiddle.net/GrsXx/


text:
Q: Evaluation of the integral $I=\int_0^{\infty}[1-J_0(kr)]k^{1-\alpha}dk$ How to compute
\begin{equation}
I(r) = \int_0^{\infty}[1-J_0(kr)]k^{1-\alpha}dk,\quad 2<\alpha<4
\end{equation}
where $J_0(x)$ is the zeroth order Bessel function of the first kind.
A paper gives the following result
\begin{equation}
I(r)=cr^{\alpha-2}
\end{equation}
and
\begin{equation}
c = \frac{4\Gamma(3-\alpha)}{\alpha-2}\sin\left(\frac{\pi}{2}(3-\alpha)\right)B(1/2,(\alpha-1)/2)
\end{equation}
with $B(x,y)$ being Beta function.
It seems the above result does not give a defined value for $\alpha=3$.
Can someone show how to evaluate $I(r)$?
Thanks.

A: The first identity just follows from setting $k=\frac{1}{r}u$, so the point is just to compute:
$$ I=\int_{0}^{+\infty}(1-J_0(u))\,u^{1-\alpha}\,du $$
that depends on the Beta function since the Fourier transform of $J_0(u)$ is simply given by $\frac{\mathbb{1}_{(-1,1)}}{\sqrt{1-t^2}}$:
$$I = \frac{1}{\alpha-2}\int_{0}^{+\infty} J_1(u)\,u^{2-\alpha}\,du =\frac{2}{\pi(\alpha-2)}\int_{0}^{1}\int_{0}^{+\infty}\frac{t \sin(st)}{\sqrt{1-t^2}}s^{2-\alpha}\,ds\,dt$$
and since for any $t>0$:
$$ \int_{0}^{+\infty}\sin(st)\,s^{2-\alpha}\,ds = \Gamma(3-\alpha)\cos\frac{\pi\alpha}{2} t^{\alpha-3}$$
by the residue theorem, the Beta function arises from:
$$ \int_{0}^{1}\frac{t^{\alpha-2}}{\sqrt{1-t^2}}\,dt = \frac{1}{2}\int_{0}^{1}z^{\frac{\alpha-3}{2}}(1-z)^{-\frac{1}{2}}\,dz.$$
For $\alpha\geq 4$, the function $(1-J_0(u))\,u^{1-\alpha}$ has a non-integrable singularity in a right neighbourhood of zero, since over there:
$$ 1-J_0(u) = \frac{u^2}{4}-\frac{u^4}{64}+o(u^5).$$
When $\alpha=3$, notice that the zero of the sine function and the pole of the Gamma function cancel out, giving:
$$ \lim_{\alpha\to 3}\Gamma(3-\alpha)\sin\left(\frac{\pi}{2}(3-\alpha)\right) = \frac{\pi}{2}.$$


text:
Q: How to create horizontal and vertical scroll bars How to create horizontal and vertical scrollbars like this page without using any plugin. Here is what I want: Screenshot

A: To do this you will first need to set a fixed height (for vertical scrolling) or fixed width (for horizontal scrolling) on the container.  Then you can use overflow-x and overflow-y to tell the browser how to handle content that extends outside of that width/height. In this case you want to use the scroll option, or auto. scroll means the scrollbars will always be shown, auto means the browser will only show the scrollbars if there is enough content to require it.
.scroll-horizontal {
    overflow-x: auto;
    width: 200px;
}

.scroll-vertical {
    overflow-y: auto;
    height: 200px;
}

A: write this code in the beginning of the HTML.

Now, to enter the scrollable content,

  PUT YOUR SCROLLABLE CONTENT HERE

Note that the scroll bar only appear if the content is long enough to be scrolled.
This is because we have overflow-x: auto; in our code.
You can adjust the size of the content by adjusting the height and width value from 200 px.

A: please try this
elementname {
    overflow-x: scroll;
    overflow-y: scroll;
}

if you want to format a scroll bar then use plugins named 'jScrollPane'
http://jscrollpane.kelvinluck.com/

A: First make sure that you have more content and less space. Using max-width would help. You could do this:

     .container {
         max-height: 400px;
         max-width: 150px;
         overflow: scroll;
     }

     .container img {
         height: 150px;
         width: 200px;
     }

        <img src="data:image/png;base64,[encoded data, 4244 characters]">


text:
Q: Can I create a branch in Perforce based on a historic point in time? I would like to create a branch in Perforce that is based off of some point in the past, i.e. not the current state of the current branch, is this possible?  If so, how?
Here is a picture of what I'm trying to do.  The current branch is in blue, and the new desired branch is shown in green.

A: This will do it:
p4 copy //depot/project/dev/...@release_x_label //depot/project/release_x/...

The command tells Perforce to copy //depot/project/dev/... as of release_x_label to //depot/project/release_x/... You can run this command entirely server side using p4 copy -v. If you don't need a copy of the files locally it's much quicker.
You can do it in one go without needing a submit by using p4 populate
p4 populate //depot/project/dev/...@release_x_label //depot/project/release_x/...

I usually use copy though to make sure I don't have any typos. =)
You can do all of this with streams as well. It's a bit odd in that the revision specifier that you use to choose what to branch from gets put on the target path you're branching to.
p4 populate -rs //stream/dev2 //stream/dev2/...@1

This will populate dev2 from its parent as of changelist1.


text:
Q: C# List<> Sort by x then y Similar to List<> OrderBy Alphabetical Order, we want to sort by one element, then another.  we want to achieve the functional equivalent of
SELECT * from Table ORDER BY x, y

We have a class that contains a number of sorting functions, and we have no issues sorting by one element.
For example:
public class MyClass {
    public int x;
    public int y;
}

List<MyClass> MyList;

public void SortList() {
    MyList.Sort( MySortingFunction );
}

And we have the following in the list:
Unsorted     Sorted(x)     Desired
---------    ---------    ---------
ID   x  y    ID   x  y    ID   x  y
[0]  0  1    [2]  0  2    [0]  0  1
[1]  1  1    [0]  0  1    [2]  0  2
[2]  0  2    [1]  1  1    [1]  1  1
[3]  1  2    [3]  1  2    [3]  1  2

Stable sort would be preferable, but not required. Solution that works for .Net 2.0 is welcome.

A: Do keep in mind that you don't need a stable sort if you compare all members.  The 2.0 solution, as requested, can look like this:
 public void SortList() {
     MyList.Sort(delegate(MyClass a, MyClass b)
     {
         int xdiff = a.x.CompareTo(b.x);
         if (xdiff != 0) return xdiff;
         else return a.y.CompareTo(b.y);
     });
 }

Do note that this 2.0 solution is still preferable over the popular 3.5 Linq solution, it performs an in-place sort and does not have the O(n) storage requirement of the Linq approach.  Unless you prefer the original List object to be untouched of course.

A: The trick is to implement a stable sort. I've created a Widget class that can contain your test data:
public class Widget : IComparable
{
    int x;
    int y;
    public int X
    {
        get { return x; }
        set { x = value; }
    }

    public int Y
    {
        get { return y; }
        set { y = value; }
    }

    public Widget(int argx, int argy)
    {
        x = argx;
        y = argy;
    }

    public int CompareTo(object obj)
    {
        int result = 1;
        if (obj != null && obj is Widget)
        {
            Widget w = obj as Widget;
            result = this.X.CompareTo(w.X);
        }
        return result;
    }

    static public int Compare(Widget x, Widget y)
    {
        int result = 1;
        if (x != null && y != null)
        {
            result = x.CompareTo(y);
        }
        return result;
    }
}

I implemented IComparable, so it can be unstably sorted by List.Sort().
However, I also implemented the static method Compare, which can be passed as a delegate to a search method.
I borrowed this insertion sort method from C# 411:
 public static void InsertionSort<T>(IList<T> list, Comparison<T> comparison)
        {
            int count = list.Count;
            for (int j = 1; j < count; j++)
            {
                T key = list[j];

                int i = j - 1;
                for (; i >= 0 && comparison(list[i], key) > 0; i--)
                {
                    list[i + 1] = list[i];
                }
                list[i + 1] = key;
            }
    }

You would put this in the sort helpers class that you mentioned in your question.
Now, to use it:
    static void Main(string[] args)
    {
        List<Widget> widgets = new List<Widget>();

        widgets.Add(new Widget(0, 1));
        widgets.Add(new Widget(1, 1));
        widgets.Add(new Widget(0, 2));
        widgets.Add(new Widget(1, 2));

        InsertionSort<Widget>(widgets, Widget.Compare);

        foreach (Widget w in widgets)
        {
            Console.WriteLine(w.X + ":" + w.Y);
        }
    }

And it outputs:
0:1
0:2
1:1
1:2
Press any key to continue . . .

This could probably be cleaned up with some anonymous delegates, but I'll leave that up to you.
EDIT: And NoBugz demonstrates the power of anonymous methods...so, consider mine more oldschool :P

A: This may help you,
How to Sort C# Generic List

A: For versions of .Net where you can use LINQ OrderBy and ThenBy (or ThenByDescending if needed):
using System.Linq;
....
List<SomeClass>() a;
List<SomeClass> b = a.OrderBy(x => x.x).ThenBy(x => x.y).ToList();

Note: for .Net 2.0 (or if you can't use LINQ) see Hans Passant answer to this question.

A: I had an issue where OrderBy and ThenBy did not give me the desired result (or I just didn't know how to use them correctly).
I went with a list.Sort solution something like this.
    var data = (from o in database.Orders Where o.ClientId.Equals(clientId) select new {
    OrderId = o.id,
    OrderDate = o.orderDate,
    OrderBoolean = (SomeClass.SomeFunction(o.orderBoolean) ? 1 : 0)
    });

    data.Sort((o1, o2) => (o2.OrderBoolean.CompareTo(o1.OrderBoolean) != 0
    o2.OrderBoolean.CompareTo(o1.OrderBoolean) : o1.OrderDate.Value.CompareTo(o2.OrderDate.Value)));


text:
Q: Adding markers to Google Map generated in Ajax request response I have a Google Map that I would like to add markers denoting the location of membership addresses, but I have a slight problem that I don't quite understand.
If I have the following:
var map = new google.maps.Map(document.getElementById('map'), {
                              center: {lat: -34.397, lng: 150.644},
                              zoom: 8
                            });

                        var marker = new google.maps.Marker({
                          position: {lat: 39.099, lng: -105.129},
                          map: map,
                          title: ''
                        });

The above successfully creates the map and adds the marker successfully, so I know I'm on the right track. But when I go to edit the script into the following:
var map = new google.maps.Map(document.getElementById('map'), {
                              center: {lat: -34.397, lng: 150.644},
                              zoom: 8
                            });

                        $.each(data[1].locations, function(i, item) {
                        var marker = new google.maps.Marker({
                          position: {lat: item.latitude, lng: item.longitude},
                          map: map,
                          title: ''
                        });
                        });

This time, the map is created but no markers are shown (even though the above does correctly response to appropriate coordinates, I get the following error in my console: InvalidValueError: setPosition: not a LatLng or LatLngLiteral: in property lat: not a number

A: Make sure that markers are being added only after ajax request is completed.
Add marker only in ajax's success part.
Example :
$.ajax({
    url:    "ajaxmap.php",
    type : 'GET',
    dataType: 'json',
    success : function(data) {

  $.each(data[1].locations, function(i, item) {
                        var marker = new google.maps.Marker({
                          position: {lat: item.latitude, lng: item.longitude},
                          map: map,
                          title: ''
                        });

}


text:
Q: Why react-navigation element not showing if using alignItems:"center"? When I'm using style property alignItems:"center" for parent element View which contains react-navigation component it shows me blank screen
But without this property everything works well just content is not centered
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { createAppContainer, createStackNavigator } from 'react-navigation';
import MainScreen from './screens/MainScreen';
import Main from './components/Main';

const MainNavigator = createStackNavigator(
    {
        Main: { screen: MainScreen }
    },
    { initialRouteName: 'Main' }
);

const AppNavigator = createAppContainer(MainNavigator);

export default function App() {
    return (
        <View style={styles.container}>
            <AppNavigator />
        </View>
    );
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#fff',
        alignItems: 'center',//there is the problem
        justifyContent: 'center',
    }
});

A: It's not considered as a good practice to style the component parent to your AppNavigator.
You should put all of your styling in each of your app screens, start by applying them to the main container of you view in ./screens/MainScreen.js,
and remplace your app function with:
export default function App() {
    return (
        <AppNavigator />
    );
}


text:
Q: Using VIM for Python IDE in Windows? I am turning to Python from .NET world. And Visual Studio was something a great tool i used.
In python world we do have basic IDLE and another one is VIM. I have seen that a lot of developers have configured VIM to a great IDE. Using basic VIM in Windows 7 seems of less use.
So i want to moderate my VIM to a level which has file explorer, syntax highlighting, search, error highlighting etc. So that it gives feel of Visual Studio and more productive.
But all hacks/tips available are for Linux/Ubuntu users mostly, which i may use later but as of now i need to make my VIM in Windows more productive, visual.
Please Suggest some Tips/Hacks/Resources to look around for VIM configuration?
Thanks

A: This question addresses your low level issue: coding Python with an IDE that is not VS.
There are a few popular blog posts addressing your high level issue: setting up Vim for Python development. They are a quick google away…
I feel the need to point out that Vim is not an IDE. You can customize it a lot and end up with something that looks like an IDE but you won't get an IDE. Only an over-customized text editor.
Anyway, here are a few tips for starting out with Vim:

*

*Do $ vimtutor as many times as needed to feel comfortable with the basics.

*Get familiar with Vim's buit-in documentation: the answers to most of your questions are somewhere inside. :help gets you to the front page, :help 'option' shows the documentation for option, :help :command shows the documentation for command… Hit <C-]> on a colored word to jump to its definition.

*Don't use Janus or SPF13 or whatever pre-packaged set of plugins. You'll only grow bad habits. Similarly, don't copy other people's vimrc wholesale.

*Ctags is an external code indexer that is used by Vim to "jump to definition" with <C-]>. cscope is another option, it's more powerful but also a little more complex. See :help tags.

*Related to ctags, TagList and TagBar are two popular plugins used to display more or less the equivalent of the Object Browser in VS.

*NERDTree is another popular plugin that mimicks the file tree found in many IDEs/editors. But Vim comes with netrw (:Ex) by default, try it before installing NERDTree.

*Read :help motion.txt as soon as possible.

*Watch Drew Neil's laser-guided vimcasts.

*Don't rush it.

A: you can use vim plugins on windows, http://www.vim.org/scripts/index.php, typing "vim {your feature here}" into google will come up with lots of results.
popular file explorer is nerdtree,
syntax highlighting can be turned on with
syntax on in your vimrc
searching open file is easy to do using reg exes .  Initialize search with /.
Searching directory is easy to do using grep.
I don't develop on windows but i have read that Cygwin might be worth installing for some linux tools if not already installed.

A: I am in no way an evangelist of any Editor/IDE.
But, if you are a newbie to Python I would suggest trying out Sublime Text 2 http://www.sublimetext.com/ . It is a very light weight yet powerful editor with a great following and it has a free evaluation version with no deadline.
But, if you intend to work using frameworks such as Django/ GAE then I would suggest using PyCharm from JetBrains
http://www.jetbrains.com/pycharm/
Finally, these tools are all just personal choices until you get comfortable with one or two of them.
Thanks,
-Hari

A: One possible compromise is to use your favorite IDE with a vim emulator plugin. For example, in Eclipse you can use Vrapper, PyCharm has IdeaVim and so forth. Lighttable also has vim key-bindings. The plug-ins (or key-binding options) give you some of the benefits of editing in Vim while still having the powerful debugging / navigation features, etc. of a full-blown IDE. BTW, Vrapper works with PyDev.
  Using an emulator in an IDE allows you to gain the "muscle-memory" necessary for  effective vim editing, without getting bogged down in "configuration hell" associated with turning an editor into an IDE (which auto-complete plugin do I use?..etc.?). Once you have mastered the vim keystrokes for normal and visual mode, used along with insert mode, you may decide to continue on into pure Vim and face those issues.

A: I wouldn't recommend to learn VIM in 2012 (despite it being a great editor). If you must, this  blog post will get you started.
But VIM isn't an IDE, it's a text editor.
If you really want a powerful IDE, try IntelliJ IDEA or Eclipse. Both have great plugins to turn them into Python IDEs (along with code completion and all the other nice time savers). For Eclipse, try PyDev. For IntelliJ, search for Python in the plugin preferences pages.


text:
Q: Three.js Map material showing warnings despite updating buffers I'm trying to load an OBL object and, on pre-specified containers (plains) display a texture. However, after I load an object, I start getting the following errors:
THREE.WebGLRenderer 58
XHR finished loading: "http://localhost:8000/original-material/room2/soba-5-2.obj".

about to traverse...
about to add to scene

WebGLRenderingContext: GL ERROR :GL_INVALID_OPERATION : glDrawElements: attempt to access out of range vertices in attribute 0
WebGL: too many errors, no more errors will be reported to the console for this context.

Following Three JS Map Material causes WebGL Warning, I explicitly started to set following flags, although I had (even beforehand) modified material attributes before adding anything to the scene.
child.material.needsUpdate = true;
child.geometry.buffersNeedUpdate = true;
child.geometry.uvsNeedUpdate = true;

Despite this, problem still persists. Any ideas?

Code
var container_re_match = /container_/

console.log('about to traverse...');
data.traverse(function(child){
    if (child instanceof THREE.Mesh) {
        child.material = new THREE.MeshPhongMaterial({
                ambient: 0xff0000, color: 0xffffff, specular: 0xffffff, shininess: 30, shading: THREE.SmoothShading});

        if (child.parent.name.match(container_re_match)) {
            var container_data = CONTAINER_DATA[child.parent.name]

            child.material.map = THREE.ImageUtils.loadTexture(container_data.image);
            child.material.needsUpdate = true;
            child.geometry.buffersNeedUpdate = true;
            child.geometry.uvsNeedUpdate = true;
        }
    }
});
console.log('about to add to scene');
scene.add(data) // Adding only after everything has been processed
}


text:
Q: How to query using IN for matching emails? given a string of emails like:
emails = "atttt@bbb-inc.com, scott@sara.com, a@a.com, rasx@bo.com"

With one query, I would like to return all matching User records where:
User.rb (id,email)

Here is my query, but it does not return results if I have emails set to more than one email:
User.where("email IN (?)", emails)
  User Load (1.0ms)  SELECT "users".* FROM "users" WHERE (users.deleted_at IS NULL) AND (email IN ('atttt@bbb-inc.com,, scott@sara.com, a@a.com, rasx@bo.com'))
 => []

Suggestions on how to update this User.where query to get all matching Users from the emails provided? Thank you.

A: First, turn the emails into an Array:
emails = "atttt@bbb-inc.com, scott@sara.com, a@a.com, rasx@bo.com".split(', ')

Then you can call:
User.where(:email => emails)


text:
Q: Is there a way to reload my app without window.location.reload() and ngOnInit()? Is there any way to reload my Angular 11 app without window.location.reload() and ngOnInit()?
window.location.reload() makes Chrome reload the tab which is not my desired outcome. And ngOnInit() causes some wierd bugs in my app.
I would like to have something similar to window.location.reload() but that doesn't refresh the Chrome tab.
Any solutions to this?
Thanks in advance.

A: it looks like without any data you approach is wrong, you can use ngAfterViewInit or one of the life cycle hooks with element refresh.  however if you are trying to refresh data on the screen you should look at service binding so that the data is "reactive".
you can use behavior subject or subject binding but it makes your data as a subscribed event so its updated without redrawing the viewport.
however without any type of code or anything this is only speculation.


text:
Q: Salesforce1 and Spring 14 Features Do the currently available native Salesforce1 apps contain all the Spring 14 Release features?
This URL indicates that they are:
http://help.salesforce.com/apex/HTViewSolution?id=000188534
I'm noticing discrepencies between the web site at /one/one.app and the native apps.  After going through the steps to make the canvas app available, and using the "Signed Request (POST)" for the "Access Method" here is what I am seeing:

*

*For mobile browsers (Safari on iOS or Chrome on Android), it is shown
and does POST the signed request to our server

*The Salesforce1 native
app on Android does not show the canvas app in the navigation menu

*The Salesforce1 native app on iOS shows the app in the navigation
menu, but makes a GET request to our server without the signed
request

Apologies for the cross post but it didn't seem like I'd get any answers here:
https://developer.salesforce.com/forums/?id=906F00000009wUiIAI

A: Sorry for the delay here.
I have confirmed the bugs for both the iOS and the Android native apps.  For iOS, the issue is that the app is incorrectly popping Canvas Apps out into a separate web container, which does a GET.  Instead, they should be opened inline which will do the correct signed request POST.  This issue should be fixed in the next release of the iOS app.
For Android, the feature is a bit behind in the dev and has not been implemented yet.  I am working with the Android team to get the Mobile Nav location implemented ASAP.
In the meantime, the easiest way will be to deploy using a VF page that uses the apex:canvasApp tag.
Again, sorry for the delay and the trouble.
Jay


text:
Q: Defining a function in pymunk I defined a function named add_spring in the following code
import pymunk
import pymunk.pygame_util
import math

pygame.init()
wid, hei = 800, 700
window = pygame.display.set_mode((wid, hei))

def draw(space, window, draw_options):
    window.fill("white")
    space.debug_draw(draw_options)
    pygame.display.update()

def wall(space, wid, hei):
    rects = [
        [(wid/2, hei - 10), (wid, 20)],
        [(wid/2, 10), (wid, 20)]
    ]
    for pos, size in rects:
        body = pymunk.Body(body_type=pymunk.Body.STATIC)
        body.position = pos
        shape  = pymunk.Poly.create_box(body, size)
        shape.elasticity = 0.4
        shape.friction = 0.5
        space.add(body, shape)

def create_ball(space, radius, mass):
    body = pymunk.Body()
    body.position = (500, 350)
    shape = pymunk.Circle(body, radius)
    shape.mass = mass
    shape.color = (55, 0, 0, 100)
    space.add(body, shape)
    shape.elasticity = 0.9
    shape.friction = 0.4
    return shape

def add_ball(space):
    body = pymunk.Body()
    body.position = (500, 500)
    shape = pymunk.Circle(body, 20)
    shape.mass = 1
    shape.friction = 0.7
    space.add(body, shape)
    return body

def create_ball_a(space, radius, mass):
    body = pymunk.Body(body_type=pymunk.Body.STATIC)
    body.position = (500, 300)
    shape = pymunk.Circle(body, radius)
    shape.mass = mass
    shape.color = (55, 0, 0, 100)
    space.add(body, shape)
    shape.elasticity = 0.9
    shape.friction = 0.4
    return shape

def create_ball_b(space, radius, mass):
    body = pymunk.Body(body_type=pymunk.Body.STATIC)
    body.position = (550, 300)
    shape = pymunk.Circle(body, radius)
    shape.mass = mass
    shape.color = (55, 0, 0, 100)
    space.add(body, shape)
    shape.elasticity = 0.9
    shape.friction = 0.4
    return shape
def add_spring(var1, var2):
    dlx = pymunk.DampedSpring(var1, var2, (0, 0), (0, 0), 5, 70, 0)
    space.add(dlx)

def run(window, wid, hei):
    run = True
    clock = pygame.time.Clock()
    fps = 60
    dt = 1 / fps
    space = pymunk.Space()
    space.gravity = (0, 981)
    big_ball = create_ball(space, 30, 10)
    joina = create_ball_a(space, 5, 10)
    joinb = create_ball_b(space, 5, 10)
    j = pymunk.DampedSpring(big_ball.body, joina.body, (0, 0), (0, 0), 5, 70, 0)
    space.add(j)
    add_spring(joina, big_ball)
    space.add(pymunk.DampedSpring(big_ball.body, joinb.body, (0, 0), (0, 0), 100, 100, 10))
    wall(space, wid, hei)
    draw_options = pymunk.pygame_util.DrawOptions(window)

    while run:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
                break
        draw(space, window, draw_options)
        space.step(dt)
        clock.tick(fps)
    pygame.quit()

if __name__ == "__main__":
    run(window, wid, hei)

But the following error shows up when I run it.
pygame 2.0.1 (SDL 2.0.14, Python 3.8.9)
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
  File "e:/pymunk/2D-cloth-simulation/string_d.py", line 104, in <module>
    run(window, wid, hei)
  File "e:/pymunk/2D-cloth-simulation/string_d.py", line 88, in run
    add_spring(joina, big_ball)
  File "e:/pymunk/2D-cloth-simulation/string_d.py", line 71, in add_spring
    dlx = pymunk.DampedSpring(var1, var2, (0, 0), (0, 0), 5, 70, 0)
  File "C:\Users\Kishlay\AppData\Local\Programs\Python\Python38\lib\site-packages\pymunk\constraints.py", line 617, in __init__
    _constraint = lib.cpDampedSpringNew(
TypeError: initializer for ctype 'struct cpBody *' must be a cdata pointer, not Body

When I do the same thing without defining a function for it, it works, but in order to keep the code clean, I need it to convert it to a function so that I can do it multiple times without hassle.

A: You have two mistakes.

*

*It needs .body (like in other DampedSpring in your code)
You can get it from var1, var2:
dlx = pymunk.DampedSpring(var1.body, var2.body, (0, 0), (0, 0), 5, 70, 0)

Or you can send .body:
add_spring(joina.body, big_ball.body)

*You have to send also space to this function (to run space.add()
Get it in function:
def add_spring(space, var1, var2):

Send it to function:
add_spring(space, joina.body, big_ball.body)

Full code:
import pygame
import pymunk
import pymunk.pygame_util
import math

# --- constants ---  # PEP8: `UPPER_CASE_NAMES`

WIDTH = 800
HEIGHT = 700
FPS = 60

# --- functions ---  # PEP8: all function before main code

def draw(space, window, draw_options):
    window.fill("white")
    space.debug_draw(draw_options)
    pygame.display.update()

def wall(space, width, height):
    rects = [
        [(width/2, height - 10), (width, 20)],
        [(width/2, 10), (width, 20)]
    ]

    for pos, size in rects:
        body = pymunk.Body(body_type=pymunk.Body.STATIC)
        body.position = pos

        shape  = pymunk.Poly.create_box(body, size)
        shape.elasticity = 0.4
        shape.friction = 0.5

        space.add(body, shape)

def create_ball(space, radius, mass):
    body = pymunk.Body()
    body.position = (500, 350)

    shape = pymunk.Circle(body, radius)
    shape.mass = mass
    shape.color = (55, 0, 0, 100)
    shape.elasticity = 0.9
    shape.friction = 0.4

    space.add(body, shape)

    return shape

def add_ball(space):
    body = pymunk.Body()
    body.position = (500, 500)

    shape = pymunk.Circle(body, 20)
    shape.mass = 1
    shape.friction = 0.7

    space.add(body, shape)

    return body

def create_ball_a(space, radius, mass):
    body = pymunk.Body(body_type=pymunk.Body.STATIC)
    body.position = (500, 300)

    shape = pymunk.Circle(body, radius)
    shape.mass = mass
    shape.color = (55, 0, 0, 100)
    shape.elasticity = 0.9
    shape.friction = 0.4

    space.add(body, shape)

    return shape

def create_ball_b(space, radius, mass):
    body = pymunk.Body(body_type=pymunk.Body.STATIC)
    body.position = (550, 300)

    shape = pymunk.Circle(body, radius)
    shape.mass = mass
    shape.color = (55, 0, 0, 100)
    shape.elasticity = 0.9
    shape.friction = 0.4

    space.add(body, shape)

    return shape

def add_spring(space, body1, body2):
    dlx = pymunk.DampedSpring(body1, body2, (0, 0), (0, 0), 5, 70, 0)

    space.add(dlx)

    return dlx

def run(WIDTH, HEIGHT):
    pygame.init()
    window = pygame.display.set_mode((WIDTH, HEIGHT))

    dt = 1 / FPS

    clock = pygame.time.Clock()

    space = pymunk.Space()
    space.gravity = (0, 981)

    big_ball = create_ball(space, 30, 10)
    joina = create_ball_a(space, 5, 10)
    joinb = create_ball_b(space, 5, 10)

    j = pymunk.DampedSpring(big_ball.body, joina.body, (0, 0), (0, 0), 5, 70, 0)
    space.add(j)

    add_spring(space, joina.body, big_ball.body)

    space.add(pymunk.DampedSpring(big_ball.body, joinb.body, (0, 0), (0, 0), 100, 100, 10))

    wall(space, WIDTH, HEIGHT)
    draw_options = pymunk.pygame_util.DrawOptions(window)

    run = True
    while run:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
                break

        draw(space, window, draw_options)

        space.step(dt)
        clock.tick(FPS)

    pygame.quit()

if __name__ == "__main__":
    run(WIDTH, HEIGHT)

PEP 8 -- Style Guide for Python Code


text:
Q: Changing number of partitions dynamically when cluster scales up I am running a spark job having 4 nodes cluster initially.
The cluster is autoscalable so during high load the number of nodes scales up to 15 nodes.
But during the startup we have provided the number of partitions on the basis of 4 nodes.Now when my cluster scales up-to 15 nodes, no of partitions are still same(assigned during startup).
My question is am I utilizing my cluster fully with same no of partitions even though I am having more no of executors.
Or spark internally handles this.
Do I have to change no of partitions dynamically when cluster scales up??
If I have to do this,how can I achieve this in my Spark job??
Any inputs are highly appreciated.
Thanks in advance!!


text:
Q: CDROM recognized, but cannot mount: no medium found on /dev/sr0 I'm using Ubuntu 17.10 and want to open some CDs and DVDs. While on my old PC running Ubuntu Server, they can be mounted easily, on my laptop they are not mounted.
I tried:
$ sudo lshw -C disk
  *-cdrom
       description: DVD-RAM writer
       product: DVDRAM GU71N
       vendor: HL-DT-ST
       physical id: 0.0.0
       bus info: scsi@2:0.0.0
       logical name: /dev/cdrom
       logical name: /dev/cdrw
       logical name: /dev/dvd
       logical name: /dev/dvdrw
       logical name: /dev/sr0
       version: AS00
       capabilities: removable audio cd-r cd-rw dvd dvd-r dvd-ram
       configuration: ansiversion=5 status=ready
     *-medium
          physical id: 0
          logical name: /dev/cdrom
 ...

$ sudo mount /dev/cdrom /media/cdrom0
mount: /media/cdrom0: no medium found on /dev/sr0.

Since it communicates with the hardware, I don't think there is a hardware problem. Recently I upgraded from 16.10 to 17.04 and then to 17.10. Not sure if that's related, but I think the hardware doesn't have any problems.
How to solve this? How can I mount the CD drive? How can I do this automatically, eventually?

A: I had the same problem when trying to mount my dvd drive on usb and getting 'no medium found on /dev/sr0'. The solution is trivial: there was no CD in my dvd reader. When I put CD in, it mounted correctly.


text:
Q: Simplest command to print unique values of some column data with count of repeated values A sample input data with 3 columns, 1st and 3rd column has values in duplicates, need to print them uniquely with their repetition count.
sort -u does help in some sense but unable to print occurrence of repeated values relating 1st and 3rd column.
Input :

A 3210 -06:00
A 5172 -06:00
A 3335 -07:00
A 3258 -05:00
B 3322 -05:00
B 5097 -05:00
C 3238 -06:00
C 5364 -05:00
C 3366 -06:00
C 3293 -06:00

Output :

A(2) -06:00
A(1) -07:00
A(1) -05:00
B(2) -05:00
C(3) -06:00
C(1) -05:00

or
Output :

A 2 -06:00
A 1 -07:00
A 1 -05:00
B 2 -05:00
C 3 -06:00
C 1 -05:00

A: Not precisely the format you want, but fits all other requirements:
awk '{print $1" "$3}' <inFile> | sort | uniq -c
In english, use awk to print only the first and third columns, then sort, then uniq with count.

A: $ awk '{ count[$1,$3]++ } END { for (i in count) { split(i, field, SUBSEP); printf("%s(%d)%s%s\n", field[1], count[i], OFS, field[2]) } }' file
A(1) -07:00
B(2) -05:00
A(2) -06:00
A(1) -05:00
C(3) -06:00
C(1) -05:00

Note that the output may not be sorted.  Pass it through sort if needed.
The code stores the count for how many times the first and third fields of the input has occurred together as a pair, in the count array (with the first and third fields as the index). At the end, we loop over the indexes of the array, splitting them up into the original first and third fields (as field[1] and field[2] respectively) and output these together with the count in the wanted format.

In the alternative format:
If the input file uses a single space for field separator (otherwise use awk '{ print $1,$3 }' instead of the cut):
$ cut -d ' ' -f 1,3 file | sort | uniq -c
   1 A -05:00
   2 A -06:00
   1 A -07:00
   2 B -05:00
   1 C -05:00
   3 C -06:00

To swap the two first columns:
$ cut -d ' ' -f 1,3 file | sort | uniq -c | awk '{ print $2, $1, $3 }'
A 1 -05:00
A 2 -06:00
A 1 -07:00
B 2 -05:00
C 1 -05:00
C 3 -06:00

A: *

*Given Input use cut, sort, uniq and sed:
cut -d ' ' -f1,3 Input |
sort | uniq -c |
sed 's/^ *//;s/^\([0-9]*\) \([^ ]*\)/\2 \1/'

*Using datamash and sed:
datamash -t ' ' -g1,3 -s countunique 2 < Input |
sed 's/\(.*\) \(.*\) \(.*\)/\1 \3 \2/'

Output of either:
A 1 -05:00
A 2 -06:00
A 1 -07:00
B 2 -05:00
C 1 -05:00
C 3 -06:00


text:
Q: Annotate with count for each user then order by date of latest occurrence I want to get the count of unread messages for each user_from which ordered by the date of last message from her/him.
class Chat(models.Model):
    user_from = models.ForeignKey(settings.AUTH_USER_MODEL)
    user_to = models.ForeignKey(settings.AUTH_USER_MODEL)
    is_read = models.BooleanField(default=False)
    added_on = models.DateTimeField(auto_now_add=True)
    message = models.CharField(max_length=255)

I'm seeking for some queryset(s) outputing like this:
Output queryset:

A: from django.db.models import Count, Max
query_set = Chat.objects.values('user_from').annotate(unread_count=Count('user_from')).filter(is_read=False).annotate(last_time=Max('added_on')).order_by('-last_time')


text:
Q: Magento Case Sensitive addFieldToFilter search result How to get case sensitive search result using addFieldToFilter() of collection object in magento.
I want to get search result based on case sensitive search results.
Like ABCDE12 is not equal to ABCde12.
I am trying to get case sensitive search result from collection.
$couponCode = 'ABCde12';
$getCoupon = $this->couponFactory->create()->getCollection()
                ->addFieldToSelect(array('coupon_code','description'))
                ->addFieldToFilter('coupon_code',array('eq' => $couponCode))->getFirstItem();

In database ABCde12 and ABCDE12 both entry are created.
I just want to fetch case sensitive record from table.
Any help would be Appreciated.

A: Yeah I faced the issue one day in Magento 1.
The problem is that, with MySQL:

String comparisons normally are case-insensitive, so you can specify
  the name as 'bowser', 'BOWSER', and so forth. The query result is the
  same.

Source: MySQL documentation
In order to avoid that you need to use the BINARY operator
However, I haven't found a way to handle it properly with Magento, so here's the hacky way of doing it:
$getCoupon = $this->couponFactory->create()->getCollection()
                ->addFieldToSelect(array('coupon_code','description'))
                ->addFieldToFilter('coupon_code',array('eq' => $couponCode));

Don't get the first item. You first retrieve the where part of the query
$where = $getCoupon->getSelect()->getPart('where');

Then you create a new where part and you inject the BINARY operator before the value that you're searching.
$newWhere = str_replace('\''.$couponCode.'\'','BINARY \''.$couponCode.'\'', $where);

Then you set the where part with the new where part you just created
$getCoupon->getSelect()->setPart('where', $newWhere);

Finally you can get the first item
$coupon = $getCoupon->getFirstItem();


text:
Q: RegEx to exclude particular words I am working on RegEx that will match a string that contains only uppercase letters and digits but not exact words ABC or XYZ or LMN.
^(?!ABC|XYZ|LMN)([A-Z0-9]+)$

This works for most of the cases but fails for input ABC12, XYZ8 etc.
How can I improve this to match the requirement.
I've referred RegEx to exclude a specific string constant but couldn't tackle this one.

A: If you are trying to match the whole string or line using ^ and $, then you can put the $ inside your negative lookahead. This will allow ABC12 to match.
^(?!(ABC|XYZ|LMN)$)([A-Z0-9]+)$


text:
Q: Unobtrusive Validation can't find JQuery reference in ASP.NET Master Page I'm building a login and signup pages in Visual Studio ASP.Net C#.
When I try to run the page in question its crashes and reports that the unobtrusive validation that relies on JQuery cannot be found despite the page being linked to a Master Page that has a reference to it:

    <form class="form1" runat="server">

        <%--Reference to jquery for all pages using MasterPage--%>
        <asp:ScriptManager ID="ScriptMan1" runat="server" EnablePageMethods="true">

  </asp:ScriptManager>

I tried changing the reference to:
<asp:ScriptReference Path="~/scripts/jquery-2.1.4.js" />

Thinking that the intellisense part was causing a problem but it made no difference.
I should add that I have connected to my SQL Server database using my own connection string rather than the default setting provided that creates a DB on the server, and as I've yet to connect to that, it might be related:
  <connectionStrings>

    <add name="MyConnection" connectionString="Data Source = SQL.mywebserver.com; Initial Catalog=db_info; Persist Security Info=True; User ID =user_abc123; Password=p@55worD" providerName="System.Data.SqlClient"/>

  </connectionStrings>

Any Ideas?
Many thanks.
Kw
Edit: More details, thanks for your help:
Here is the complete error message text:
Server Error in '/' Application.

WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery'. Please add a ScriptResourceMapping named jquery(case-sensitive).

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidOperationException: WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery'. Please add a ScriptResourceMapping named jquery(case-sensitive).

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[InvalidOperationException: WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery'. Please add a ScriptResourceMapping named jquery(case-sensitive).]
   System.Web.UI.ClientScriptManager.EnsureJqueryRegistered() +2179162
   System.Web.UI.WebControls.BaseValidator.RegisterUnobtrusiveScript() +10
   System.Web.UI.WebControls.BaseValidator.OnPreRender(EventArgs e) +9708897
   System.Web.UI.Control.PreRenderRecursiveInternal() +83
   System.Web.UI.Control.PreRenderRecursiveInternal() +155
   System.Web.UI.Control.PreRenderRecursiveInternal() +155
   System.Web.UI.Control.PreRenderRecursiveInternal() +155
   System.Web.UI.Control.PreRenderRecursiveInternal() +155
   System.Web.UI.Control.PreRenderRecursiveInternal() +155
   System.Web.UI.Control.PreRenderRecursiveInternal() +155
   System.Web.UI.Control.PreRenderRecursiveInternal() +155
   System.Web.UI.Control.PreRenderRecursiveInternal() +155
   System.Web.UI.Control.PreRenderRecursiveInternal() +155
   System.Web.UI.Control.PreRenderRecursiveInternal() +155
   System.Web.UI.Control.PreRenderRecursiveInternal() +155
   System.Web.UI.Control.PreRenderRecursiveInternal() +155
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +974

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18408


text:
Q: c# nest: converting Nest.KeyItem to Nest.KeyedBucket? What would be the syntax? We have aggregation query that returns back "CityIdCount" and "CityNameCount" like:
.Aggregations(aa => aa.Terms("CityIdCount", h => h.Size(0).Field("cityId")).Terms("CityNameCount", h => h.Size(0).Field("cityName"))

Above is not the complete query but only aggregations part of it.
           BucketAggregate cityCount = (Nest.BucketAggregate)cities.Aggregations["CityIdCount"];
            BucketAggregate cityName = (Nest.BucketAggregate)cities.Aggregations["CityNameCount"];
            var cityList = cityCount.Items;
            var cityNameList = cityName.Items;

            using (var cityIdListEnumerator = cityList.GetEnumerator())
            using (var cityNameListEnumerator = cityNameList.GetEnumerator())
            {
                while (cityIdListEnumerator.MoveNext() && cityNameListEnumerator.MoveNext())
                {
                    var currCityIdObject = cityIdListEnumerator.Current;
                    var currCityNameObject = cityNameListEnumerator.Current;

                    City city = new City()
                    {
                        //Following is original nest 1.7 version line
                        CityId = Convert.ToInt32(((Nest.KeyItem)(currCityIdObject)).Key),

                        //How can we convert it to nest 5.4? Below line gives error
                        CityId = (Nest.KeyedBucket<int>)(currCityIdObject);

                        CityCount = Convert.ToInt32(((Nest.KeyItem)(currCityIdObject)).DocCount),
                        CityName = (((Nest.KeyItem)(currCityNameObject)).Key)
                    };
                    citiesList.Add(city);
                }
            }

Please check the comments in the above code. We need to convert Nest.KeyItem to Nest.KeyedBucket. Can anyone help how can we get cityId from Nest.KeyedBucket?


text:
Q: Select columns from expression in shiny app I am trying to build a shiny dashboard app, where I process the input data and produce summary statistics based on the user supplied grouping variables. The last step, where I am stuck is to
implement a working function , which enables the user to select to display only a subset of the columns after the calculation of the summary statistics.
My attempt is in  the lines after output$select_col in global.R .  Right now each time I try to use the selector shiny crashes with the error "incorrect number of dimensions".
global.R
# Shiny
library(shiny)
library(shinydashboard)
library(shinyjs)

# Data tools
library(dplyr)
library(tidyr)
library(tibble)
library(data.table)

server.R
server <- function(input, output) {

raw_tables<-reactive({
 mtcars
  })

  output$cyl <-   renderUI({
    selectInput(inputId = "cyl",
                label = "Which number of cyl to consider",
                choices = c(4,6,8),
                selected = NULL,
                multiple=TRUE)
  })

  filtered_tables<-
    reactive({
      if(is.null(input$cyl)){
        data_filtered <- raw_tables()
      }
      else{
        data_filtered <- raw_tables() %>% filter(cyl %in% input$cyl)
      }
    })
  new_statistics <- reactive({
    if(is.null(filtered_tables())){
      return(NULL)
    }
    if(length(input$grouping_variables) == 0){
      op <- filtered_tables() %>%
        ungroup()
    } else {
      op  <- filtered_tables() %>%
        group_by_(.dots = input$grouping_variables)
    }

    op %>% #
      summarise(nr_cars = n(),
                mean_mpg = mean(mpg,na.rm=T),
                sd_mpg = sd(mpg,na.rm=T))

  })

  nice_table <-reactive({
    if(is.null(new_statistics())){
      return(NULL)
    }
    DT::datatable(new_statistics(),
                  colnames = c(
                    "nbr cars"="nr_cars" ,
                    "mean mpg"="mean_mpg",
                    "sd mpg"="sd_mpg"
                    ), selection = list(target = 'column') ,  extensions = c('ColReorder'), options = list(colReorder = TRUE)
    ) %>%
      DT::formatRound(columns=c(
        "nbr cars" ,
        "mean mpg",
        "sd mpg"),
      digits=2)
  })

  output$select_col <- renderUI({
    if(is.null(nice_table())){
      return(NULL)
    }
    selectInput("col", "Select columns:", choices = colnames(nice_table()), selected=NULL, multiple=TRUE)
  })

  output$statistics = DT::renderDataTable({
    if(length(input$col)>0)
    {

      return(DT::datatable(nice_table()[, colnames(nice_table()) %in% input$col]))
    }
    else
    {
      return(NULL)
    }
  })
}

ui.R
dbHeader <- dashboardHeader(title = "test",
                            titleWidth = 250)

sidebar <- dashboardSidebar(
  width = sidebarWidth,
  br(),
  sidebarMenu(
    menuItem(text =  "Data View",
             tabName = "dat_view",
             icon = icon("cloud-download")
    )

  )
)

body <- dashboardBody(

  # Add shinyJS  mini-sidebar
  shinyjs::useShinyjs(),

  tabItems(
    tabItem(tabName = "dat_view",
            fluidPage(
              sidebarLayout(
                sidebarPanel(width=2,

                             selectInput(inputId = 'grouping_variables',
                                         label = 'Which grouping var?',
                                         choices = c("cyl","gear","carb"),
                                         selected = NULL,
                                         multiple=TRUE,
                                         selectize=TRUE),
                             uiOutput("cyl"),
                             uiOutput("select_col")

                )
                ,
                mainPanel(
                  tabsetPanel(id="dat_view_tabs",
                              tabPanel(
                                'statistics',

                                DT::dataTableOutput(outputId='statistics')
                              )
                  )

                )
              )))))

ui <- dashboardPage(skin    = "blue",
                    header  = dbHeader,
                    sidebar = sidebar,
                    body    = body)


text:
Q: Javascript variables inside twig asset I want to append images by AJAX in my TWIG template with liipImagineBundle implementation.

This is what I want to receive in my javascript:

Image path is in my JavaScript variable name: value.imgPath
How can I append it using

In other words, How I can use javascript variables inside twig brackets??

A: imn't sure but i think this is what you want to do
var value = {"imgPath":"img.jpg"};

$('#myId').append("");


text:
Q: Editable bootstrap table then Insert data to MYSQL database I'm trying to use an editable bootstrap table where in data can be inserted on the database. However, I find it difficult since I'm only new with this field. I can load the data from the database and edit the table field but I don't know how can I insert it on the database.

Below is my code for the table. For the <tbody, I used javascript and ajax to load the data from the database. Note that, it only loads the CATEGORY ID and DESCRIPTION. The AMOUNT must be inserted by the user.

        CATEGORY
        CATEGORY ID
        DESCRIPTION
        AMOUNT

As per the resources online, it says that I can use contenteditable="true" for me to have an editable table.

I found a script online where it shows the output of the live table when button is clicked.
var $TABLE = $('#table');
var $BTN = $('#export-btn');
var $EXPORT = $('#export');

// A few jQuery helpers for exporting only
jQuery.fn.pop = [].pop;
jQuery.fn.shift = [].shift;

$BTN.click(function () {
var $rows = $TABLE.find('tr:not(:hidden)');
var headers = [];
var data = [];
// Get the headers (add special header logic here)
$($rows.shift()).find('th:not(:empty)').each(function () {
headers.push($(this).text().toLowerCase());
});

// Turn all existing rows into a loopable array
$rows.each(function () {
var $td = $(this).find('td');
var h = {};

// Use the headers from earlier to name our hash keys
headers.forEach(function (header, i) {
h[header] = $td.eq(i).text();
});
data.push(h); //adds new items to the end of an array
});

// Output the result
$EXPORT.text(JSON.stringify(data));
});

However, I can't insert it on the database. I'm planning of inserting the data in a new MySQL table in which it stores the description and amount. Can someone help me on how can I insert it?


text:
Q: why button is still disabled after filling form in vuetify I'm trying to add validation on login and registration form. button disabled till all form validation is completed after that the button should be able to clickable but its not don't know why is I'm doing something wrong?
I have already done same thing in login form and after filling email and password the disabled button enable and I'm able to login using button but don't know why it's not working in registration form.
screenshot

 data() {
    return {
      email: "",
      password: "",
      confirmPassword: "",
      err_message: "",
      errorMessages: "",
      err_show: false,
      showPass: false,
      validate: false,
      showConPass: false,
      rules: {
        required: (value) => !!value || "Required is requred.",
        min: (v) => v.length >= 6 || "Min 6 characters",
      },
      conPass: [
        (v) => !!v || "Required is requred.",
        (v) => v === this.password || "Passwords do not match",
      ],
      emailRules: [
        (value) => {
          if (value) return true;

          return "E-mail is requred.";
        },
        (value) => {
          if (/.+@.+\..+/.test(value)) return true;

          return "E-mail must be valid.";
        },
      ],
    };
  },

 <v-card class="mx-auto py-10 px-10 mt-10" max-width="500" outlined>
    <ErrorMessage :err_show="err_show" :err_message="err_message" />
    <v-form v-model="validate">
      <v-card-title>Register</v-card-title>

      <v-text-field
        v-model="email"
        :rules="emailRules"
        :error-messages="errorMessages"
        label="Email"
        placeholder="example@gmail.com"
        required
      ></v-text-field>

      <v-text-field
        class="text__Field"
        v-model="password"
        :append-inner-icon="showPass ? 'mdi-eye' : 'mdi-eye-off'"
        :rules="[rules.required, rules.min]"
        :type="showPass ? 'text' : 'password'"
        name="input-10-1"
        label="Password"
        hint="At least 6 characters"
        counter
        @click:append-inner="showPass = !showPass"
      ></v-text-field>

      <v-text-field
        class="text__Field"
        v-model="confirmPassword"
        :append-inner-icon="showPass ? 'mdi-eye' : 'mdi-eye-off'"
        :rules="conPass"
        :type="showConPass ? 'text' : 'password'"
        name="input-10-1"
        label="Confirm Password"
        hint="At least 6 characters"
        counter
        @click:append-inner="showConPass = !showConPass"
      ></v-text-field>
    </v-form>

    <v-card-actions>
      <v-btn :disabled="!validate" elevation="1" @click="register"
        >Register</v-btn
      >
    </v-card-actions>
  </v-card>


text:
Q: Magic Number - The Quest for the Simplest Is there any better logic that can be applied to magic numbers?
Or is there a magic number that I am missing out on?
Please help me out with this simplest working code!

A Magic number is a number whose sum of digits eventually leads to 1.
Example#1:  19 ;  1+9 =10 ; 1+0 = 1.  Hence a magic number.
Example#2:  226; 2+2+6=10; 1+0 =1.  Hence a magic number.
Example#3:  874; 8+7+4=19; 1+9=10; 1+0=1.  Hence a magic number.

boolean isMagic ( int n ) {
  return n % 9 == 1;
}

A: Well, I'm not 100% that the code you placed would work to get a "magic number", but my approach to the problem would be different.
First, I'd receive a String, so that I can get the different digits of the number with a String.charat.
Then I'd use a while cycle to sum the numbers until it gets a single digit number, then check if it's 1.
The code would be
boolean isMagicNumber(String number) {

    int[] digits = new int[number.length()];
    int sum = 99;

    while(sum/10 >= 1) {
          sum = 0;
          for(int i = 0; i < number.length(); i++) {
              sum += Integer.parseInt(""+number.charAt(i));
          }
          if(sum == 1) {
               return true;
          }
    }
    return false;
}

There might be a better solution, but this is what I'd do to solve the problem.


text:
Q: Does it violate any OOP principle if a member function does not use any of class properties/member variables? I have an existing class which interacts which can open, read or write to a file. I need to retrieve a file modification for that purpose I have to add a new method
Suppose this following is my class definition where I want to add a new method.
class IO_file
{
 std::string m_file_name;
 public:
 IO();
 IO(std::string file_name);

+ time_t get_mtime(file_name);
+       OR
+ time_t get_mtime();
};

I have two options -

*

*Create an empty object and then pass the file_name in the method argument for which I wish to retrieve the file modification time.

*Pass the file name at the object construction and simply call the member function which will operate on the member variable.
Both options will serve the purpose. I also believe that second approach is better than first one. But what I don't understand is How?
Is first approach bad design since it doesn't make use of a member variable?
Which principle of Object oriented design does it violate?
If a member function does not use the member variable, should  that member function should always be made static?

A:
Does it violate any OOP principal if a member function does not use any of class properties/member variables?

No.
OOP doesn't care if your member function uses, or doesn't use, class properties or member variables.  OOP cares about polymorphism and not hard coding implementation.  Static functions have their uses but a function shouldn't be static simply because it doesn't depend on object state. If that's your thinking fine, but don't blame it on OOP because that idea didn't come from OOP.

Is [it] bad design [to not] make use of member variables?

If you don't need to remember state from call to call there is no good reason to use state.

Which principle of Object oriented design [does] it violate?

None.

If a member function does not use the member variable then that member function should always be made static?

No. This thinking has the implication arrow going in the wrong direction.

*

*A static function can't access instance state

*If the function has no need to access instance state then the function can be static or non-static
Making the function static here is completely up to you.  But it will make it more like a global if you do.  Before going static consider hosting the function in a stateless class.  It's more flexible.

I have here an OOP example of a member function that doesn't use class properties or member variables.
The member function (and it's stateless class):
#include <iostream>

class Strategy
{
public:
     virtual int execute (int a, int b) = 0; // execute() is a so-called pure virtual
                                             // function. As a consequence, Strategy
                                             // is a so-called abstract class.
};

Three different implementations:
class ConcreteStrategyAdd:public Strategy
{
public:
    int execute(int a, int b)
    {
        std::cout << "Called ConcreteStrategyAdd's execute()\n";
        return a + b;
    }
};

class ConcreteStrategySubstract:public Strategy
{
public:
    int execute(int a, int b)
    {
        std::cout << "Called ConcreteStrategySubstract's execute()\n";
        return a - b;
    }
};

class ConcreteStrategyMultiply:public Strategy
{
public:
    int execute(int a, int b)
    {
        std::cout << "Called ConcreteStrategyMultiply's execute()\n";
        return a * b;
    }
};

A place to store the choice of implementation:
class Context
{
private:
    Strategy* pStrategy;

public:

    Context (Strategy& strategy)
        : pStrategy(&strategy)
    {
    }

    void SetStrategy(Strategy& strategy)
    {
        pStrategy = &strategy;
    }

    int executeStrategy(int a, int b)
    {
        return pStrategy->execute(a,b);
    }
};

An example of use
int main()
{
    ConcreteStrategyAdd       concreteStrategyAdd;
    ConcreteStrategySubstract concreteStrategySubstract;
    ConcreteStrategyMultiply  concreteStrategyMultiply;

    Context context(concreteStrategyAdd);
    int resultA = context.executeStrategy(3,4);

    context.SetStrategy(concreteStrategySubstract);
    int resultB = context.executeStrategy(3,4);

    context.SetStrategy(concreteStrategyMultiply);
    int resultC = context.executeStrategy(3,4);

    std::cout << "\nresultA: " << resultA
              << "\nresultB: " << resultB
              << "\nresultC: " << resultC
              << "\n";
}

Outputs:
Called ConcreteStrategyAdd's execute()
Called ConcreteStrategySubstract's execute()
Called ConcreteStrategyMultiply's execute()

resultA: 7
resultB: -1
resultC: 12

And all without execute() caring about the state of any object.  The Strategy class is actually stateless. Only state is in Context. Stateless objects are perfectly fine in OOP.
Found this code here.

A: get_mtime would make more sense here as a standalone function or as a static function, rather than as you've shown here.
The mtime of a file is read, on most systems, from a call to lstat or similar, and doesn't require an open file descriptor, so it doesn't make sense to have it as a member function of an instantiated class.

A: The reason that second option seems instinctively better (and, IMO, IS better) is because your first option gives you an object that doesn't actually represent anything.
By not specifying the filename, your IO_file class is really just an abstract object which just happens to resemble a concrete file. If you're passing in the filename when you call the method you may as well just refactor the entire method into a free-floating pure function instead; there's no actual benefit to keeping it tied to an object that you'll need to instantiate just to use it. It's just a function; the object instantiation boilerplate is just an inconvenient added step.
On the other hand, once the filename is given any methods you call on that object are being are more like queries about a specific instance of a thing. That's better OO because your objects have actual meaning and, therefore, utility.

A: Let's translate this to C. First we our class - now it's a struct:
struct IO_file {
    char* m_file_name;
};

Let's, for the simplicity of the snippets, define a constructor function(ignoring memory leaks for now):
struct IO_file* IO_file(char* file_name) {
    struct IO_file* obj = malloc(sizeof(struct IO_file));
    obj.m_file_name = file_name;
    return obj;
}

Option #2 looks like this:
time_t get_mtime(struct IO_file*);

and used like this:
time_t mtime = get_mtime(IO_file("some-file"));

How about option #1? Well, it looks like this:
time_t get_mtime(struct IO_file* this, char* file_name);

And how is it used? Essentially, you are asking to pass junk as the first parameter:
time_t mtime = get_mtime((struct IO_file*)1245151325, "some-file");

Doesn't make much sense, does it?
C++'s object system hides it, but the object is also an argument of the method - an implicit pointer argument named this. This is what option #1 is bad - it has an argument that is unused by definition(arguments that happen to be unused, but may be used in overrides are OK). Such arguments contribute nothing while complicating the function's signature, definition and usage and confusing readers of the code which are left pondering what the argument is supposed to do, why is it OK to pass junk to it, and whether or not the fact that you are passing junk/NULL/empty object to it is the cause of the bug they are currently trying to solve. Spoiler - it isn't, but they are still going to waste time exploring that possibility.
The fact that the junk argument is implicit may lessen the effect, but it's still there, and and be easily avoided by making the method static.


text:
Q: Reference request - time series analysis book with numerical algorithms I am working on some applications of time series, and I wanted to find a book that has the numerical algorithms or pseudocode for computing things like AR models, and ARIMA models, using nonlinear least squares, method of moments, the differencing operations, as well as State-space model like Kalman filters, etc. I can use all of the existing packages in python or R, etc., but I would rather write the code myself so that I understand it.
I have copies of Shumway and Stoffer and all of the other books, but they just show the mathematics without showing estimation algorithms. Even the videos I have found on line don't really give much in the way of estimation.
Ideally the book or reference would show how to generate a fake time-series of data, then show how to difference the data and estimate the coefficients. I can figure out most of this myself, but just seems like there should be a better reference for stuff like this. Thanks.


text:
Q: Codeigniter: How to handle database error? I'm creating a web application using codeigniter and postgresql. I have this inside my database:
user
id name
unique(name)

When someone try to register with the same name, i get an error. How can i handle them, without displaying the codeigniter's error and showing instead my custom error?
If i set $db['default']['db_debug'] = FALSE; i don't get any error of course, but is there a way to handle the db error or should i check myself if the table already contains an entry with that same name?

A: Use Codeigniters form validation class. is_unique[table.columnName]. This will do the work for you. Below is an example
$this->form_validation->set_rules('name', 'Name', 'is_unique[table_name.Name]');

Then just set a custom message referencing the is_unique validation like below
$this->form_validation->set_message('is_unique', 'Name already exists');

A: I dont know anything by codeigniter, but im going to assume the principle works the same:
You first make a query like SELECT id FROM tablename WHERE name='SomeName' LIMIT 1, then you check the number of rows. This kind of checking is fairly normal. Control as much as you (sensebly) can to avoid errors down the road.
Zero rows? Safe to insert. Not zero rows? Display something like 'username allready taken'.
Example with some code:
$check = mysqli_query("SELECT id FROM tablename WHERE name='SomeName' LIMIT 1");
if( $check->num_rows!==0 ){
    echo 'Username allready taken'; // echo is bad, you should process this better, but this is easy demo
}
else{
    // Your normal inserting code goes here.
}

A: Like Martijn said, it is a solution.
CI doesn't throw exception, so when you perform a query, it will return NULL if the statement fails.
You may want to see  CodeIgniter - how to catch DB errors?


text:
Q: Publishing an InfoPath form wiped out Personal Views in the Form Library I published an InfoPath 2007 form into a Form Library on MOSS 2010 and I lost all the data in the form column fields.  I was able to restore the data by doing a check-out/Check-in on the documents, but now realized it has screwed up the personal view that were created in that library.  The views no longer contain the filers or column that referred to the columns of the form data.  Any clue why this happened or how we can restore the personal views other then recreating them?

A: You are probably facing the issue described in KB article 2554288 Columns published from InfoPath fields are recreated when the same InfoPath form template is re-published to more than one document libraries in a SharePoint site. The issue is that InfoPath isn't very flexible when it comes to matching up columns in SharePoint with what it's expecting in the form. It has probably duplicated all of the columns in the list.
The only way I know to resolve this is from backup or painstakingly cleaning up the mess.

A: The KB article Alex linked above offers one (theoretically) good solution: Publish the form as a Site Content Type and then associate that with the library.
After running into this today when publishing an updated form into a Test environment, I decided to try another solution when publishing into Production (you only live once), which worked well:
When in the publishing wizard and selecting fields to promote, go through the full list and Modify each field which already exists in the destination library: change the Site Column Group from "(None: Create new column...)" to "(This document library)" and then select the existing column.
I'm guessing that the safest practice for any forms deployed this way is to go through the Promotion list every time you change the environment/site/library you're publishing to and switch everything to "...Create new column..." (if not already set) and then change to "(This ... library)" to force the internal column GUID to be set correctly.

A: I had the same issues and the problem is related to how you publish your form. When I republished the form, the list view lost all lookup fields in the form and I had to add them again. Also any list view webpart containing these coloums needed to be updated. Also I needed to reopen all forms and save them again in order to have the lookup field information available in the SharePoint list.
To solve this problem i publish the form as a content type instead. I found this blog which describes step by step how to do this.
http://www.marclenferna.com/blog/archive/2009/01/18/how-to.-publish-your-infopath-form-to-sharepoint--a.aspx
Basically you upload the form as a content type to an new list which is only to contain the contenttype and then you create a new form library where you add the new content type.


text:
Q: Not able to update tilt after getting marker bounds Gmap V2 I am using this to get the bounds of markers on my map:
markerList.add(m);
        LatLngBounds.Builder builder = new LatLngBounds.Builder();
        for (Marker marker : markerList) {
            builder.include(marker.getPosition());
        }
        LatLngBounds bounds = builder.build();
        CameraUpdate updatecamera = CameraUpdateFactory.newLatLngBounds(bounds, 50);
        map.animateCamera(updatecamera);

After getting update, I would like to tilt the map to 30 degrees.
I have used this to tilt the camera in the past, but it is not working with the bounds feature:
CameraPosition cameraPosition = new CameraPosition.Builder()
                        .target(meLoc).zoom(6).bearing(0).tilt(30).build();
                map.animateCamera(CameraUpdateFactory
                        .newCameraPosition(cameraPosition));

How do I add this tilt after getting the bounds?
Thanks

A: As you say, the Android Maps API v2 doesn't currently directly support animating the camera with both bounds and tilt info.
One workaround is to use the following steps:

*

*Do the camera animation you want to perform with the bounds, but leave out the tilt

*Listen for the end of the above camera animation, get the current camera position, and then perform the tilt

This has the effect of moving the camera to the bounds while looking straight down (i.e., tilt = 0), and then tilting the camera in place.  I've found that this works well in some use cases, and actually looks nice, but in others its kind of awkward.  It may or may not work for your particular use case.
To implement this, let's assume you have a main class MapScreen.java where your map is implemented.  You'll need change it to include the camera listener interface, a reference to the camera position, a reference to your activity, an initial tilt value you want to use (you can alternately set this at runtime), and a default camera padding:
public class MapScreen extends FragmentActivity implements GoogleMap.OnCameraChangeListener {
    ...
    private GoogleMap map;
    public static CameraPosition lastCameraPosition;
    public static MapScreen mapScreen;
    public static float CAMERA_INITIAL_TILT = 30.0f;
    public static int CAMERA_PADDING = 100;
    ...
    public void onCreate(Bundle savedInstanceState) {
        ...
        mapScreen = this;
        ...
        //Set up map object here like normal
        map = ((SupportMapFragment)(getSupportFragmentManager().findFragmentById(R.id.map))).getMap();
        ...
        //Set camera change listener
        map.setOnCameraChangeListener(this);
    }
    ...
}

In this class, you'll also need to add a method to listen and save the location of the camera when the first animation stops:
@Override
public void onCameraChange(CameraPosition position) {
    //Save the last camera position so we can reference it when tilting the camera following animations
    lastCameraPosition = position;
}

Also, add an inner class you can reference that performs the tilt after the first animation finishes (with a slight delay to get the correct CameraPosition):
public class tiltOnFinishAnimation implements CancelableCallback {

    @Override
    public void onCancel() {
        //Do nothing
    }

    @Override
    public void onFinish() {
        //We want to run the tilt animation, but the CameraPosition needed to center the camera in the right place
        //is only available after the onFinish() method completes.  So, we delay this by 10 ms to let the CameraPosition update
        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
          public void run() {
              mapScreen.runOnUiThread(new Runnable() {
                    public void run() {
                        if(lastCameraPosition != null){
                            //Finish with a tilt
                            CameraPosition cameraPosition = new CameraPosition.Builder()
                                .target(lastCameraPosition.target)
                                .zoom(lastCameraPosition.zoom)
                                .bearing(lastCameraPosition.bearing)
                                .tilt(CAMERA_INITIAL_TILT)
                                .build();
                            //Perform the tilt!
                            mapScreen.map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
                        }
                    }
                });
          }
        }, 10);
    }
}

Finally, when you want to move the camera, execute your normal code, but first identify some of the map view attributes needed for animating the camera correctly based on orientation, and include a reference to the callback to execute when the first part of the animation without the tilt stops:
//Get the View height and width, so we don't exceed the screen size after padding for the camera updates
int width;
int height;
if(mapFragment != null){
    width = mapFragment.getView().getWidth();
    height = mapFragment.getView().getHeight();
}else{
    //If the map fragment hasn't been instantiated yet, use the entire display
    if (android.os.Build.VERSION.SDK_INT >= 13){
        Display display = getWindowManager().getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);
        width = size.x;
        height = size.y;
    }else{
        Display display = getWindowManager().getDefaultDisplay();
        width = display.getWidth();
        height = display.getHeight();
    }
}

if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE){
    //Use verticle size for padding
    CAMERA_PADDING = (int) (height * 0.2f);
}else{
    //Use horizontal size for padding
    CAMERA_PADDING = (int) (width * 0.2f);
}

//Your code
markerList.add(m);
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (Marker marker : markerList) {
    builder.include(marker.getPosition());
}
LatLngBounds bounds = builder.build();

//Here's the new code below that triggers first the movement to the bounds, then the tilt (as a callback)
map.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, width, height, CAMERA_PADDING), new tiltOnFinishAnimation());

A: In order to set GoogleMap Tilt and Bound all marker you need to use following code.
googleMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 75));
CameraPosition camPos = new CameraPosition.Builder(googleMap.getCameraPosition())
                              .target(bounds.getCenter())
                              .bearing(bearing).tilt(45).build();
googleMap.animateCamera(CameraUpdateFactory
                              .newCameraPosition(camPos));

A: The key point is not having an animateCamera(..) followed by another animateCamera(..) without enough delay, as they overlap. So you should better use moveCamera(..) first and then animateCamera(..), or use some delay technique for the second animateCamera(..) such as new Handler().postDelayed(..).


text:
Q: Modify Variable within Method with Service I want to know the right way to handle this scenario: modify a variable within a method with a service.  I know you could just do:
$input = $this->modify($input)

But that doesn't feel like the correct OOP way of handling the situation.  Please see the inline comments.
class myClass {

    public function __construct(Service $service)
    {
        $this->service = $service;
    }

    public function work($input)
    {
        // $input = SOMETHING
        $this->service->modify($input);
        // $input = SOMETHING MODIFIED
        Entity::create($input);
    }

}

A: It can be achieved by passing in the input as reference:
public function modify(&$input) {
//                     ^ See what I did there?

A better approach would be to return the modified input, and assign it again:
$input = $this->service->modify($input);

Don't start messing with references until you know exactly what you're doing.