text:
Q: How to copy value and translations from one field to another in Odoo? Imagine you want to fill a field in the sale.order form with a default value, the same text will be used for each company that is being used in Odoo. Sometimes the usual way to proceed is to use a common field in the res.company model. Other option is to add a field that is filled with some other content in the res.partner form, when the customer is selected.
But the problem I found is: if I want to get the translations for that field, which are already in the original one, I would have to do it manually, inheriting the create method of ir.translation. When the field is copied to the sale.order form a record for the current used language is created, so I took advantage of it to create the rest of records. Is there a better way to do this?
Also, I would like to add that after saving the record I press the world icon to translate the text again, new translations are created with the current text. So I would need to translate everything again on every sale.order record.
I did this in the ir.translation model for a simple text field in order to create the translations of the rest of languages. The field field_to_translate is translatable on both sides:
@api.model
def create(self, vals):
    record = super(IrTranslation, self).create(vals)
    name = vals.get('name', False)  # name of the field to translate
    lang = vals.get('lang', False)  # creating record for this language
    if 'context' in dir(self.env):
        cur_lang = self.env.context.get('lang', False)  # current used language
        if name == 'sale.order,field_to_translate' and lang == cur_lang:
            langs = self.env['ir.translation']._get_languages()
            langs = [l[0] for l in langs if l[0] != cur_lang]   # installed languages

            for l in langs:
                if self.env.user.company_id.field_to_translate:
                    t = self.env['ir.translation'].search([
                        ('lang', '=', l),
                        ('type', '=', 'model'),
                        ('name', '=', 'res.company,field_to_translate')
                    ])
                    if t:
                        self.env['ir.translation'].create({
                            'lang': l,
                            'type': 'model',
                            'name': 'sale.order,field_to_translate',
                            'res_id': record.res_id,
                            'src': record.src,
                            'value': t.value,
                            'state': 'translated',
                        })

Ah, and I want to do this because I want to print them on different reports. The language of these report will depend on the customer lang field.
In short, how can I set a translatable field in res.company as a default value in other field in the sale.order model? The translations to other languages should be copied as well. My above proposal is kind of cumbersome

A: Well, finally I have created the translations in the create method of sale.order. I have used a customized translate_fields method of the ir.translation model in order to create the translations automatically and then I update all their values manually with the correct language translation.
On the other hand I found this class in the l10n_multilang module that can be useful for other people that may find the same problem:
class AccountChartTemplate(models.Model):
    _inherit = 'account.chart.template'

    @api.multi
    def process_translations(self, langs, in_field, in_ids, out_ids):
        """
        This method copies translations values of templates into new Accounts/Taxes/Journals for languages selected

        :param langs: List of languages to load for new records
        :param in_field: Name of the translatable field of source templates
        :param in_ids: Recordset of ids of source object
        :param out_ids: Recordset of ids of destination object

        :return: True
        """
        xlat_obj = self.env['ir.translation']
        #find the source from Account Template
        for lang in langs:
            #find the value from Translation
            value = xlat_obj._get_ids(in_ids._name + ',' + in_field, 'model', lang, in_ids.ids)
            counter = 0
            for element in in_ids.with_context(lang=None):
                if value[element.id]:
                    #copy Translation from Source to Destination object
                    xlat_obj._set_ids(
                        out_ids._name + ',' + in_field,
                        'model',
                        lang,
                        out_ids[counter].ids,
                        value[element.id],
                        element[in_field]
                    )
                else:
                    _logger.info('Language: %s. Translation from template: there is no translation available for %s!' % (lang, element[in_field]))
                counter += 1
        return True

    @api.multi
    def process_coa_translations(self):
        installed_langs = dict(self.env['res.lang'].get_installed())
        company_obj = self.env['res.company']
        for chart_template_id in self:
            langs = []
            if chart_template_id.spoken_languages:
                for lang in chart_template_id.spoken_languages.split(';'):
                    if lang not in installed_langs:
                        # the language is not installed, so we don't need to load its translations
                        continue
                    else:
                        langs.append(lang)
                if langs:
                    company_ids = company_obj.search([('chart_template_id', '=', chart_template_id.id)])
                    for company in company_ids:
                        # write account.account translations in the real COA
                        chart_template_id._process_accounts_translations(company.id, langs, 'name')
                        # copy account.tax name translations
                        chart_template_id._process_taxes_translations(company.id, langs, 'name')
                        # copy account.tax description translations
                        chart_template_id._process_taxes_translations(company.id, langs, 'description')
                        # copy account.fiscal.position translations
                        chart_template_id._process_fiscal_pos_translations(company.id, langs, 'name')
        return True

    @api.multi
    def _process_accounts_translations(self, company_id, langs, field):
        in_ids, out_ids = self._get_template_from_model(company_id, 'account.account')
        return self.process_translations(langs, field, in_ids, out_ids)

    @api.multi
    def _process_taxes_translations(self, company_id, langs, field):
        in_ids, out_ids = self._get_template_from_model(company_id, 'account.tax')
        return self.process_translations(langs, field, in_ids, out_ids)

    @api.multi
    def _process_fiscal_pos_translations(self, company_id, langs, field):
        in_ids, out_ids = self._get_template_from_model(company_id, 'account.fiscal.position')
        return self.process_translations(langs, field, in_ids, out_ids)

    def _get_template_from_model(self, company_id, model):
        out_data = self.env['ir.model.data'].search([('model', '=', model), ('name', '=like', str(company_id)+'\_%')])
        out_ids = self.env[model].search([('id', 'in', out_data.mapped('res_id'))], order='id')
        in_xml_id_names = [xml_id.partition(str(company_id) + '_')[-1] for xml_id in out_data.mapped('name')]
        in_xml_ids = self.env['ir.model.data'].search([('model', '=', model+'.template'), ('name', 'in', in_xml_id_names)])
        in_ids = self.env[model+'.template'].search([('id', 'in', in_xml_ids.mapped('res_id'))], order='id')
        return (in_ids, out_ids)


text:
Q: Permissions are not translating between windows and linux So I have an NFS mount which is provided by netapp. It is mounted from a client perspective on both linux and windows machines. If i create a file on the windows mount point then when i look at the permissions on linux the owner/group is "nobody" rather than my AD user.
I read that I should be configuring idmapd.conf on linux to have the domain and to use nsswitch. So i have configured idmapd.conf like so:
[General]

Verbosity = 0
Pipefs-Directory = /run/rpc_pipefs
# set your own domain here, if id differs from FQDN minus hostname
Domain = domain.ad.company.com

[Mapping]

Nobody-User = nobody
Nobody-Group = nogroup

[Translation]

Method = nsswitch

Other than this configuration. Is there anything else i might be missing? I keep seeing parts about matching UID and GID's, but why would I need to do that if i access both windows and linux via one active directory account?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Subset strings of the folder name in a vector I have the following vector of directories:
c(".", "./LRoot_1", "./LRoot_1/asd", "./LRoot_1/LClass_copepodo",
"./LRoot_1/LClass_shadow", "./LRoot_2", "./LRoot_2/asd", "./LRoot_2/LClass_bolha",
"./LRoot_2/LClass_cladocera")

I would to like get the the names of each element after LClass_ into a new vector.
Thanks

A: result = str_extract(x, pattern = "(?<=LClass_).*")
result
# [1] NA          NA          NA          "copepodo"  "shadow"    NA
# [7] NA          "bolha"     "cladocera"

A: In base R
 sub("LClass_", "", grep("LClass_", basename(v1), value = TRUE))
[1] "copepodo"  "shadow"    "bolha"     "cladocera"

Or with
regmatches(v1, regexpr("(?<=LClass_).*", v1, perl = TRUE))
[1] "copepodo"  "shadow"    "bolha"     "cladocera"


text:
Q: Calculating Pi with C I want to calculate pi but I am getting 3.058403 as a result. How can I fix this code?
#include <stdio.h>

int main(){
double x = 0;
float g =0;

printf("How many terms to calculate pi to? ");
scanf("%f", &g);

int n;
for (n = 0; n < g ; n++){

     double z = 1.0 / (2 * n + 1);
     if ((n % 2) == 1){
        z = z * -1;
     }
     x = (x + z);
     }
     double p = 4 * x;
    printf("The value of pi is: %f", p);
  return 0;
 }

A: This is not really an answer because the actual answer has been discussed in the comment section.
Corrected version of your code:

*

*removed pointless parentheses

*use meaningful variable names

*use of int for integer comparison

*declaration of variables as close as possible to their scope

*code formatted properly

#include <stdio.h>

int main() {
  printf("How many terms to calculate pi to? ");

  int nbofterms;
  scanf("%d", &nbofterms);

  double x = 0;

  for (int n = 0; n < nbofterms; n++) {
    double z = 1.0 / (2 * n + 1);
    if (n % 2 == 1) {
      z *= -1;
    }
    x = (x + z);
  }

  double pi = 4 * x;
  printf("The value of pi is: %f", pi);
  return 0;
}


text:
Q: document.getElementById for different "id" values or alternative to this code Actually I'm trying to create an "autosave" system for the content of some "" marked as contenteditable.
DIVS have an structure like his.

[..]

And there's a function like this, that works fine for only one div (when the user stops writing on a div save the data)
var timeoutId;
document.getElementById('test_one').addEventListener("input", function() {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(function() {
          function_to_save();
    }, 1000);
}, false);

The problem is that I try to use this same function for all the divs with a id name that includes the word "test", because all this names are generated dynamically...
I try to use regular expressions what I can't make that work... any idea or alternative code?

A: You could use querySelectorAll to get a nodeList
var elems = document.querySelectorAll("[id*='test']");

and as the question is marked jQuery
var elems = $('[id*='test']');

[id^='test'] will match all ids starting with test.
[id$='test'] will match all ids ending with test.
[id*='test'] will match all ids containing test.
With a nodeList you'd have to iterate
var elems = document.querySelectorAll("[id*='test']");

for (var i=elems.length; i--;) {
    elems[i].addEventListener("input", functionName, false);
}


text:
Q: How to find the nearest x,y co-ordinate from a particular pixel using python My goal is to find the nearest x,y point co-ordinate for every pixel. Based on that i have to colour the  pixel points.
Here is what i have tried,
The  below code will draw the points.
import numpy as np
import matplotlib.pyplot as plt

points = np.array([[0,40],[0,0],[5,30],[4,10],[10,25],[20,5],[30,35],[35,3],[50,0],[45,15],[40,22],[50,40]])
print (points)
x1, y1 = zip(*points)
plt.plot(x1,y1,'.')
plt.show()

Now to find the nearest point for each pixel.
I am found something like this where i have to give manually each pixel co-ordinates, to get the nearest point.
from scipy import spatial
import numpy as np
A = np.random.random((10,2))*100
print (A)
pt = np.array([[6, 30],[9,80]])
print (pt)
for each in pt:
    A[spatial.KDTree(A).query(each)[1]] # <-- the nearest point
    distance,index = spatial.KDTree(A).query(each)
    print (distance) # <-- The distances to the nearest neighbors
    print (index) # <-- The locations of the neighbors
    print  (A[index])

The output will be like this,
[[1.76886192e+01 1.75054781e+01]
 [4.17533199e+01 9.94619127e+01]
 [5.30943347e+01 9.73358766e+01]
 [3.05607891e+00 8.14782701e+01]
 [5.88049334e+01 3.46475520e+01]
 [9.86076676e+01 8.98375851e+01]
 [9.54423012e+01 8.97209269e+01]
 [2.62715747e+01 3.81651805e-02]
 [6.59340306e+00 4.44893348e+01]
 [6.66997434e+01 3.62820929e+01]]
[[ 6 30]
 [ 9 80]]
14.50148095039858
8
[ 6.59340306 44.48933479]
6.124988197559344
3
[ 3.05607891 81.4782701 ]

Instead of giving each point manually i want to take each pixel from the image and i wanted to find the nearest blue point. This is my first question.
After that i want to classify those points into two categories,
Based on pixel and point i want to colour it, basically i want to do a cluster on it.

This is not in proper form. But at the end i want it like this.
Thanks in advance guys.

A: *

*Use cKDTree instead of KDTree, which is faster (see this answer).

*You can give the kdtree an array of points to query instead of looping over all of them.

*Constructing a kdtree is a costly operation compared to querying it, so construct it once and query many times.

Compare the following two code snippets, on my tests the second one run x800 times faster.
from timeit import default_timer as timer

np.random.seed(0)
A = np.random.random((1000,2))*100
pt = np.random.randint(0,100,(100,2))

start1 = timer()
for each in pt:
    A[spatial.KDTree(A).query(each)[1]]
    distance,index = spatial.KDTree(A).query(each)
end1 = timer()
print end1-start1

start2 = timer()
kdt = spatial.cKDTree(A)  # cKDTree + outside construction
distance,index = kdt.query(pt)
A[index]
end2 = timer()
print end2-start2

A: you can use scikit-learn for this:
from sklearn.neighbors import KNeighborsClassifier
neigh = KNeighborsClassifier(n_neighbors=1)
labels = list(range(len(points)))
neigh.fit(points, labels)
pred = neigh.predict(np.random.random((10,2))*50)

if you want the points itself and not their class labels you can do
points[pred]


text:
Q: Is there a way to sum only the integers in a list of pairs that contain a letter and an integer in Prolog? I'm having trouble figuring out how to find the sum of the integers that are in a list of pairs like so:
[[a, 1], [b, 2], [c, 3], [d, 4]]

I tried something like this, since it is reminiscent of a regular sum function:
sum([], 0).
sum([[_,Head]|[_,Tail]], Sum) :-
    sum([_,Tail], Sum2),
    Sum is Head+Sum2.

With the call being:
sum([[a, 1], [b, 2], [c, 3], [d, 4]], Total),
write('Sum = '), write(Total).

But that doesn't work. It prints out false, when it should print out the sum, which would be 10 here.

A: I think it might help to split this into two tasks:

*

*create a new list of the second item of each sublist; and

*sum up that list.

This makes it easier to tackle the two problems, and furthermore you now have two extra predicates that can be used for other purposes.
We can obtain a list of the second item of the sublists with:
item2list([], []).
item2list([[_, X|_]|T], [X|T2]) :-
    item2list(T, T2).

or we can use maplist/3 [swi-doc] and nth1/3 [swi-doc]:
item2list(L1, L2) :-
    maplist(nth1(2), L1, L2).

or we can write item2list in terms of findall/3 [swi-doc] and member/2 [swi-doc]:
item2list(L1, L2) :-
    findall(X, member([_,X|_], L1), L2).

although here the predicate is not bidirectional.
For example:
?- item2list([[a, 1], [b, 2], [c, 3], [d, 4]], L).
L = [1, 2, 3, 4].

I leave summing up that list as an exercise.

A: In your attempt to define the predicate sum/2, you're not handling the lists of lists correctly. Try:
sum(Lists, Sum) :-
    sum(Lists, 0, Sum).

sum([], Sum, Sum).
sum([[_,N]| Lists], Sum0, Sum) :-
    Sum1 is Sum0 + N,
    sum(Lists, Sum1, Sum).

This version uses an accumulator to enable a tail-recursive definition. Sample call:
| ?- sum([[a, 1], [b, 2], [c, 3], [d, 4]], Sum).

Sum = 10
yes

A: Whenever a goal fails that you expect to succeed, see this as an opportunity to learn (short form for logic earn = earn logic). After all, this is Prolog which was meant to mean Programming in Logic. So where is the logic in your program?
For the moment your program fails, but you expected it to succeed. Where is the culprit? Let's generalize your program such that the resulting program still fails, but is much smaller. There are two easy ways to generalize a program:

*

*remove goals (by adding a prefix *)

*remove terms (replacing term by _/*term*/
We can do this pretty blindly. No need to understand your program. Just recheck that the goal still fails. Here is what I came up with on my first try:

:- op(950, fy, *).
* _G_0. % ignore the argument _G_0

sum([], _/*0*/).
sum([_/*[_,Head]*/|[_,Tail]], Sum) :-
    * sum([_,Tail], Sum2),
    * Sum is Head+Sum2.

?- sum([_/*[a, 1]*/, _/*[b, 2]*/, _/*[c, 3]*/, _/*[d, 4]*/], Total).
   false.                            % gnah - still fails

One problem has to be in the remaining visible part. Too difficult to figure out? Let Prolog explain it to you by querying the most general query:
?- sum(Xs, Sum).
   Xs = []
;  Xs = [_A,_B,_C].

So only two lengths of lists are possible: The empty list and a list with three elements. Note that we have currently a generalized version of the predicate. So there is no guarantee that we will find solutions for both lengths. However, we can be 100% sure that for all other lengths there will be no solution.
Let's get back at the original program and ask the most general query:
?- sum(Os, Total).
   Os = [], Total = 0
;  false.

Oh no, there is a single solution only. And not even a single solution for sum([_|_], Total).
So let's generalize the program again but now with respect to this failing goal:

sum([], _/*0*/).
sum([_/*[_,Head]*/|[_,Tail|_/*[]*/]], Sum) :-
    sum([_,Tail], Sum2),
    * Sum is Head+Sum2.

?- Os = [_|_], sum(Os, Total).
   false.

In this part there must be a further error. And in fact, the goal sum([_,Tail], Sum2) is the culprit: It is about a list of exactly two elements, but the rule wants at least three
For the actual fixes, see the other answers.
This method works for pure, monotonic programs such as yours.


text:
Q: How to reconstruct python source from loaded modules (sys.modules)? Is it possible to construct human readable source for loaded modules if you have access to sys.modules?
People tell me you cannot, but I'm sure it is possible in Python.

A: You can disassemble a Python-coded module using the dis module of the standard library: that produces definitely human readable source, just not Python source, but rather bytecode source.  Putting eggs back together starting from the omelette is a tad harder.
There used to be a decompiler for Python 2.3 (see here) but I don't know if anybody's been maintaining it over the last several years, which suggests there isn't much interest in this task in the open source community.  If you disagree, you could fork that project, making your own project with the goal of decompiling 2.7 (or whatever Python release you crave to decompile for), and attract others enthusiastic about this task -- if you can find them, that is.

A: Generally, the source code will be available in the file system, in places that can be easily discovered from sys.modules.
for name, mod in sys.modules.items():
    try:
        fname = mod.__file__
    except AttributeError:
        continue
    if fname.endswith(".pyc"):
        fname = fname[:-1]
    try:
        fcode = open(fname)
    except IOError:
        continue
    code = fcode.read()
    # .. do something with name and code


text:
Q: Is there a way to connect two browsers without WebRTC? I want to create a Peer to Peer connection with two browsers without using existing code (mostly). I want to implement the server infrastructure by myself, as well as the client code.
There is just one issue, WebRTC seems to be everywhere.
Don't get me wrong, I'd use it, but since this is for a school project I have to implement almost everything by myself.
Looking at the WebRTC source code, I expected some Javascript implementations of existing components, however, all I ended up seeing is very complex C++ code that is intended for web browser developers.
Is it possible to implement a Peer to Peer connection between two browsers without using WebRTC?

A: For security reasons browsers do not allow you to make UDP and TCP requests yourself. You need to use one of the 3 protocols provided by browsers

*

*HTTP

*WebSockets

*WebRTC

The C++ code you saw is the underlying implementation that browsers can use for WebRTC


text:
Q: Effect of Cosmological Expansion at the Atomic Level
Possible Duplicate:
Why does space expansion not expand matter?

Does cosmological expansion have any effects at the atomic level?

A: No. See: Expansion of the space-time metric and Why does space expansion not expand matter?.


text:
Q: Git overwrite master with a branch I cloned a repository and created a new branch. Forgot to checkout to new branch. Did the changes (deleted most of the files), added, commited and then pushed to remote. Now I've lost master.
Trying to return to previous state:
git checkout master
git reset --hard Tony_branch
git push -f origin master

Results in:
Total 0 (delta 0), reused 0 (delta 0)
remote: Processing changes: done
To ssh://<link> can't share the name obviously.
 ! [remote rejected] master -> master (non-fast forward)
error: failed to push some refs to

All answers suggest a "git pull". But it will re delete the files...
How can I fix this?
EDIT:
I am trying to retrieve old master by overwriting it with a branch I created before the changes... other ways might be better of course.

A: I don't know the exact state of your current repository, and therefore this answer might not work for you, at least not right out of the box.  Instead, I am giving steps which should have been followed as soon as you realized that pushing master was a mistake.
First, checkout a new branch from master locally:
# from master
git checkout -b Tony_branch_real

Then, revert the commits you made to master:
# again, from master
git revert A^..B

Here A represents the first unintended commit you made to master, and B represents the last unintended commit.  git revert will add a new commit to your master branch which functionally undoes whatever the (inclusive) range of commits A through B were doing.  Your actual command would look like more like this:
git revert dk93kg93^..k20gjei9

where A and B have been replaced with their SHA-1 hashes.  Check git log on your master branch to find the required SHA-1 hashes.
Finally, you only need to do a regular push of master to the remote:
git push origin master

This should work because all you have done locally is to add a new revert commit.
The reason we are avoiding doing things like hard reset on master is that perhaps this branch is shared by other developers.  Hard reset rewrites history, and therefore this is something we want to avoid for publicly shared branches.

A: It seems your remote will not accept a git push -f. So unless you can fix the branch protection on the remote (gitlab, github, bitbucket), you cannot undo the master branch.
However you can restore the files you did, in various way. One is to revert all commits, one by one, of master, until you are back to the original state.
Another way is to do
git checkout master
git reset --hard origin/master
git reset Tony_branch #soft reset on purpose
git add ... # all changes
git commit -m 'Reverting master to state before bad push'
git push origin master

A: There are basically 2 ways to fix a mistake like this.
One way is to do a history rewrite.  This is usually what the person who made the mistake wants, because it undoes the mistake almost entirely.  But it is not always feasible, and sometimes it's just not allowed.
The other options is to accept the mistake as part of history, and add a correction also to the history.
There are at least a couple ways to do each of these.

History Rewriting
It sounds like you know a suitable way to execute a history rewrite, but it isn't working because of the push -f step.  If you control the remote repo, you might be able to change permissions/protection settings to allow a forced push to master, but that's not necessarily a good idea, for two reasons:
First, protecting the master branch is probably a good idea most of the time, even if not in this specific instance.  OF course one could unprotect it, do the rewrite, and then re-protect it, if that were the only concern.
The second possible concern is, if any other clones have already pulled the errant commits into master, then force pushing to remove those commits from master's history will "break" those clones and they'll have to take steps to recover.  IF they follow the wrong steps, they could easily re-introduce the removed commits, and this is especially a concern if they have any new work based off of the commits you'd be undoing.  See the git rebase docs under "Recovering from upstream rebase"; even though what you're doing isn't a rebase per se, the same situation applies.
So it may well be that you need a solution that doesn't rewrite history, which is what I'll focus on for the duration.

Adding a Correction
Your repo might currently look like
... x <--(tony_branch)
     \
      A -- B -- C <--(master)(origin/master)

Now, you'd like to move origin/master to x; this would make the "cleanest" history.  (And, if we're being honest, it would avoid keeping a permanent record of the slip-up.  This is not to say that we have any reason to keep the record of the mistake; only that wanting to get rid of such a record can feel more important than it is, weighed against the cost of a history rewrite.)
But you've read this far because apparently rewriting origin/master's history isn't a viable option.  So generally people will suggest using git revert.  This would result in something like
... x <--(tony_branch)
     \
      A -- B -- C -- ~CBA <--(master)(origin/master)

where ~CBA reverses the changes from A, B, and C, leaving the content (TREE object) at master just like what was at x.  That's one option; it's simple and leaves things in a straightforward state for any future git commands.
Anther option is to use a merge commit for the revert.  This makes A, B, and C look like a side branch that was abandoned.  The "up side' is that it's a little easier to see that A..C can/should be ignored; the "down side' is that the merge in question will be a bit unnatural - what is sometimes called an "evil merge".  If you're likely to rebase this section of commits, then the "evil merge" could be an issue - but then again, since we go there because history rewrites of master aren't a thing, maybe that doesn't matter.  Anyway, this would end up looking more like
... x <--(tony_branch)
    |\
    | \---------- Y <--(master)(origin/master)
     \           /
      A -- B -- C

To do this, you could say
git checkout master
git reset --hard tony_branch
git merge -s ours origin/master
git push

Note that whichever way you go about this, commits A through C are incorporated into master's history.  That means it is no longer possible to "re-apply" your branch's changes by merging those commits into master - because they're "already there".  To fix this, you can create copies of commits A through C and put those copies on tony_branch.  This can be done before or after updating master (by revert or by merge); before might be a tad easier, but I didn't include the instructions there because it was easier to explain why here.
So what you would do is a "forced rebase" of A through C.  Contrary to popular belief, rebase does not 'replace' the source commits, but rather it copies them.  The force operation just means "make the copies even though I'm not really changing the base or anything else".  The first step is to check out C.  How to do that depends on what other steps you've taken:
(A) After applying the merge to master, you could
git checkout master^2

which puts you in detached HEAD state on the 2nd parent of the merge commit at master.  OR
(B) After instead applying a revert, you could
git checkout master^

(if the revert was applied in a single commit; it would be something like master~3 if individual revert commits were used, replacing 3 with however many actual revert commits were used).  OR
(C) Before fixing master, you could simply
git checkout --detach master

but note that you do want to end up in "detached HEAD" state to avoid incorrect movement of the master branch; hence the --detach option.
Now having C checked out, you can
git rebase -f tony_branch
git branch -f tony_branch

and you get something like
      A' -- B' -- C' <--(tony_branch)
     /
... x ----------- Y <--(master)(origin/master)
     \           /
      A -- B -- C

A: If you are not confident with reset/revert, I would do the below steps instead of doing reset/revert:
(let's assume the branch name you created before the changes is "good-master-branch")

*

*Switch your git main branch from master to another (for example, "good-master-branch")

If you are using tools like github, or bitbucket, you can do the setting in the GUI.

*Delete your current bad master branch

First, make sure you are not on master branch git checkout good-master-branch
delete local git branch -D master
delete remote git push origin --delete master

*Create a new master branch with the good code

git checkout good-master-branch
git checkout -b master

*Set the new 'master' branch as your git main branch

Now, you have a new & clean master branch!


text:
Q: Continuity of a composition map between Holder spaces Let $\varphi\in C^{\infty}_0(\mathbb{R})$, $0<\alpha<1$, $\Omega\subset\mathbb{R}^d$ be a bounded domain.
Is it true that the map $\Phi:C^{0,\alpha}(\bar{\Omega})\to C^{0,\alpha}(\bar{\Omega})$ defined by
\begin{eqnarray}
\Phi(u):=\varphi\circ u
\end{eqnarray}
is continuous? Or are there any props similar to this?

A: This is true, and here is an approach:
$$
\varphi\circ(u+h)-\varphi\circ u = h \int_0^1 \varphi'\circ(u+th)\,dt
$$
On the right, the Hölder norm of the integral is controlled by the derivatives of $\varphi$ and the Hölder norm of $u+th$. It remains to use multiplicative property: $[uv]_\alpha\le C[u]_\alpha[v]_\alpha$. The latter holds because
$$
|u(x)v(x)-u(y)v(y)|\le |u(x)| |v(x)-v(y)|+|u(x)-u(y)||v(y)| \le 2|x-y|^\alpha [u]_\alpha [v]_\alpha $$
and similarly for the supremum part of the $C^\alpha$ norm:
$$
\sup_x|u(x)v(x)|\le \sup_x|u(x)| \sup_x|v(x)| \le [u]_\alpha [v]_\alpha $$


text:
Q: Python appending list Trying to change a list so i can generate a password
passwordlength=int(input('Enter how long you would like the password')) # The user input

for x in range(0,passwordlength):
       password=''.join(characters)
       print(password)

That is what i am working with now. Characters is what i am using for my list. This is giving me for the input the list repeated for the input number.
Every time i try and use a append to the list i just end up going backwards
Any help would be appreciated

A: I think random.sample may be what you want:
from random import sample

passwordlength = int(input('Enter how long you would like the password')) # The user input

password = ''.join(sample(characters,passwordlength))

Or else take a slice up to passwordlength:
password = ''.join(characters[:passwordlength])

To validate the user input we can use a try/except and a while loop:
from random import sample

while True:
    try:
        password_length = int(input('Enter password length between 1-{}'.format(len(characters)))) # The user input
        if password_length > len(characters):
            print("Password is too long")
            continue
        password = ' '.join(sample(characters,password_length))
        break
    except ValueError:
         print("Please enter digits only")

If you have ints in your character list you will need to map  to str before joining.
password = ' '.join(map(str,sample(characters,password_length)))

A: Here is some is a mock set up.  Where choice will randomly choice an item from a list
from random import choice

myaplha = #somelist of letters to choice from
password = int(input("Enter password length")):

passw = []
for i in range(password):
    passw.append(choice(myaplha))
print("".join(passw))

or
password = "".join([choice(myaplha) for i in range(int(input("Enter password length")))])
print(password)

A: Try it like this:
passwordlength=int(input('Enter how long you would like the password')) # The user input
characters=['1','2','3','4','5','a','b','b']
password=[]
for x in range(0,passwordlength):
       password.append(characters[x])

print(''.join(password))

A: I'm sorry, but this question isn't completely clear.
Here are the assumptions that I am making here:

*

*passwordlength is an integer containing the length to truncate to (which is in the code)

*characters is a list of characters / numbers that you want to use for the password.  e.g. characters = ['1', '2' ,'a' , 'c', 'd'] etc.

I don't understand what you are trying to do with the for loop?
I believe the following should do what you want.
password = ''.join(characters)[0:passwordlength]


text:
Q: If inertial mass were equal to for example half of gravitational mass why would things not still fall at same rate? I have read that it is the equality of inertial and gravitational mass that causes all objects to fall at the same rate irrespective of size. But if this were not true, what effect would we see? Would inertial mass being half g-mass mean an object twice as massive would accelerate twice as fast? If so, why?
EDIT: Here is where it is asserted that the equality is responsible for all objects falling at same rate:
Why do two bodies of different masses fall at the same rate (in the absence of air resistance)?

A: Objects would be accelerated by gravity at a uniform rate regardless of their mass provided that inertial mass and gravitational mass were proportional. There's no requirement for them to be identical, from that perspective.

A: Say you have Earth's mass as $M$ and your object's mass and distance from Earth is $m$ and $r$
Using Newtonian gravity we have the Force experiences by the object to be $F_g = \frac{GMm}{r^2}$ where $G$ is a constant.
Now the force experienced by earth due to the object's mass is $F_{g2} = \frac{GMm}{r^2}$
Acceleration of both objects, $F_1 = ma_1 \to \frac{GMm}{r^2} = ma_1$ so $a_1 = \frac{GM}{r^2}$
$F_2 = \frac{GMm}{r^2} = Ma_2 \to a_2 = \frac{Gm}{r^2}$
The acceleration that the earth experiences is negligible in comparison. The acceleration the object experiences is only due to Earth's mass.
(Note that for considerably large objects the acceleration due to the object's mass would make it seem like the object is accelerating quicker towards Earth than other objects because Earth is moving towards the object fairly quickly too)
If inertial mass $F = ma$ was different from the gravitational mass you would just have a different acceleration for each object BUT every object would still be accelerated at the same magnitude.
ex: $m_g = \frac{m_i}{2}$ then $F_g = \frac{GMm_g}{r^2} = m_ia$ so that $a = \frac{GM}{2r^2}$ and you'd have halved acceleration.

A: Assume that Force by each if $W = \frac{GM_gm_g}{R^2}$
Where $m_g$ and $M_g$ are the gravitational masses of both body under test and earth respectively
Suppose that $m_i$ is the body inertial mass
Assuming $m_i=km_g$
Where k is not 1 but a proportionality constant
Newton 2nd law:
$W = \frac{GM_gm_g}{R^2}=k m_g a$
Where $a$ is the acceleration
==>
$a=\frac{G M_g m_g}{k R^2}$ ==> independent of the both values of $m_i$, and $m_g$, but different than the case when:
k=1
The acceleration is different in its absolute value but independent of the inertial/gravitational mass of the falling body


text:
Q: Android: Unable to listen for SMS sent I have written an App to display SMS sent. But my Content Observer is not getting triggered with the following code, when am SMS is sent from default messaging app instead it triggers with URI "content://sms".
    SMSSentObserver smsSentObserver = new SMSSentObserver(null, this);
    ContentResolver contentResolver = this.getContentResolver();
    contentResolver.registerContentObserver(Uri.parse("content://sms/sent"), true, smsSentObserver);

Can some one please tell me why? I have added permission to READ_SMS.
   <uses-permission android:name="android.permission.READ_SMS" />

Basically I need to save the SMS sent on my App. Any help is appreciated.
EDITs:
I tried adding "android.permission.SEND_SMS" as permissions
Here is my SMSSentObserver:
public class SMSSentObserver extends ContentObserver {
    private final Context _context;

    public SMSSentObserver(Handler handler, Context context) {
        super(null);
        _context = context;
    }

    @Override
    public void onChange(boolean selfChange) {
        saveSentSMS();
        super.onChange(selfChange);
    }

    private void saveSentSMS() {
        Uri uriSMSURI = Uri.parse("content://sms/sent");
        Cursor cur = this._context.getContentResolver().query(uriSMSURI, null, null, null, null);

        if(null == cur) {
            return;
        }

        if(cur.moveToFirst()) {
            String strProtocol = cur.getString(cur.getColumnIndex("protocol"));
            if(null != strProtocol) { //for sent messages protocol will be null.
                return;
            }

            int type = cur.getInt(cur.getColumnIndex("type"));
            if(type == 2) {
                String strSMSBody = cur.getString(cur.getColumnIndex("body"));
                String strPhoneNo = cur.getString(cur.getColumnIndex("address"));
                long smsDateTime = cur.getLong(cur.getColumnIndex("date"));
                String serviceCenter = cur.getString(cur.getColumnIndex("service_center"));
                String strStatus = cur.getString(cur.getColumnIndex("status"));
                String strPerson = cur.getString(cur.getColumnIndex("person"));
                Log.e("Info", "SMS saved");
            }
        }
    }
}

Thank you


text:
Q: What is optimal value for Phusion passenger PassengerMaxRequestQueueSize I know this depends on the box hardware, but for example if there are set 100 processes, the default queue is also 100. Does it makes sense to increase PassengerMaxRequestQueueSize to 200 or 300? Probably this depends on free memory. Thoughts?
The best answer will be explaining the setting and probably one or two examples, assuming the server process requests for 2-3 seconds.
Thanks in advance!

A: Why you should limit queuing
Any requests that aren't immediately handled by an application process, are queued. Queuing is usually is bad: it often means that your server cannot handle the requests quickly enough.
A larger queue means that requests are less likely to be dropped. But this comes with a drawback: during busy times, the larger the queue, the longer your visitors have to wait before they see a response. This causes them to click reload, making the queue even longer (their previous request will stay in the queue; the OS does not know that they've disconnected until it tries to send data back to the visitor), or causes them to leave in frustration.
So having a limit on the queue is a good thing. It limits the impact of the above situation.
You should ensure that requests are queued as little as possible. That could mean:

*

*Making your app faster (if your workload is CPU bound).

*Upgrading to faster hardware (if your workload is CPU bound).

*Increasing your app's concurrency settings (if your workload is I/O bound), e.g. by increasing the number of processes or threads.

If you cannot prevent requests from being queued, then the next best thing to do is to keep the queue short, and to display a friendly error message upon reaching the queue limit. Something like, "We're sorry, a lot of people are visiting us right now. Please try again later." The documentation for PassengerMaxRequestQueueSize tells you how to do that.
Optimal value for the queue size
It's hard to say what the optimal queue size should be. A good rule of thumb is: set the request queue size to the maximum number of requests you can handle in one second. Depending on your situation you may have to tweak things a little bit.
This rule of thumb comes from the notion of expected burst traffic. How many simultaneous requests do you expect on your server?
Suppose that your queue size is 100, and that for whatever reason you receive 150 requests at the same time. Suppose that your server is fast enough to handle 150 requests in half a second, so you know it's not a performance problem. But if you have a request queue size of 100, then 50 of those requests will be dropped with a "Request queue full" error.
In such a situation, you should set the queue size to the maximum number of concurrent requests that you think you can safely handle without performance issues.

A: This SO question and the Passenger docs here talk more about working with this. If you want more information about why this is happening on your server you can try running passenger-status (usually you need to run this as root).
If you would like to set a custom error page when visitors see this issue you can use the following (in Apache) to set a custom error page:
PassengerErrorOverride on
ErrorDocument 503  /error503.html

As mentioned by Hongli you can also change the setting PassengerMaxRequestQueueSize to a higher number to queue more requests.  You can also set this to 0 and disable it (for most situations this is not an optimal solution however).
For reference, the default error message a visitor to your site will see when bumping against this limit is:
This website is under heavy load

We're sorry, too many people are accessing this website at the same time. We're working on this problem. Please try again later.


text:
Q: What would you avoid re-inventing at all costs? We recently had to re-invent a high-availability queueing engine like RabbitMQ (for various reasons).
Naturally this turned out to be more time consuming and expensive than expected.
What type of things would you avoid rebuilding at all costs?  Which types of components should rather be reused?

A: Just follow the cost benefit analysis. You should avoiding re-inventing all things that Cost_To_Acquire + Maintenance_Cost + Risk is higher then the costs to build the component.
Cost to Acquire can be the cost to purchase a license, pay training or just spend hours studying.
The Risk is far higher for any new product: it is not fully tested, has not known problems, has no community around it, and any plug-ins/tweaks will have to be reinvented.


text:
Q: Custom resources in Android (different vocabularies) I have a problem in Android java where I want to have different vocabularies in different languages.
The app is used by the military and police force in Germany and Sweden.
Of course the germans want the app in german and the swedes want it in Swedish and that is of course taken care of by putting string resources under res/values-de/strings.xml and res/values-sv/strings.xml and is selected by different settings in the Android device (see Resource handling).
But my problem is that the police-force uses a different vocabulary than the military force wich I want to reflect in some way in the resources. Is there any way to have different vocabulary-resource that i can set in app f.ex by having a res/values-de-mil/strings.xml or in any ohther simple way.

A: I don't think it's possible. An option would be to set the preferences of the user in shared preferences (you could ask that when the user open the app for the first time) and store if it's a policeman or a military.
Then you could use reflection to load your strings resources.
<string name="string_policeMan">Word for a policeman</string>
<string name="string_military">Word for a military</string>

SharedPreferences shared = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
boolean isPoliceMan = shared.getBoolean(policeMan, false);

int resId;
if(isPoliceMan)
   resId = R.string.class.getField("string_policeMan").getInt(null);
else
   resId = R.string.class.getField("string_military").getInt(null);

 String field = context.getResources().getString(resId);

A: There is actually a way to do this, namely by (ab)using quantity strings. Just for academical purposes I'll give you a proof of concept below, but as a warning up front: know that this approach does not generalize to any locale. For German and Swedish, however, you should be fine.
For the theory behind quantity strings (or plurals, as they're usually referred to as Android resources) please have a read here. It also has an explanation for why the approach outlined below does not generalize to any locale. I'm going to assume that will all make sense, so let's fast forward to the proof of concept.
values-de/plurals.xml
<resources>
    <plurals name="hello_im_in_the">
        <item quantity="one">Hallo, ich bin in der Armee.</item>
        <item quantity="other">Hallo, ich bin auf der Polizei.</item>
    </plurals>
</resources>

values-sv/plurals.xml
<resources>
    <plurals name="hello_im_in_the">
        <item quantity="one">Hej, jag är på militären.</item>
        <item quantity="other">Hej, jag är på polisen.</item>
    </plurals>
</resources>

Let's use above resources in an activity with four TextViews: two for every locale, and one for every 'force' (police force vs. military that is).
@Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.res_activity_layout);

    int policeForceQuantity = 0;
    int militaryQuantity = 1;

    TextView militaryTextViewDe = (TextView) findViewById(R.id.military_de);
    TextView policeForceTextViewDe = (TextView) findViewById(R.id.police_force_de);

    Configuration config = new Configuration(getResources().getConfiguration());
    config.locale = Locale.GERMAN;
    getResources().updateConfiguration(config, getResources().getDisplayMetrics());
    String militaryText = getResources().getQuantityString(R.plurals.hello_im_in_the, militaryQuantity);
    String policeForceText = getResources().getQuantityString(R.plurals.hello_im_in_the, policeForceQuantity);
    militaryTextViewDe.setText(militaryText);
    policeForceTextViewDe.setText(policeForceText);

    TextView militaryTextViewSv = (TextView) findViewById(R.id.military_sv);
    TextView policeForceTextViewSv = (TextView) findViewById(R.id.police_force_sv);

    config = new Configuration(getResources().getConfiguration());
    config.locale = new Locale("sv");
    getResources().updateConfiguration(config, getResources().getDisplayMetrics());
    militaryText = getResources().getQuantityString(R.plurals.hello_im_in_the, militaryQuantity);
    policeForceText = getResources().getQuantityString(R.plurals.hello_im_in_the, policeForceQuantity);
    militaryTextViewSv.setText(militaryText);
    policeForceTextViewSv.setText(policeForceText);
}

All above does is use a quantity of 1 to 'select' military phrases, and any other value (0 in this example) for phrases specific to the polic force. For the sake of the example, I'm simply changing the locale at runtime so we get to see the results side by side, and without actually having to go into the device's locale settings.
Result:

In other words, this shows we were able to successfully take advantage of Android's locale system, and use a predefined quantity to select the military phrase or police force phrase for displaying.
Not pretty, and definitely not what quantity strings were intended for, but it will get the job done in your specific use case.

A: As far as I know its not possible to have res/values-de-mil as android system does not know who the user is. You can do this approach have 2 sets of strings.
For e.g.you have a
<string name="Name">...</string>
make it as
<string name="mil_Name">...</string>
<string name="cop_Name">...</string>
Now if u know that the user is military then getResources().getString(R.string.mil_Name);


text:
Q: Prolog setOf with Multiple Predicates In my prolog database, I have below facts:
played('Sharon rose', piano).
played('Robert Kay', piano).
played('Kelvin Cage', drums).
singer('Robert Kay').
band_leader('Sharon rose').

I want to print out all the names uniquely as a single list.
Below is my query using setof and the output:
setof(X, (played(X,_);singer(X);band_leader(X)), Output).

Output = ['Robert Kay','Sharon rose'] ? ;

Output = ['Kelvin Cage'] ? ;

Output = ['Robert Kay','Sharon rose']

yes

However, the output isn't what I want.
I want it to print out the names uniquely as a list.

A: You get multiple answers due to the anonymous variable in the goal argument of setof/3. Try instead:
?- setof(X, Y^(played(X,Y);singer(X);band_leader(X)), Output).


text:
Q: Android code to stop thread service running in back ground Hi here is the code to run the service in back ground. It is working fine. But it is not getting stopped when operation is finished. Here is my code. I am unable to stop service once data is sent to server and i am calling delete method to delete data in sqlite and mythread.stop(); to stop thread but it is not getting stopped. who to stop thread is there any solution for that.
public class ServiceTest extends Service {

    List<NameValuePair> nameValuePairs;

    String timerss=null,additional=null;

    String loc=null;

    int localUname = 0;

    String sno;

    String deviceid;

    List<Contact> contacts;

    private static String TAG = ServiceTest.class.getSimpleName();
    private MyThread mythread;
    public boolean isRunning = false;

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate");
        mythread  = new MyThread();
    }

    @Override
    public synchronized void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy");
        if(!isRunning){
            mythread.interrupt();
            mythread.stop();
        }
    }

    @Override
    public synchronized void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        Log.d(TAG, "onStart");
        if(!isRunning){
            mythread.start();
            isRunning = true;
        }
    }

    public void readWebPage(){
        DatabaseHandler db = new DatabaseHandler(ServiceTest.this);
        contacts = db.getAllContacts();
        for (Contact cn : contacts) {
            String log = " USERNAME: "
                    + cn.getID() + " ,loc: " +cn.getName();

            localUname =  cn.getID();
            sno = String.valueOf(localUname);
            loc = cn.getName();
            timerss = cn.getPhoneNumber();
//          deviceid = cn.getMacId();
//          additional = cn.getAdditonal();

            System.out.println("benbenarji:" + localUname + loc+timerss+deviceid+additional);

            System.out.println("benbenarji1:" + localUname + loc);

        }
        try {

            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://ip:80808/ActIotWifiLockApp/LockWebServices/storeLogForUD");
            //add your data
            nameValuePairs = new ArrayList<NameValuePair>(4);
            nameValuePairs.add(new BasicNameValuePair("slno", sno));
            nameValuePairs.add(new BasicNameValuePair("macId", deviceid));
            nameValuePairs.add(new BasicNameValuePair("logdesc", additional));
            System.out.println("logdes:" + additional);
            nameValuePairs.add(new BasicNameValuePair("dateTime", "timerss"));
            nameValuePairs.add(new BasicNameValuePair("username", "loc"));

            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            //Execute HTTP Post Request
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            final String response = httpclient.execute(httppost, responseHandler);

            System.out.println("ResponseScan: " + response);

//            runOnUiThread(new Runnable() {
//                public void run() {
//
//                    dialog.dismiss();
//                }
//            });

            if (response.contains("true")) {

                db.deleteAllData();
                mythread.interrupt();
                mythread.stop();

            } else {
                Log.e("ServiceHandler", "Couldn't get any data from the url");
            }

        } catch (Exception e) {
            System.out.println("Exception : " + e.getMessage());
        }
    }

    class MyThread extends Thread{
        static final long DELAY = 10000;
        @Override
        public void run(){
            System.out.println("ben:"+isRunning);
            while(isRunning){
                Log.d(TAG,"Running");
                try {
                    readWebPage();
                    Thread.sleep(DELAY);
                } catch (InterruptedException e) {
                    isRunning = false;
                    e.printStackTrace();
                }
            }
        }

    }

}

A: Your implementation of onDestry contains the line
if(!isRunning){

Could it be that you need to say:
if(isRunning){

because I assume you want to stop the thread if isRunning is true.
Besides this, the documentation reminds us of the following:

it is your responsibility to stop the service when its work is done, by calling stopSelf() or stopService().


text:
Q: My project is on Google App Engine(webapp2). I am not able to import firebase-admin I am developing my web app using webapp2. I have tried to setup firebase-admin but I am not able to import it. The firebase-admin files are in the lib folder.I have also added the lib folder by vendor.add.
If I import the firebase-admin using lib.firebase-admin it works. But there are alot of imports in the init.py folder of the firebase-admin. Thus even those imports are not working.
from firebase_admin import auth
The above line of code
'from firebase_admin import auth' does not work. But 'lib.firebase_admin import auth' works. This is a workaround which isnt feasible.
The stack trace is below:
Traceback (most recent call last):
  File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2-2.5.2\webapp2.py", line 1535, in __call__
    rv = self.handle_exception(request, response, e)
  File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2-2.5.2\webapp2.py", line 1529, in __call__
    rv = self.router.dispatch(request, response)
  File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2-2.5.2\webapp2.py", line 1278, in default_dispatcher
    return route.handler_adapter(request, response)
  File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2-2.5.2\webapp2.py", line 1102, in __call__
    return handler.dispatch()
  File "C:\Users\Farrukh Bin Rashid\Documents\Internship\Blog-GoogleSearchAPI - Firebase Admin\Blog\controllers\Handler.py", line 10, in dispatch
    webapp2.RequestHandler.dispatch(self)
  File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2-2.5.2\webapp2.py", line 572, in dispatch
    return self.handle_exception(e, self.app.debug)
  File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2-2.5.2\webapp2.py", line 570, in dispatch
    return method(*args, **kwargs)
  File "C:\Users\Farrukh Bin Rashid\Documents\Internship\Blog-GoogleSearchAPI - Firebase Admin\Blog\controllers\Home.py", line 22, in get
    default_app = firebase_admin.initialize_app()
  File "C:\Users\Farrukh Bin Rashid\Documents\Internship\Blog-GoogleSearchAPI - Firebase Admin\Blog\lib\firebase_admin\__init__.py", line 62, in initialize_app
    credential = credentials.ApplicationDefault()
  File "C:\Users\Farrukh Bin Rashid\Documents\Internship\Blog-GoogleSearchAPI - Firebase Admin\Blog\lib\firebase_admin\credentials.py", line 128, in __init__
    self._g_credential, self._project_id = lib.google.auth.default(scopes=_scopes)
  File "C:\Users\Farrukh Bin Rashid\Documents\Internship\Blog-GoogleSearchAPI - Firebase Admin\Blog\lib\google\auth\_default.py", line 281, in default
    credentials, project_id = checker()
  File "C:\Users\Farrukh Bin Rashid\Documents\Internship\Blog-GoogleSearchAPI - Firebase Admin\Blog\lib\google\auth\_default.py", line 111, in _get_gcloud_sdk_credentials
    from google.auth import _cloud_sdk
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\devappserver2\python\runtime\sandbox.py", line 1174, in load_module
    raise ImportError('No module named %s' % fullname)
ImportError: No module named google.auth```

A: If you are using Python 2.7 on App Engine, you will need to follow these steps in order to use this library. If you are using Python 3.7, you can just use your requirements.txt and won't need to use vendor.add().


text:
Q: AWS ruby gem as if is not installed When I try to run a really small program that was nly suposed to test if I can connect to the amazon dynamoDB I get an error as if I havent installed the aws gem...
My code is the following:
require "AWS"

AWS.config(  access_key_id: ENV["coco"],
secret_access_key: ENV["xixi"]
)

DB = AWS::DynamoDB.new

And I have the following error:
 reducer.rb:4:in `<main>': uninitialized constant AWS (NameError)

The gem is installed as you can see here:
Bernardos-MacBook-Pro:cn bersimoes$ gem which aws
/Users/bersimoes/.rvm/gems/ruby-1.9.3-p286/gems/aws-2.6.0/lib/aws.rb

Any help is appreciated!

A: You've got the wrong gem. You want aws-sdk for AWS::DynamoDB support. Install with:
gem install aws-sdk

You might need to uninstall the existing aws gem to ensure you load the right one (they both have an aws.rb file). Alternatively you could use gem 'aws-sdk' in your code before your require to ensure the correct gem is loaded. Another possibility is to require 'aws-sdk' since the gem provides that file basically as an alias.
Also you should use:
require 'aws' # note lower case

This probably won't cause problems on a Mac, but will cause issues if you ever move your code to a case-sensitive machine like Linux.

A: If you are receiving this error and you have the "aws-sdk" gem installed, you likely have upgraded to version 2 of the aws-sdk gem unintentionally. Version 2 uses the Aws namespace, not AWS. This allows version 1 and version 2 to be used in the same application.
See this blog post for more information.

A: Yeah i just ran into this issue and resolved. It is because AWS updated their gem to 2.0. If you update the gem to 2.0 different configuration is required according to this article they posted.
If you want to using the version you had before, just change the Gemfile like below:
Gemfile
gem 'aws-sdk', '< 2.0'


text:
Q: Thread.UncaughtExceptionHandler with multiple threads Our Android application uses several threads.

*

*The usual UI thread

*A communication layer ( a sticky service ) running several threads to connect to a socket.

*And few more, to load images, videos...

We currently have just one UncaughtExceptionHandler defined in our Application:
public class OurApplication extends MultiDexApplication {

    public void onCreate (){
        super.onCreate();

        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread thread, Throwable e) {
                //...
            }
        });
    }
}

Making some research about this concern we found this ( In this post. ), and we start thinking about every thread :

Basically, you have to implement your own instance of an UncaughtExceptionHandler, then you will have to make sure that for every thread your App runs you call setUncaughtExceptionHandler.

Since we still have some exceptions, basically coming from the sticky service, that are not handled by the UncaughtExceptionHandler we are thinking that the handler is not properly set for some threads.
Because the default handler is a static variable of java.lang.Thread this not seems to be possible and having just one handler within the Application seems to be enough.
Can this be caused for example if the service starts before having defined the handler into the Application?
EDIT:
Our service doesn't run on a separate process :
<service
    android:name=".servicios.ServiceBoot"
    android:action="com.aplicaty.soapbox.MyService"
    android:enabled="true"
    android:exported="true" >
</service>

Any hints or ideas is welcome.


text:
Q: How can i get Id item number in entity data model i'm trying to check the login information ,,, and get the item Id if they are correct ,,, Otherwise show error entry message
my code is:
var getid = from user in db.tables
            where user.name == tbusername.Text && user.password == tbpassword.Text
            select user.Id;

c = Int32.Parse(getid);

but the vs say there's an error at c = Int32.Parse(getid); What's wrong?

A: You cant convert a list to an integer. Where returns a collection, (or said better an IEnumerable). You are pushing a list of something into a space (Int32.Parse) that only wants a 1 of something.
Also if your Id is an int, you shouldn't have to parse it
Example
var getid = (from user in db.tables
            where user.name == tbusername.Text && user.password == tbpassword.Text
            select user.Id).FirstOrDefault();

// or
var getid = db.tables.Where(user => user.name == tbusername.Text && user.password == tbpassword.Text)
                     .Select(user => user.Id)
                     .FirstOrDefault();

if(getid == null)
{
    MessageBox.Show("Oh nooez!!!");
    return;
}

MessageBox.Show("You is id : " + getid );

Enumerable.FirstOrDefault Method (IEnumerable)

Returns the first element of a sequence, or a default value if the
  sequence contains no elements.

Enumerable.Where Method (IEnumerable, Func)

Filters a sequence of values based on a predicate.

Return Value

Type: System.Collections.Generic.IEnumerable An
  IEnumerable that contains elements from the input sequence that
  satisfy the condition.


text:
Q: Scanning through process memory I want to write a process scanner to detect malicious code and I need to scan every section of a PE executable loaded in memory. I've been wondering how to do it and it seems to me that there are two viable solutions:

*

*ReadProcessMemory

Pros: easy to use
Cons: must read and copy memory to a buffer, can't read the whole process memory because of the limited buffer, searching is also difficult because of the little "window" of memory copied to the buffer at a time

*

*Inject a DLL into the process' memory

Pros: Able to access directly process memory, no copy required
Cons: "injecting" is frowned upon by several security programs and it's a rather tricky method, plus I need to copy also the data the program needs to work with
My question is: is there another method to accomplish a complete memory scan of another process' memory (given that I have the privileges to do that) ?
If not: how should I deal with the need to scan the whole memory if I need to read one little "window" at a time?


text:
Q: an idiom or verb for "pretend to great learning" What is a verb to describe the act of pretending that you know a lot of things? In other words, is there a verb that describe how a 'sciolist' behave?

He always [pretends to great learning].

Idioms also work but preferably an idiomatic verb phrase not like know-it-all e.g.
In my native language we use "sell knowledge" meaning act or say sth as if you are very knowledgeable but you are not, you just pretend it and what you know at best is nothing more than surface knowledge. I want to find an English equivalent. By the way it has a negative connotation actually it's disapproving.

A: In a negative sense:

a smarty-pants

or

a mister know-it-all

You could also say:

Why are you pretending to be so smart?

For a person who is intelligent or learned, informally we use smart a lot.

A: I think the term smart-aleck is commonly used to describe this behavior... I found no verb matching it, but you can say "He's always such a smart-aleck".
Other related terms are pseudo-intellectual (used either as a noun to refer to a person who pretends to be an intellectual, or as an adjective), and pseudo-scholarship (noun, describes work pretended to have scholarly value).
I could not find a catchy verb for either of these. I think "pretend to great learning" could be understood, but is probably lengthy and awkward. If you want something similar, "pretend to be an intellectual" would be more natural.


text:
Q: Is it possible to set access priority to files in windows i am working on a system that has 2 parts. the parts are as follow:
1- a producer application that generate and append files in space A, and i cannot modify it ( i must not make noise for this part).
2- a transformer application that copies the files from space A(near the part1) to Space B.
. If part 2 starts to copy a file from A to B and during the copying of the file, part1 wants to append the same file, the part1 will stopped, because the file is under control of part2.
I want to if the part1 wants to append the file, control of the file granted to part 1, and it's not important to what happens for part2.
IS it possible to do that in windows??

A: If you are working within one computer system (not via network), then in general the correct way would be to monitor the writes, made by part 1, as they happen, and copy the written data on-the-fly. This is achieved using a file system filter driver, which intercepts write operations and captures the data being written.


text:
Q: Display  validation errors inside  I have a hidden <p:fileUpload> which is opened via <h:outputLabel>.
<p:messages id="message" autoUpdate="true" />

<h:form id="form">

    <p:fileUpload id="file-input" auto="true"
        allowTypes="/(\.|\/)(gif|jpe?g|png)$/" sizeLimit="10"
        invalidSizeMessage="wrong size" fileUploadListener="#{bean.image}"
        update="@form message" style="display: none;"
        invalidFileMessage="wrong file" />

    <h:outputLabel for="file-input_input">
        <h:graphicImage name="images/dummy.jpg" />
     </h:outputLabel>

    <h:outputText value="#{bean.file.fileName}" />
    <br />
    <h:outputText value="#{bean.file.size}" />
</h:form>

Unfortunately, no messages are displayed after validation failed (e.g invalid size or invalid file). Those messages are displayed inside the <p:fileUpload> content box instead of in <p:messages>.
How can I display those messages inside <p:messages> instead of inside <p:fileUpload>?

A: The validation is performed fully client side without hitting the server. So you can't control this from server side on.
The message container of the <p:fileUpload> is available via messageContainer property of the widget variable. Simple let jQuery move it into the <p:messages> when clicking the label:
<p:messages id="messages" ... />

<h:form>
    <p:fileUpload id="file-input" widgetVar="file-input" ...
        styleClass="ui-helper-hidden" />
    ...
    <h:outputLabel for="file-input_input" ...
        onclick="PF('file-input').messageContainer.appendTo($('#messages'));" />
</h:form>

(I only renamed <p:message id> to be more sensible, and used a PrimeFaces specific class to hide it instead of an inline style)
The onstart and oncomplete attributes of <p:fileUpload> weren't usable as they are only executed when the client side validation has passed and the file upload request is actually sent.


text:
Q: Holding Arrays not in RAM I am learning (and trying to teach) electronics/programming with some friends.  We have decided to build a LED cube using a launchpad for our task.
Here's the issue we run into:
For our animations, we store them in a two dimensional array.
   We get error if we define array as constant
I don't want this array to be in RAM, because we don't have very much available.
EDIT:  See below for code
I hope this is posted in the correct place.
At not time (I think?) am I changing any array, they are all set one time by hand and just looped over.  I'm unsure of what is trying to be (implicitly?) converted
Info if needed:
MSP430G2553
16kB Flash
0.5kB RAM
Thanks for your help
UPDATE:
  Well HansPassant told me why that error was showing up.  But I still get a RAM overflow (Apparently it isn't being stored in flash?)
Another thing I tried is instead of #define RON (Row ON) I declared it as const too.   (so when an animation array was created, it was created explicitly with only constants)  I had hoped that would store it in flash.
Here's the entirety of code if needed:
#define povDelay delayMicroseconds(200) // POV Delay

const int CON = LOW;
const int COFF = HIGH;
const int RON = HIGH;
const int ROFF = LOW;

const int col[9] = {P1_0, P1_1, P1_2, P1_3, P1_4, P1_5, P2_0, P2_1, P2_2};
const int row[3] = {P1_6, P1_7, P2_3};

void setup()
{
 // Serial.begin(9600);
  for (int i = 0; i < 9; i++)
  {
    pinMode(col[i], OUTPUT);
    digitalWrite(col[i], COFF);
  }
  for (int i = 0; i < 3; i++)
  {
    pinMode(row[i], OUTPUT);
    digitalWrite(row[i], ROFF);
  }
}

void sideToSide(int delayTime)
{
  int sideDelay = 1000;
  // Left Frame
  const int leftFrame[3][9] = {
     {CON, COFF, COFF, CON, COFF, COFF, CON, COFF, COFF},
     {CON, COFF, COFF, CON, COFF, COFF, CON, COFF, COFF},
     {CON, COFF, COFF, CON, COFF, COFF, CON, COFF, COFF}
   };
  // Middle Frame
  const int middleFrame[3][9] = {
     {COFF, CON, COFF, COFF, CON, COFF, COFF, CON, COFF},
     {COFF, CON, COFF, COFF, CON, COFF, COFF, CON, COFF},
     {COFF, CON, COFF, COFF, CON, COFF, COFF, CON, COFF}
    };
  // Right Frame
  const int rightFrame[3][9] = {
     {COFF, COFF, CON, COFF, COFF, CON, COFF, COFF, CON},
     {COFF, COFF, CON, COFF, COFF, CON, COFF, COFF, CON},
     {COFF, COFF, CON, COFF, COFF, CON, COFF, COFF, CON}
   };

  // Display this animation 3 times (Frame 1, Frame 2, Frame 3, Frame 2)
  for (int i = 0; i < 4; i++)
  {
    displayFrame(leftFrame, delayTime);
    displayFrame(middleFrame, delayTime);
    displayFrame(rightFrame, delayTime);
    displayFrame(middleFrame, delayTime);
  }
  // Last animation
  displayFrame(leftFrame, delayTime);

} // ############ END SIDE TO SIDE

void frontToBack(int delayTime)
{
    // Left Frame
  const int frontFrame[3][9] = {
     {CON, CON, CON, COFF, COFF, COFF, COFF, COFF, COFF},
     {CON, CON, CON, COFF, COFF, COFF, COFF, COFF, COFF},
     {CON, CON, CON, COFF, COFF, COFF, COFF, COFF, COFF}
   };
  // Middle Frame
  const int middleFrame[3][9] = {
     {COFF, COFF, COFF, CON, CON, CON, COFF, COFF, COFF},
     {COFF, COFF, COFF, CON, CON, CON, COFF, COFF, COFF},
     {COFF, COFF, COFF, CON, CON, CON, COFF, COFF, COFF}
    };
  // Right Frame
  const int backFrame[3][9] = {
     {COFF, COFF, COFF, COFF, COFF, COFF, CON, CON, CON},
     {COFF, COFF, COFF, COFF, COFF, COFF, CON, CON, CON},
     {COFF, COFF, COFF, COFF, COFF, COFF, CON, CON, CON}
   };

  // Display this animation 3 times (Frame 1, Frame 2, Frame 3, Frame 2)
  for (int i = 0; i < 4; i++)
  {
    displayFrame(frontFrame, delayTime);
    displayFrame(middleFrame, delayTime);
    displayFrame(backFrame, delayTime);
    displayFrame(middleFrame, delayTime);
  }
  // Last animation
  displayFrame(frontFrame, delayTime);

}  // ############# END FRONT TO BACK

void diagFunctionOne(int delayTime)
{
  const int firstFrame[3][9] = {
     {CON, COFF, COFF, COFF, COFF, COFF, COFF, COFF, COFF},
     {CON, COFF, COFF, COFF, COFF, COFF, COFF, COFF, COFF},
     {CON, COFF, COFF, COFF, COFF, COFF, COFF, COFF, COFF}
  };
  const int secondFrame[3][9] = {
     {COFF, CON, COFF, CON, COFF, COFF, COFF, COFF, COFF},
     {COFF, CON, COFF, CON, COFF, COFF, COFF, COFF, COFF},
     {COFF, CON, COFF, CON, COFF, COFF, COFF, COFF, COFF}
  };
  const int thirdFrame[3][9] = {
     {COFF, COFF, CON, COFF, CON, COFF, CON, COFF, COFF},
     {COFF, COFF, CON, COFF, CON, COFF, CON, COFF, COFF},
     {COFF, COFF, CON, COFF, CON, COFF, CON, COFF, COFF}
  };
  const int forthFrame[3][9] = {
     {COFF, COFF, COFF, COFF, COFF, CON, COFF, CON, COFF},
     {COFF, COFF, COFF, COFF, COFF, CON, COFF, CON, COFF},
     {COFF, COFF, COFF, COFF, COFF, CON, COFF, CON, COFF}
  };
  const int fifthFrame[3][9] = {
     {COFF, COFF, COFF, COFF, COFF, COFF, COFF, COFF, CON},
     {COFF, COFF, COFF, COFF, COFF, COFF, COFF, COFF, CON},
     {COFF, COFF, COFF, COFF, COFF, COFF, COFF, COFF, CON}
  };
  // Start from 7
  const int sixthFrame[3][9] = {
     {COFF, COFF, COFF, COFF, COFF, COFF, CON, COFF, COFF},
     {COFF, COFF, COFF, COFF, COFF, COFF, CON, COFF, COFF},
     {COFF, COFF, COFF, COFF, COFF, COFF, CON, COFF, COFF}
  };
  const int seventhFrame[3][9] = {
     {COFF, COFF, COFF, CON, COFF, COFF, COFF, CON, COFF},
     {COFF, COFF, COFF, CON, COFF, COFF, COFF, CON, COFF},
     {COFF, COFF, COFF, CON, COFF, COFF, COFF, CON, COFF}
  };
  const int eighthFrame[3][9] = {
     {CON, COFF, COFF, COFF, CON, COFF, COFF, COFF, CON},
     {CON, COFF, COFF, COFF, CON, COFF, COFF, COFF, CON},
     {CON, COFF, COFF, COFF, CON, COFF, COFF, COFF, CON}
  };
  const int ninthFrame[3][9] = {
     {COFF, CON, COFF, COFF, COFF, CON, COFF, COFF, COFF},
     {COFF, CON, COFF, COFF, COFF, CON, COFF, COFF, COFF},
     {COFF, CON, COFF, COFF, COFF, CON, COFF, COFF, COFF}
  };
  const int tenthFrame[3][9] = {
     {COFF, COFF, CON, COFF, COFF, COFF, COFF, COFF, COFF},
     {COFF, COFF, CON, COFF, COFF, COFF, COFF, COFF, COFF},
     {COFF, COFF, CON, COFF, COFF, COFF, COFF, COFF, COFF}
  };

    for (int i = 0; i < 4; i++)
  {
    displayFrame(firstFrame, delayTime);
    displayFrame(secondFrame, delayTime);
    displayFrame(thirdFrame, delayTime);
    displayFrame(forthFrame, delayTime);
    displayFrame(fifthFrame, delayTime);
    displayFrame(sixthFrame, delayTime);
    displayFrame(seventhFrame, delayTime);
    displayFrame(eighthFrame, delayTime);
    displayFrame(ninthFrame, delayTime);
    displayFrame(tenthFrame, delayTime);
  }
}

/*

#####################################################
#####################################################
#####################################################
######################################################
#######################################################

*/

// Takes a frame and displays it for the length of animation delay (in ms)
void displayFrame(const int frame[3][9], int animationDelay)
{
 // Serial.println("displayFrame called");
 unsigned long currentTime = millis();

 while (1) // Do this continually until animationDelay is met
 {
 int i, j;
 // Rows
 for (i = 0; i < 3; i++)
 {
   // Turn correct ROW on
   digitalWrite(row[i], RON);

   // Columns
   for (j = 0; j < 9; j++)
   {
     // Turn correct COLUMNS on
     digitalWrite(col[j], frame[i][j]);

   } // End J loop

   povDelay;
   digitalWrite(row[i], ROFF);

 } // End I Loop

 if ((millis() - currentTime) >= animationDelay)
 {
   delay(10);
   // Cleanup, Turn all OFF
  for (int i = 0; i < 9; i++)
    {
      digitalWrite(col[i], COFF);
    }
    for (int i = 0; i < 3; i++)
    {
      digitalWrite(row[i], ROFF);
    }

   delay(10); // timefix?

   return;

 } // End time test if statement

 }

}

void loop()
{
  diag(350);
  sideToSide(350);
  frontToBack(350);

//  for (int i = 0; i < 9; i++)
//  {
//    digitalWrite(col[i], CON);
//  }
//  for (int i = 0; i < 3; i++)
//  {
//    digitalWrite(row[i], RON);
//    delay(250);
//    digitalWrite(row[i], ROFF);
//  }

}

And the error that exists:

c:/users/dan/appdata/local/energi~1/hardware/tools/msp430/bin/../lib/gcc/msp430/4.6.3/../../../../msp430/bin/ld.exe:

region `ram' overflowed by 142 bytes
      collect2: ld returned 1 exit status

A: not sure this will help, but to ld you can specifiy the memory area to use, see the docs.
That apart, you're wasting much space for a bit, using an integer. The easier way to reduce memory: change const int frontFrame[3][9] to const BYTE frontFrame[3][9], after declaration of typedef unsigned char BYTE.
You can spare more if you use bits to represent bits:
#define ON(b) (1 << b)

const int frontFrame[3] = {
     {ON(8) | ON(7) | ON(6)},
     {ON(8) | ON(7) | ON(6)},
     {ON(8) | ON(7) | ON(6)}
};

and you will test a bit (in displayFrame) using
for (int r = 0; r < ROWS_NUM; ++r)
  for (int c = 0; c < COLS_NUM; ++c)
    if (frame[r] & ON(c)) { ... }

I would also try to add static in front of data declaration, but most probably this would have no effect on memory placement.


text:
Q: How can I make the icon font color on a windows 7 prof desktop work? I have C:\Windows\Web\Wallpaper\Scenes\img25.jpg as wallpaper (I think it's a standard windows wallpaper.) The desktop icon font color is white. It cannot be read without heavy eye pain. I want it to be black.

I couldn't change the icon font color in advanced properties (ie the good old window color settings dialog) for aero for windows 7 professional x32. I've heard that the icon font color should change automatically to suit my needs, it doesn't work as advertised in my scenario.
How could I fix it and rescue my eyes from popping out?
EDIT screenshot attached. sorry for bad english.

A: You an customize your desktop icon using Iconoid tool. Its freeware and easy to configure  now you can do whatever you want with your desktop icon.

A: Since the icon font is dynamic you have to find a work around.
Go into Control Panel. At the top there is an arrow by "Control Panel" click that and find Performance Information and Tools. Click it.
You should now be at a page where the machine gives you a base score. On the left hand panel click adjust visual effects. Now comes the fun part, click 'adjust for best appearance' and play with the boxes until your desired effect.


text:
Q: Beamer and pseudocode I am preparing a presentation with beamer from a previous paper written in latex. I want to insert in a slide the pseudocode
    \begin{algorithm}
\begin{algorithmic}[1]
\FOR{$i=1$ to $N$}
\FOR{$j=1$ to $JJJJ}
\STATE $energy[i*JJJ+j] =$ \\
$ interpolate(AAA[i*JJJ+j], ZZZ)$
\ENDFOR
\ENDFOR
\end{algorithmic}
\caption{pseudocode for the calculation of }
\label{alg:seq}
\end{algorithm}

but I get problems since the beamer document does not compile. I tried to use the same packages that in the latex document. I also tried to find examples through google but nothing. Could you tell me what is wron here or how could I add pseudocode in beamer )examples on the net, etc)?

A: The floating object algorithm doesn't behave well with beamer (which onviously disables floating objects). To prevent problems you can 1) use the H placement specifier for algorithm, or 2) drop the algorithm environment and use the \captionof command from the caption package if a caption is needed. The following example shows the first approach:
\documentclass[12pt]{beamer}
\usepackage{algorithm,algorithmic}

\begin{document}

\begin{frame}

\begin{algorithm}[H]
\begin{algorithmic}[1]
\FOR{$i=1$ to $N$}
\FOR{$j=1$ to $JJJJ$}
\STATE $energy[i*JJJ+j] =$
$ interpolate(AAA[i*JJJ+j], ZZZ)$
\ENDFOR
\ENDFOR
\end{algorithmic}
\caption{pseudocode for the calculation of }
\label{alg:seq}
\end{algorithm}
\end{frame}

\end{document}

A: *

*Load the required packages (for example algorithmic and algorithm2e or algorithm)

*Use the float package with H option for the floating algorithm environment option to get a fixed position

*Use the fragile option for the frame if you get strange errors, it can fix problems with verbatim text and listings

Compilable example:
\documentclass{beamer}
\usetheme{Singapore}
\usepackage{algorithm2e}
\usepackage{algorithmic}
\usepackage{float}
\begin{document}
\section{Test}
\begin{frame}[fragile]
\begin{algorithm}[H]
\begin{algorithmic}[1]
\FOR{$i=1$ to $N$}
\FOR{$j=1$ to $JJJJ$}
\STATE $energy[i*JJJ+j] =$ \\
$ interpolate(AAA[i*JJJ+j], ZZZ)$
\ENDFOR
\ENDFOR
\end{algorithmic}
\caption{pseudocode for the calculation of }
\label{alg:seq}
\end{algorithm}
\end{frame}
\end{document}

A: Yeah. None of this works for me. I have been scouring for answers for two or three days and seen yet other solutions that don't work for me. I'm betting that if you're using latex 2020 by han the tanh then you're here reading this. Go ahead and downvote me all you want, but you can always make it look good enough with tabbing inside of a block environment. You can even enclose each printing line within an uncover for extra dramatic effect.
\begin{frame}
  \frametitle{My Procedure}
\begin{block}{}
\begin{tabbing}
  \uncover<2- | alert @2>{My\=Fun($x,y$)\=\\}
  \uncover<3- | alert @3>{\>Let $\ell=1,$ \>~~$\epsilon_0=1,w_0=x,$ and $z_0=y$\\}
  \uncover<4- | alert @4>{\>While \>$(\epsilon_{\ell-1} >$ tol $)$\\}
  \uncover<5- | alert @5>{\>\>Let $w_{\ell}$ be the solution to $w = G(w z_{\ell-1})$\\}
  \uncover<6- | alert @6>{\>\>Let $z_{\ell}$ be the solution to $z = G(w_{\ell-1} z) + H(z)$\\}
  \uncover<7- | alert @7>{\>\>Let $\epsilon_{\ell}= |w_{\ell} - w_{\ell-1}| + |z_{\ell} - z_{\ell-1}|$\\}
  \uncover<8- | alert @8>{\>End While\>\\}
  \uncover<9- | alert @9>{End MyFun\>\\}
\end{tabbing}
\end{block}
\end{frame}

A: We add a new slide to Beamer documentation, using this \begin{frame}...\end{frame} and algorithm using \begin{algorithm}...\end{algorithm}
 If you try to directly embed algorithm in the frame it would not work.
Therefore use  \scalebox{}{...}
Syntax:
\begin{frame}
    \scalebox{1}{\begin{algorithm}...\end{algorithm}}
\end{frame}

https://beerensahu.wordpress.com/2014/11/17/documentation-how-to-write-algorithms-in-latex-beamer-slids/


text:
Q: enable_profile_selector with FB javascript SDK Regarding this information: http://developers.facebook.com/docs/reference/rest/stream.publish
Parameters: target_id and uid description says:
If I want to publish as page, I should use the 'enable_profile_selector' option with FB.login. This option enables the profile selector on the permission dialog. as I understood enable_profile_selector it's not permission but send it as GET parameter, then when user is asked permissions he can choose profile, if I am a facebook page admin then I can choose page page profile.
So basically problem is where to enable 'enable_profile_selector' and how pass "enable_profile_selector" parameter with javascript sdk.

A: Here anyway I wanted to get the page access token.So I used this method
 https://developers.facebook.com/docs/authentication/pages/


text:
Q: bash color not working I have some issues with color. It works fine on one line but not on the other 2
 echo "  \e[35mWeather.......:\e[0m `echo "\e[36m$weather\e[0m" | head -1`"
    echo "  \e[35mToday.........:\e[0m `echo "\e[36m$weather\e[0m" | head -2 | tail -1`"
    echo "  \e[35mTomorrow......:\e[0m `echo "\e[36m$weather\e[0m" | tail -1`"

A: Go through your own code step by step.
When you have a multi-line variable and you do this:
"\e[36m$weather\e[0m"

it adds \e[36m to the beginning of the whole variable. It doesn't add the code to the beginning of each and every line in that variable; just to the first line. So the output is something like this:

\e[36mCurrently in Struer, DK: 8 °C and Cloudy
High: 9 C Low: 7 C Mostly cloudy
High: 8 C Low: 8 C Cloudy, a shower; windy\e[0m

So when you take only the 2nd or 3rd line, they do not come with the color code, because there was nothing that would it there. To make it work the way you want, swap the operations – first extract the line you want, then add color codes to the result:
echo "  \e[35mToday.........:\e[0m \e[36m$(echo "$weather" | head -2 | tail -1)\e[0m"


text:
Q: windows 10 git shell gitignore and VC.db the foo.vc.db file is rendering git unusable. I downloaded a gitignore file from
https://github.com/github/gitignore/blob/master/VisualStudio.gitignore  . now it seems to have the right stuff as *.VC.db is there, however when I do git pull I see git is NOT ignoring my foo.VC.db file and the merge fails

A: If you want to gitignore files which are already tracked by git you need to remove them from the git cache first and then add them:
git rm --cached -r . && git add --all


text:
Q: Finding all functions satisfying $\int^x_0f(t)dt=f(x)-1$
I want to find all functions that satisfy $$\int^x_0f(t)dt=f(x)-1$$

It's easy to check that $e^x$ satisfies this equation. Also, from Newton-Libnitz one can verify that the above equality implies $f(x)=f'(x)$, so I suspect that all solution are of the form $ce^x$.
Now, looking at the equation, only function of the form $ce^x$ to satisfy this equation is $e^x$. Is it really the only function to satisfy this property or am I missing something?
Any help would be appreciated.

A: Yes, that is correct. You can also say that$$0=\int_0^0f(t)\,\mathrm dt=f(0)-1,$$and that therefore $f(0)=1$. And the only function of the form $x\mapsto ce^x$ that maps $0$ into $1$ is the exponential function.


text:
Q: Need to monitor an SSR with an arduino I need to monitor the coil side of an SSR (not actually a coil I know). The problem with my circuit is it allows enough current through the resistor divider to 0V to actually turn on the SSR. Just wondering if anyone has a better way. I initially designed it thinking the SSR circuit would have been PNP.

A: Wire the LED of a 6N137 in series with the SSR input (most SSRs draw no more than 10mA for 3-32V in, which you should verify).
Add a pullup resistor on the 6N137 output, plus power and ground.
Done.

You could also do this slightly cheaper by wiring a PNP transistor base in series with the high side (with a parallel resistor of perhaps 1K) and keep your divider. The optocoupler gives more isolation from EMI coupled back through the SSR.
Edit:
If you can't open the circuit, you can just increase the resistors by 100:1 (say 2M and 500K), add a 10nF cap to ground and use a 2N7000 transistor to buffer the voltage. Input to the ATTiny85 alone would actually work too (typical <50nA leakage), typically, but 1uA max leakage is too much to absolutely guarantee it. 2N7000 is 100nA max.
If you have access to both sides of the SSR you could just parallel the SSR input with a resistor but it sounds like that's another unstated limitation.


text:
Q: Configure LocalSearch UnionMove via JavaAPI Various aspects of OptaPlanner configuration can be specified in the XML config then overridden via JavaAPI. For example you can set a default TerminationConfig in your XML then at runtime switch it for a user specified value.
The docs seem to indicate that it should be possible, but I haven't found any examples. The context is that I'm hoping to dynamically alter the UnionMove section of the config and omit Swap moves if the instance to be solved doesn't have at least 2 planning entities. Currently this results in lots of Bailing from infinite logging when users are experimenting with small problems.

A: Taken from https://www.optaplanner.org/docs/optaplanner/latest/planner-configuration/planner-configuration.html#solverConfigurationByJavaAPI :
private SolverConfig template;

public void init() {
    template = SolverConfig.createFromXmlResource(
            "org/optaplanner/examples/nqueens/solver/nqueensSolverConfig.xml");
    template.setTerminationConfig(new TerminationConfig());
}

// Called concurrently from different threads
public void userRequest(..., long userInput) {
    SolverConfig solverConfig = new SolverConfig(template); // Copy it
    solverConfig.getTerminationConfig().setMinutesSpentLimit(userInput);
    SolverFactory<NQueens> solverFactory = SolverFactory.create(solverConfig);
    Solver<NQueens> solver = solverFactory.buildSolver();
    ...
}

In your case, you would need to modify the Phase List of the SolverConfig (see the SolverConfig Javadocs ); the move selectors can be gotten and set via LocalSearchPhaseConfig and ConstructionHeuristicPhaseConfig (you need to use instanceof when iterating phase list to determine which one to cast to).
The bailing from infinite logging sound like a bug.


text:
Q: Is apps.ubuntu.com deprecated? I'm trying to visit https://apps.ubuntu.com and to search for an app. However, it seems based on this screenshot, that this website only supports Ubuntu versions up to Ubuntu 14.04. Is this correct, or am I missing something?

Edit: karel correctly pointed out that although "Ubuntu 14.04 (trusty)" is listed in the search interface of apps.ubuntu.com, it doesn't do anything:

What is going on at apps.ubuntu.com?

A: Ubuntu Apps Directory is deprecated.
All searches to Ubuntu Apps Directory no longer connect to that website. Instead they are redirected to https://snapcraft.io/store. Even though Ubuntu 12.04 is currently an End Of Life release it is still possible to search for Ubuntu 12.04 packages using rmadison <package-name>. The rmadison program is provided by the devscripts package from the default Ubuntu repositories.
I've known about this since September, 2016, and now it is becoming apparent to the community that it's time to move on: What do we do about the links to apps.ubuntu.com?, and now two years later the consensus is that we should stop adding links to apps.ubuntu.com.
What follows was correct at the time that it was originally posted, but it is obsolete now that Ubuntu Apps Directory is no longer available.

Ubuntu Apps Directory only supports Ubuntu versions from Ubuntu 10.04 to Ubuntu 13.10, all of which are End Of Life versions except for Ubuntu 12.04. Packages from more recent supported releases of Ubuntu can be searched for at Ubuntu Packages Search.
Ubuntu 14.04 is listed in the Ubuntu Apps Directory, but it's not searchable there. Instead it's searchable at Ubuntu Packages Search.
It's obvious from comparing Ubuntu Apps Directory with Ubuntu Packages Search that supported releases at Ubuntu Packages Search receive more support than unsupported releases at Ubuntu Apps Directory do, but I am not going to conjecture about whether this is by coincidence or by design or the reasons official or otherwise why this disparity exists.
In addition to searching for packages in all the currently supported releases, Ubuntu Packages Search also supports searching for packages from the second latest release even if that release is an EOL release, and sometimes it even supports searching for packages from the third latest release as well. For example in September, 2018 the gcc package from the second latest release, Ubuntu 17.10, can still be found at https://packages.ubuntu.com/artful/gcc as shown in the screenshot. This is useful when you need to download and install a missing package for 17.10 in order to upgrade it to 18.04, even if 17.10 is currently an End Of Life release.

A: Canonical have probably forgotten to update apps.ubuntu.com for the new current release Ubuntu 16.10 or the current LTS release Ubuntu 16.04. I can see no announcement anywhere that apps.ubuntu.com is deprecated, it seems to be some sort of mistake on their part.
Clearly, this is not a great experience, before you could choose to find packages on apps.ubuntu.com for the latest release of Ubuntu (in addition to command-line tools and packages.ubuntu.com), but now you can't. I think most people haven't noticed, because for apps that used to exist in the Ubuntu repositories and continue to exist (like Blender), everything still works as it should.
I've filed these two bug reports about it:

*

*Current Ubuntu release not in apps.ubuntu.com

*"firefox" is not found for Ubuntu 14.04 on apps.ubuntu.com


text:
Q: Unable to create a file from a path in Vim I have often PATHs for files which do not exist in my codes.
I run as my cursor is at a PATH which does not exist
CTRL-W f

I get
E447: Can't find file "~/bin/editors/emacs/python_mode" in path

The long way of creating new file is
Ctrl-W v
:args [copy_paste_the_path_with_mouse]

Do you know any short way of creating a new file in Vim when you have PATHs for files in a file which do not exists yet?
I would like to create a new file simply by
CTRL-W f

A: If you do :h E447 to look up the error message you received, you will see this:
...
If you do want to edit a new file, use:
    :e <cfile>
To make gf always work like that:
    :map gf :e <cfile><CR>

So try this:
:nmap <C-w>f :e <cfile><CR>

A: :e path_to_file
:w!

I don't think there's a built in key combination for reading in the clipboard for the new file.
You should be able to use key maps for this or a custom script.
See this question  and vim.org for more info.
Hope that helps

A: To avoid having to copy-paste with the mouse you can do :edit ^R^P to copy the path/filename at the cursor position into the command line.  For more info do :help ^R^P


text:
Q: WebRequest timed out in windows service I use WebRequest in a client to consume a web service on Internet. Each request is triggered in a separate thread.
It works well if hosting the client in IIS. But most of the requests will get timed out error if the client is hosted in a windows service.
When I tried to debug the problem using Fiddler, the WebRequest worked well as all traffic went through 127.0.0.1:8888
Without Fiddler, the traffic goes to Internet directly through a random port, and the time out problem hits again.
The windows service runs under Local System account.
Why do I get time out if the client is in windows service without using a proxy?
Update: My original question wasn't clear. The requests are made concurrently (or at a very short interval). This is to do with the connection limit in the ServicePoint class. By default only 2 connections are allowed to the same external destination. If the destination is local, the limit will be int.Max value. That's why fiddler can magically fix the problem with the proxy. So I manually set the DefaultConnectionLimit to 100 and the requests are on wire.
Adjusting HttpWebRequest Connection Timeout in C#

A: The most common source of problems that is "magically" fixed by running Fiddler is when your .NET code fails to call Close() on the object returned by GetResponseStream(). See http://www.telerik.com/automated-testing-tools/blog/13-02-28/help-running-fiddler-fixes-my-app.aspx for more details.


text:
Q: Printing math with user input: Can't convert float to str implicitly Here's the code :
import time
time.sleep(0.7)

while True:
    print("Enter the word 'quit' to quit the calculator :(")
    print("Enter the word 'freenet' to enroll the SSHcrack")
    user_input = input(": ")

    if user_input == "quit":
        break
elif user_input == "freenet":
    num1 = float(input("Enter a Port to Crack:"))
    num2 = input("Enter a Network Name")
    num3 = float(input("Enter an IP-Address,(without symbols!):"))
    result = num3 / num1
    result2 = result / 13
    print("Injectable SSH "+ result2 +"for the Network "+num2)

Of course this is just a calculator (I only added the problem code block) and I wanted to test around with the print statement, but it gives me this TypeError:
Traceback (most recent call last):
  File "<mypath>", line 51, in <module>
    print("Injectable SSH "+ result2 +"for the Network "+num2)
TypeError: Can't convert 'float' object to str implicitly

A: As the error message states: You have to convert 'float' to str explicitly.
This fixes your problem:
print("Injectable SSH "+ str(result2) + " for the Network " + str(num2))

Even better, use format strings:
print("Injectable SSH {} for the Network {}".format(result2, num2))

They help you keeping your message formatting clean, structured and transparent.

A: You have to explicitly convert result2 and num2 to strings.
print("Injectable SSH "+ str(result2) +"for the Network "+ str(num2))

A: The problem is that you're attempting to add a float (decimal) to a string in the line
print("Injectable SSH "+ result2 +"for the Network "+num2)

"Interjectable SSH " is a string and result2 is a float, and python has no way of knowing how to add a decimal to a string.  Some languages will automatically convert the float into a string, but python will not, hence the error "Can't convert 'float' object to str implicitly".
What you need to do is explicitly convert both result2 and num2 into strings using the built in str() method.  With the necessary changes, the line wil look something like this:
print("Injectable SSH "+ str(result2) +"for the Network "+str(num2))

There are a couple other ways that you can do this in python.  If you want to look into that, look up a tutorial in "python string formatting".

A: In python, '+' is used to concatenate string objects.
Ofcourse in python 2.7, you would have done concatenation/joining of any type of object for a print using a ','.
So, the solution may be like:
   print("Injectable SSH "+ str(result2) +"for the Network "+num2)