text:
Q: Add background image to html.div in Dash-plotly I know how to add a background image to a plotly graph object, however, is it possible to add background image for html.Div or html.H1 ?

A: Here is a working example demonstrating how to add a background-image using inline styles.
import dash
from dash.dependencies import Input, Output
import dash_core_components as dcc
import dash_html_components as html
from pandas_datareader import data as web
from datetime import datetime as dt
import plotly.graph_objs as go

app = dash.Dash()
app.layout = html.Div(children=[
    html.H1('Hello Dash', style={'background-image': 'url(https://upload.wikimedia.org/wikipedia/commons/2/22/North_Star_-_invitation_background.png)'})
    ])

if __name__ == '__main__':
    app.run_server(debug=True)


text:
Q: mysql jdbc connection with SSL fails at tls handshake level Our mysql server is configured to accept only connection with ssl cipher DHE-RSA-AES256-GCM-SHA384.
I am using java mysql-connector-java (8.0.15) and java 8 (openjdk version "1.8.0_191"
OpenJDK Runtime Environment (build 1.8.0_191-8u191-b12-2ubuntu0.16.04.1-b12)
When I list the available ciphers using the below program I get the
TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 cipher as available.
Below is the program to list the ciphers available
https://confluence.atlassian.com/stashkb/files/679609085/679772359/1/1414093373406/Ciphers.java
But when I enable debug mode on ssl I get
Ignoring unsupported cipher suite: TLS_DHE_RSA_WITH_AES_256_GCM_SHA384.
and with below message
upcoming handshake states: server_hello[2]
*** ClientHello, TLSv1.1
RandomCookie:  GMT: 1535642319 bytes = { 168, 0, 213, 212, 68, 19, 189, 131, 12, 147, 76, 108, 65, 77, 56, 170, 35, 147, 119, 196, 102, 161, 241, 133, 49, 97, 153, 200 }
Session ID:  {}
Cipher Suites: [TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, TLS_RSA_WITH_AES_256_CBC_SHA, TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, TLS_DHE_RSA_WITH_AES_256_CBC_SHA, TLS_DHE_DSS_WITH_AES_256_CBC_SHA, TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, TLS_RSA_WITH_AES_128_CBC_SHA, TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_DSS_WITH_AES_128_CBC_SHA, TLS_EMPTY_RENEGOTIATION_INFO_SCSV]
Compression Methods:  { 0 }
Here the client starts communicating through TLSv1.1 when the server is using TLSv1.2
I also noticed that the ExportControlled.java (package com.mysql.cj.protocol;) creates SSLContext as (line 563)
try{
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(kms, tms.toArray(new TrustManager[tms.size()]), null);
        return sslContext;

    }

Please help me understand why the available cipher is ignored and what should I do to connect to the server

A: It is very simple, I just had to add the enabledTLSProtocols parameter to the jdbc url
Eg:-
jdbc:mysql://<hostname>:3115/<schema>?enabledTLSProtocols=TLSv1.2

A: I got this working, I have to set and enable TLS protocol version in connection property with mysql-connector-java-8.0.26.jar while in SSL mode. props.setProperty("enabledTLSProtocols", "TLSv1.2")
Properties props = new Properties();
props.setProperty("user", USER_SSL);
props.setProperty("password", PASS_SSL);
props.setProperty("useSSL", "true");
props.setProperty("requireSSL", "true");
props.setProperty("verifyServerCertificate", "true");
props.setProperty("sslMode", "VERIFY_CA");
props.setProperty("javax.net.debug", "all");
props.setProperty("enabledTLSProtocols", "TLSv1.2");
props.setProperty("zeroDateTimeBehavior", "convertToNull");

// Setting the truststore
props.setProperty("trustCertificateKeyStoreUrl", TRUST_STORE_URL);
props.setProperty("trustCertificateKeyStorePassword", TRUST_STORE_PASSWORD);

// Setting the keystore
props.setProperty("clientCertificateKeyStoreUrl", KEYSTORE_URL);
props.setProperty("clientCertificateKeyStorePassword", KEYSTORE_PASSWORD);
try {
conn = DriverManager.getConnection(DB_URL, props);
} catch (Exception ex)
{
Logger.debug(ex);
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to update docker image in elastic--beanstalk instance I'm using elastic-beanstalk to deploy multiple docker containers. I have travisCI configured to watch for changes to the master branch of my code repository, rebuild the docker images, push the new images to Docker hub, and then redeploy with elastic-beanstalk. The issue is that the elastic-beanstalk instance continues to show an older version of the image after the redeployment.
My .travis.yml file:
sudo: required
services:
  - docker

cache: false

before_install:
  - docker build -t [image-tag-1] -f ./client/dev.Dockerfile ./client

script:
  - node ./testTest.js

after_success:
  - docker build -t [image-tag-1]-client ./client
  - docker build -t [image-tag-2]-nginx ./nginx
  - docker build -t [image-tag-3] ./server
  # Log into the docker CLI
  - echo "$DOCKER_PASSWORD" | docker login -u "$DOCKER_ID" --password-stdin
  # Take those images and push them to docker hub
  - docker push [image-tag-1]
  - docker push [image-tag-2]
  - docker push [image-tag-3]

deploy:
  provider: elasticbeanstalk
  region: us-west-2
  app: xxxx-v7
  env: xxxxx-env
  bucket_name: elasticbeanstalk-us-west-2-xxxx
  bucket_path: docker-xxxx
  on:
    branch: master
  access_key_id:
    secure: $AWS_ACCESS_KEY
  secret_access_key:
    secure: $AWS_SECRET_KEY

After pushing changes to the master branch, travis successfully rebuilds and pushes the images, and elastic-beanstalk successfully redeploys. But the content of the elastic-beanstalk site shows that the old docker image is still being used. How can I get elastic-beanstalk to actually pull the new images during the redeployment?

A: Try specifying the label variable in the deploy settings. The label is a unique identifier for a deployment version. If you continue using the same label, the same version will be deployed to the beanstalk even if you build and push the new version.
Further reading:

*

*Travis CI : AWS Elastic Beanstalk Deployment


text:
Q: Getting Codec Error when sending Email with Attachment and Inline Images Using Mailgun Update: I have identified that this code works with python2.7, but doesn't work for python 3.4. Any suggestions?
I an trying to send multiple Images using Mailgun's API. Since the number of emails I send varies from one email to another, I have to make a dynamic list that than can be passed in the files parameters.
Here is my code:
  list_of_files = []
  count = 0
  for attachment in attachments:
    count += 1
    #tup = ("attachment" %(count), open(attachment))
    tup = ("attachment", open(attachment))

    list_of_files.append(tup)

  for inline in inlines:
    count += 1
    #tup = ("attachment" %(count), open(inline))
    tup = ("inline", open(attachment))

    list_of_files.append(tup)
  list_of_files = MultiDict(list_of_files)
  #sys.exit()
  print(list_of_files)

  r =  requests.post(
                      keys.mailgun_login,
                      auth=("api", keys.mailgun_API_key),
                      files = list_of_files,
                      #files = [('attachment', open('/Users/krishnaregmi/workdir/project12/media/BFSTPFQPBPSVUQY/pic_2.jpg'))],
                      data = {
                              "from": from_email,
                              "to": to_email,
                              "subject": subject,
                              "text" : body_plain,
                              "html" : body_html,
                              }
                      )
  return r

However, I keep on getting errors that I cannot figure out the root cause of. Here is the stack Trace:
Any Ideas on how to get the solve this problem?
MultiDict([('attachment', <_io.TextIOWrapper name='/Users/krishnaregmi/workdir/project12/media/BFSTPFQPBPSVUQY/pic_2.jpg' mode='r' encoding='UTF-8'>), ('attachment', <_io.TextIOWrapper name='/Users/krishnaregmi/workdir/project12/media/BFSTPFQPBPSVUQY/pic_2.jpg' mode='r' encoding='UTF-8'>)])
Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/Users/krishnaregmi/workdir/venv/lib/python3.4/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
    utility.execute()
  File "/Users/krishnaregmi/workdir/venv/lib/python3.4/site-packages/django/core/management/__init__.py", line 330, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/Users/krishnaregmi/workdir/venv/lib/python3.4/site-packages/django/core/management/__init__.py", line 190, in fetch_command
    klass = load_command_class(app_name, subcommand)
  File "/Users/krishnaregmi/workdir/venv/lib/python3.4/site-packages/django/core/management/__init__.py", line 40, in load_command_class
    module = import_module('%s.management.commands.%s' % (app_name, name))
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/importlib/__init__.py", line 109, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 2254, in _gcd_import
  File "<frozen importlib._bootstrap>", line 2237, in _find_and_load
  File "<frozen importlib._bootstrap>", line 2226, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 1200, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 1129, in _exec
  File "<frozen importlib._bootstrap>", line 1471, in exec_module
  File "<frozen importlib._bootstrap>", line 321, in _call_with_frames_removed
  File "/Users/krishnaregmi/workdir/project12/continuous_loop/management/commands/run_emailsending_loop.py", line 22, in <module>
    status = mh.send_email_from_email_object(email)
  File "/Users/krishnaregmi/workdir/project12/executive_email/mailgun_helpers.py", line 34, in send_email_from_email_object
    body_html,
  File "/Users/krishnaregmi/workdir/project12/executive_email/mailgun_helpers.py", line 90, in send_email_files
    "html" : body_html,
  File "/Users/krishnaregmi/workdir/venv/lib/python3.4/site-packages/requests/api.py", line 109, in post
    return request('post', url, data=data, json=json, **kwargs)
  File "/Users/krishnaregmi/workdir/venv/lib/python3.4/site-packages/requests/api.py", line 50, in request
    response = session.request(method=method, url=url, **kwargs)
  File "/Users/krishnaregmi/workdir/venv/lib/python3.4/site-packages/requests/sessions.py", line 451, in request
    prep = self.prepare_request(req)
  File "/Users/krishnaregmi/workdir/venv/lib/python3.4/site-packages/requests/sessions.py", line 382, in prepare_request
    hooks=merge_hooks(request.hooks, self.hooks),
  File "/Users/krishnaregmi/workdir/venv/lib/python3.4/site-packages/requests/models.py", line 307, in prepare
    self.prepare_body(data, files, json)
  File "/Users/krishnaregmi/workdir/venv/lib/python3.4/site-packages/requests/models.py", line 453, in prepare_body
    (body, content_type) = self._encode_files(files, data)
  File "/Users/krishnaregmi/workdir/venv/lib/python3.4/site-packages/requests/models.py", line 150, in _encode_files
    fdata = fp.read()
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/codecs.py", line 319, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

A: Update:
I changed the code to open files to this:
for attachment in attachments:
    count += 1
    #tup = ("attachment" %(count), open(attachment))
    tup = ("attachment", open(attachment, 'rb'))

    list_of_files.append(tup)

  for inline in inlines:
    count += 1
    #tup = ("attachment" %(count), open(inline))
    tup = ("inline", open(attachment, 'rb'))

That fixed the problem.


text:
Q: Android view flipper with centered top title I want to make an app with flip animations like Android Market app.It will have title at top center and it will flip with the page.Are there any source code or library for this?

A: You will have to desing your view accordingly. I would recommend using fragments.
http://developer.android.com/guide/topics/fundamentals/fragments.html


text:
Q: Convert dataframe columns into dict and save it as json file, with columns name as dict key and row values as dict values I have a pandas dataframe as below :
device_id   user_id level
d_id1   u_id1   1
d_id1   u_id2   -1
d_id1   u_id3   1
d_id2   u_id100 -1
d_id3   u_id100 1
d_id3   u_id4   1

I want to convert it into a list of dictionaries depend on columns and rows that looks like:
[
{
"device_id":d_id1
"result_key":[
                {"user_id":u_id1,"level":1},
                {"user_id":u_id2,"level":-1},
                {"user_id":u_id3,"level":1}
             ]
},
{
"device_id":d_id2
"result_key":[{"user_id":u_id100,"level":-1}]
},
{
"device_id":d_id3
"result_key":[{"user_id":u_id100,"level":1},
              {"user_id":u_id4,"level":1}
              ]
}
]

What is the effecient way to do that and save it into json file?

A: Use GroupBy.apply with DataFrame.to_dict for result_key column first, then for dictionary use to_dict with both columns:
d = (df.groupby('device_id')[['user_id','level']].apply(lambda x: x.to_dict('records'))
       .reset_index(name='result_key')
       .to_dict('records'))
print (d)
[{'device_id': 'd_id1', 'result_key': [{'user_id': 'u_id1', 'level': 1},
                                       {'user_id': 'u_id2', 'level': -1},
                                       {'user_id': 'u_id3', 'level': 1}]},
 {'device_id': 'd_id2', 'result_key': [{'user_id': 'u_id100', 'level': -1}]},
 {'device_id': 'd_id3', 'result_key': [{'user_id': 'u_id100', 'level': 1},
                                       {'user_id': 'u_id4', 'level': 1}]}]

Last convert dictionary to json file:
import json
with open('out.json', 'w') as f:
    json.dump(d, f)


text:
Q: Different UIViewController modal transition to another VC with different animation here is my question, let s say i have UIViewController A B C D...
currently I am using the default transiation animiation for all VCs modal transite , shows as ->

what i want is... let user pick what kind of transiation animation they like to use..for all the VC modal transition animations...
i guess some code need to be added in some where here? ->
- (IBAction)cardAction:(id)sender {
UIImage *img = [(UIButton *)sender currentBackgroundImage];
[self performSegueWithIdentifier:@"cardSegue" sender:img];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if ([segue.identifier isEqualToString:@"cardSegue"]) {
    UIImage * img = (UIImage *)sender;

    ResultViewController *viewcontroller = [segue destinationViewController];
    viewcontroller.img = img;
    }
}

please help..

A: A segue lets you define the transition in the Storyboard but you want to let the user define the transition.  UIStoryboardSegue doesn't let you do this, so you're going to need to perform the transition yourself.
There's a good answer on performing transitions using different styles here:
How to change the Push and Pop animations in a navigation based app
Instead of calling performSegueWithIdentifier, you'd use the code from that answer to perform the transition.

A: You can just create your own segue subclass and then changing the
- (void) perform;

function.
If you need an example for the segue subclassing go to this tutorial:
>>> Link to tutorial <<<
Regards,
Nils


text:
Q: Why the right branch of an hyperbole is not an algebraic curve?
Prove that the subset of $\mathbb{R}^2$ defines by $X^2-Y^2=1$, $X>0$ is not an algebraic curve.

It's clear that the hyperbole is an algebraic curve because I can define the set
$$V(F)=\{(X,Y)\in\mathbb{R}^2 : F(X, Y)= X^2-Y^2-1=0\}.$$
However, I don't know why the right branch is not an algebraic curve. Any help would be aprecciate.

A: Suppose your half-hyperbola (that I will call $C$) is a curve defined over some finitely generated field $K$ and let $\sigma$ be a field automorphism of $\Bbb R$ fixing $K$.
Then $C$ is fixed by $\sigma$. Since $\pi_1(C) = [1 ; \infty)$, $\sigma$ must induce a permutation of $[1 ; \infty)$.
In particular, $\forall x \in \Bbb R, x\ge 1 \iff \sigma(x)\ge 1$. Since $\sigma$ is also a field morphism, it fixes $\Bbb Q$ and so for any rational $r$, by replacing $x$ with $x+1-r$ and doing a few manipulations, you get that $\forall x \in \Bbb R, x \ge r \iff \sigma(x) \ge r$.
But since every real number is entirely determined by which rational numbers are lesser (or greater) than it, you deduce from there that $\sigma$ has to be the identity on $\Bbb R$.
So, any field automorphism fixing $K$ has to fix $\Bbb R$, and therefore $K=\Bbb R$
.
This contradicts the fact that $K$ is finitely generated (you can't shove an uncountable number of coefficients in a polynomial equation !)
And so $C$ cannot be an algebraic curve.

You can turn this around and pick a point on $(x,y) \in C$ transcendant over $K$, then there is a $K$-automorphism sending $x$ to $-x$, and so $(-x,y)$ and $(-x,-y)$ also satisfy the equation and have to be in $C$ but they are on the left branch.

A: I will use the fact that the curve has a rational parametrization. Every point on the curve except $(1,0)$ can be written as
$$(x,y) = \left( \frac{1+t^2 }{1-t^2}, \frac{2 t}{1-t^2}\right) $$ for a unique $t \in \mathbb{R} \backslash\{\pm 1\}$. The part with $x >0$ corresponds to $t \in (-1, 1)$.
Say we have a polynomial $P$ so that $P( \frac{1+t^2 }{1-t^2}, \frac{2 t}{1-t^2}) = 0$ for all $t \in (-1,1)$. Then $P( \frac{1+t^2 }{1-t^2}, \frac{2 t}{1-t^2}) = 0$ for all $t \in \mathbb{R} \backslash \{\pm 1\}$. That is, if $P$ is $0$ on the one branch of the hyperbola, it is $0$ on the hyperbola. Therefore, the positive branch is not an algebraic curve.
Note: We use the existence of a rational parametrization. In fact, even for other curves this is true: a piece of a curve is not algebraic. For instance, take $y^2 = x(x+1)(x+2)$. The positive branch is not an algebraic curve again. One needs to use an analytic parametrization in this case.


text:
Q: Can you tell me what tense is: "if + simple past, would + infinitive"?
She hugs and smiles thinking if Arjun wasn't so greedy he would be alive today.

It is easy to understand , if he had not been greedy he would have been alive today. But, what does the above mean?

A: If Arjun wasn't so greedy he would be alive today is an example of a syntactic construction that is often called the second conditional or conditional 2. The verb in the if-clause (the protasis) is in the simple past tense, while the main clause (the apodosis) contains the modal would plus a bare infinitive (in this case be).
One use of the second conditional is for present counterfactuals (statements about the present that are contrary to the truth):

If you didn't smoke so much, you wouldn't have such a nasty cough (but
  you do smoke, so you do have a nasty cough).
If Arjun wasn't so greedy, he would be slim (but he is greedy, so he
  is not slim).

On this basis, the statement If Arjun wasn't so greedy, he would be alive today implies: but he is greedy so he is not alive today. This is clearly nonsensical, since you cannot be greedy without being alive.
Assuming that Arrjun is indeed dead and greed resulted in his death, the sentence needs to be constructed as follows:

If he had not been greedy, he would be alive today.

This is a so-called mixed conditional because it mixes the past perfect of the verb in the if-clause (a prototypical conditional 3 protasis) with would plus a bare infinitive (a prototypical conditional 2 apodosis).
As an aside I am interested to know the source of the sentence in question. As well as the semantic issue discussed above, it uses hug intransitively, whereas hug is normally followed by an object.

A: From EduFind.com:

The given sentence is an example of  TYPE 2 CONDITIONAL sentence.
The type 2 conditional is used to refer to a time that is now or any
  time, and a situation that is unreal. These sentences are not based on
  fact. The type 2 conditional is used to refer to a hypothetical
  condition and its probable result. In type 2 conditional sentences,
  the if clause uses the simple past, and the main clause uses the
  present conditional.
More Examples-
If you went to bed earlier    you would not be so tired.
If it rained  you would get wet.
If I spoke Italian    I would be working in Italy.
If Arjun wasn't so greedy he would be alive today.
The second sentence which you are referring to is a Type 3
  Conditional
The type 3 conditional is used to refer to a time that is in the past,
  and a situation that is contrary to reality. The facts they are based
  on are the opposite of what is expressed. The type 3 conditional is
  used to refer to an unreal past condition and its probable past
  result. In type 3 conditional sentences, the if clause uses the past
  perfect, and the main clause uses the perfect conditional.

Refer to this site for more details on the conditional sentences.


text:
Q: Wordpress Custom Post Type categroies I have a custom post type called STORIES.
When a user adds a new STORY, I need them to be able to assign a category (or multiple categories) to the post so I can sort them later by category.
To do this, I only want specific categories I assign to the STORY posts to show - NOT all of the wordpress categories attached to every post type.
For example the default Wordpress category is 'Uncategorized'. How do I remove this category (and any othersI don't want) to ONLY show the ones I select via the custom post type editor?
Is there any way I can make this happen?
I am using custom Post Types UI with Advanced Custom Fields.

A: You can do that with Post Types UI,  You will need to create a new taxonomy.
Here is the screenshot explaining that
https://s.w.org/plugins/custom-post-type-ui/screenshot-4.png?r=1180724
Just fill the text boxes with appropriate names, and check STORY under
"Attach to Post Type" option.
After that you will have custom taxonomy like "Story Category" to use for stories only.


text:
Q: ggplot piechart label freq instead of percent? Hi supposed I have the following pie info.
df=structure(list(Var1 = c("a", "b"), Freq = c(306L, 1064L), per = c(0.223357664233577,
0.776642335766423)), row.names = c(NA, -2L), class = "data.frame")

and I plot this pie chart with direction -1
ggplot(data = df,
       aes(x = "", y = per, fill = Var1)) +
  geom_col() +
  geom_text(aes(label = scales::percent(per, accuracy = 1)),
            position = position_stack(vjust = 0.5),
            color = "grey20", size = pietext ) +
  coord_polar(theta = "y", direction =-1 ) +
  theme_void ()

However what I would like is to label with with the frequency rather than the percentage.
  Var1 Freq       per
1    a  306 0.2233577
2    b 1064 0.7766423

Is this possible with this method? I tried replacing per with Freq but that just gave some really strange text.
thank you.

A: aes(label = Freq) is the way to go:
ggplot(data = df,
       aes(x = "", y = per, fill = Var1)) +
  geom_col() +
  geom_text(aes(label = Freq),
            position = position_stack(vjust = 0.5),
            color = "grey20", size=12) +
  coord_polar(theta = "y", direction =-1) +
  theme_void ()

A: Just change  geom_text(aes(label =Freq)
ggplot(data = df, aes(x = "", y = per, fill = Var1)) +
   geom_col() +
   geom_text(aes(label =Freq),
            position = position_stack(vjust = 0.5),
            color = "black", size = 10 ) +
   labs( x="", y="", fill="")+
  scale_fill_manual(values=c("#4E79A7", "#fc7d0b"))+
  coord_polar(theta = "y", direction =-1 ) +
  theme_no_axes()

Plot:

or something that is better than a pie chart
Sample code:
library(waffle)
library(ggthemes)

    vals <- c(306,1064)
    val_names <- sprintf("%s (%s)", c("a","b"), label=vals)
    names(vals) <- val_names

    waffle::waffle(vals) +
    ggthemes::scale_fill_tableau(name=NULL)

Plot:

Sample code:
df=structure(list(Var1 = c("a", "b"), Freq = c(306L, 1064L), per = c(0.223357664233577, 0.776642335766423)), row.names = c(NA, -2L), class = "data.frame")


text:
Q: using gsub function to change multiple values in the same column (variable) of a dataset I have this column of data below:
data$fruits = c("apple","Orange","Banana")

I want to use the "gsub" function to change "apple" and "Banana" to "grape" and "mango" respectively such that new data is:
data$fruits = c("grape","Orange","mango")

I know that if I want to change only "apple", I can use:
data$fruits = gsub("apple", "grape", data$fruits).

My trouble is doing same for two or more values using "gsub"
Any help will be useful.

A: Usually we probably would use an assignment matrix a.
data <- tmp

a <- cbind(c("apple","Banana"), c("grape","mango"))
matches <- na.omit(match(a[,1], data$fruits))
data[matches, "fruits"] <- a[, 2]
data
#   X1 X2 X3 X4 fruits
# 1  1  4  7 10  grape
# 2  2  5  8 11 Orange
# 3  3  6  9 12  mango

If you really rely on gsub you could do
data <- tmp

invisible(apply(a, 1, function(x) data$fruits <<- gsub(x[1], x[2], data$fruits)))
data
#   X1 X2 X3 X4 fruits
# 1  1  4  7 10  grape
# 2  2  5  8 11 Orange
# 3  3  6  9 12  mango

but that's a bit awkward.

Data:
tmp <- data.frame(matrix(1:12, 3, 4))
tmp$fruits = c("apple","Orange","Banana")


text:
Q: Tons Of rpc.idmapd errors in syslog I am growing weary of some error messages in my syslog - its showing:
Jul 3 15:16:38 web rpc.idmapd[14535]: nss_getpwnam: name 'nobody' does not map into domain 'mydomain.com'
I have check, my hostname is correct as mydomain.com and I even added a valid entry in /etc/hostname . I have edited my /etc/idmapd.conf to reflect this domain name, this error message log every 10minutes and its becoming frustrating, I do not know why or whats causing it, the nfs server is working ok, with correct entries and now message in the log.
I am using centos6
-- Ofcoure, i have substituted mydomain.com with my real domain

A: I had the same issue on 2 NFSv4 clients and it was related to some files and directories having unknown uid and gid.  Those files had been copied from an old server with a completely different list of users.  On the nfs server they will show up with a numeric uid/gid.  But on the clients, idmapd maps those to the user nobody and group nogroup but issue the warning you mention in the log files.
I think you should check your nfs exported directories if they contain such files.  The easiest way I've found was to do it with find:
find /path/to/your_nfs_dir/ -user nobody -or -group nogroup -ls

and you can even change them right away if you want to make those files to belong to some existing user/group:
find /path/to/your_nfs_dir/ -user nobody -exec chown myuser {} \;
find /path/to/your_nfs_dir/ -group nogroup -exec chgrp mygroup {} \;

You need to do this on one of the client, as on the nfs server the files will not be identified as belonging to nobody/nogroup.

A: I am also having this problem, I was able to determine that the idmapd map problem is partly a kernel problem on the client machine.
First, on the nfs server, logs show that idmapd is being fed numerical ids for some users instead
of names, by the nfs client.  This behavior is related to the kernel on the client, with the kernel, 2.6.32-431.el6.centos.plus.x86_64.
It fails, but with 2.6.32-358.14.1.el6.centos.plus.x86_64, uid mapping works, however gid mapping still fails.
The only way I've been able to get both uid and gid mapping to work is to revert to NFSv3.


text:
Q: How to place % and value in a single input field I have a input field text box that has % aligned towards left and value aligned towards right and the input box is disabled. How can I achieve this using HTML and css. It should look something like the attached image.
enter image description here
I have tried the below code.

      <input disabled class="averagePrice" [value]="3.99" />

A: I tried something close to what you mentioned in the image description.
Well, this can be done using the 'span' tag. A similar thing could've been achieved using the 'div' tag but when it comes to grouping elements for styling purposes, 'span' tag should be used (inline tag being more preferable than the block-level tag, in some specific cases like these).

.percentinput {
    border: 1px inset #ccc;
  }
.percentinput input {
    text-align: right;
    border: 0;
  }
%<input disabled type="text" placeholder="33.6" >

A: Here it is
HTML

   %
  <input disabled class="input-field" type="text" value="33.6">

CSS
.input-icons i {
  position: absolute;
}
.input-icons {
  width: 100%;
  margin-bottom: 10px;
  position: relative;
}
.icon {
  padding: 10px;
  color: green;
  min-width: 20px;
  text-align: center;
}

.input-field {
  padding: 10px;
  text-align: right;
}


text:
Q: using django permissions.IsAuthenticatedOrReadOnly with token authentication I have this Django API view that I want to allow authorized and unauthorized users access it, I have set Django token-authentication as the default authentication class, however, whenever I try to access the view as unauthenticated user,I get error Unauthorized: which is weird coz am making a get request in the view
my code is here
@api_view(['GET'])
@permission_classes([permissions.IsAuthenticatedOrReadOnly])
def all_Search(request):
    print(request.headers)
    src = request.GET.get('q')

my settings for rest framework is
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ]
}

is there a way to work around this? will appreciate any help, thanks

A: I've tried to reproduce your error but I failed.
This is my configuration:
settings.py
INSTALLED_APPS = [
    ...
    'rest_framework',
    'rest_framework.authtoken'

]

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ]
}

urls.py
urlpatterns = [
    path('search/', api.all_search, name="search")

]

api.py
from rest_framework import permissions
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response

@api_view(['GET'])
@permission_classes([permissions.IsAuthenticatedOrReadOnly])
def all_Search(request):
    print(request.headers)
    src = request.GET.get('q')
    return Response()

test.py
from rest_framework import status
from rest_framework.test import APILiveServerTestCase
from rest_framework.reverse import reverse

class TestTokenAuthorization(APILiveServerTestCase):
    def test_can_search_without_token(self):
        url = reverse('search', kwargs={})
        response = self.client.get(url, {}, format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)

and this is the result of the test:
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
{'Cookie': '', 'Content-Type': 'application/octet-stream'}
Destroying test database for alias 'default'...

I'm using djangorestframework==3.10.3 and python3.7
As you can see, I didn't authenticate the request (no token is passed) and the headers were printed as expected from the permissions.
Maybe your issue is caused by something else in your code. Try to include more details in your question.
By the way, your all_Search function is missing the return Response()

A: Okey I just decided to try something and it seams to be working, at least for now. I somehow believed that DEFAULT_AUTHENTICATION_CLASSES was the issue in this case and in deed it was, so I had to just remove the
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ]
}

#opt to use
#authentication_classes = [TokenAuthentication, SessionAuthentication]
#in my views that requires authentications

in my settings, this was not all though, but now I could access the view either authorized or not: (having auth token or not). but this was not getting authenticated user by default
so I did this
make a view to get a user based on a given token
from django.contrib.auth.models import AnonymousUser
from rest_framework.authtoken.models import Token

def get_user(token):
    try:
        token = Token.objects.select_related('user').get(key=token)
        return token.user
    except:
        return AnonymousUser

and get user in my view if token exists in the headers
@api_view(['GET'])
@permission_classes([permissions.IsAuthenticatedOrReadOnly])
def all_Search(request):
    auth = request.headers.get('Authorization').split(' ')[1]
    key = request.headers.get('Authorization').split(' ')[0]
    if key == 'Token' and auth != 'null': #used null coz my frontend sends null if key is not available
        user = get_user(auth)
        print(user)


text:
Q: Can't ping first IP with dual NICs on different subnets with multiple gateways I have two NICs assigned to a server.
eth0 - 10.199.10.0/24 w/ a GW of 10.199.10.1
eth1 - 10.199.20.0/24 w/ a GW of 10.199.20.1

From my desktop, I can ping the IP assigned to each NIC just fine (10.199.10.100 and 10.199.20.100). So I set up Apache to listen on ALL ips on said server. I tested this just fine from my desktop as well. Now, I went to create a new VM on the 10.199.20.0 subnet and I can access the RH test page by hitting http://10.199.20.100 BUT I can't access it via 10.199.10.100.
This is troublesome since I have a bunch of services on this server that can only listen on one particular IP (the 10.199.10.100). My network guy tells me the routes look fine and that it could be the routing table on the server itself.
#ip route
10.199.10.0/24 dev eth0  proto kernel  scope link src 10.199.10.100
10.199.20.0/24 dev eth1  proto kernel  scope link src 10.199.20.100
169.254.0.0/16 dev eth0  scope link  metric 1002
169.254.0.0/16 dev eth1  scope link  metric 1003
default via 10.199.10.1 dev eth0

# ip rule
0:      from all lookup local
32764:  from all to 10.199.20.100 lookup build
32765:  from 10.199.20.100 lookup build
32766:  from all lookup main
32767:  from all lookup default

Netowrk Layout
These servers are Xen guests. We have four Xen servers with multiple NICs. The admin server with the two NICs have two virtual NICs assigned to them. One from 10.199.10.x and one from the 10.199.20.x subnet (two different NICs). The test server only has the 10.199.20.x network assigned to it. I can ping the 10.199.30.x network just fine.


text:
Q: How to properly install LLVMLITE in windows 10? I'm trying to install the llvmlite in my windows 10, so i'm following the step-by-step from the documentation:
You must have Visual Studio 2013 or later (the free "Express" edition is ok) in order to compile LLVM and llvmlite.
In addition, you must have cmake installed, and LLVM should have been built using cmake, in Release mode. Be
careful to use the right bitness (32- or 64-bit) for your Python installation.

So, i already have everything, and when i try to install with the command python setup.py build, the following error occurs:
Trying generator 'Visual Studio 12 2013'
-- The C compiler identification is unknown
-- The CXX compiler identification is unknown
CMake Error at CMakeLists.txt:3 (project):
  No CMAKE_C_COMPILER could be found.

CMake Error at CMakeLists.txt:3 (project):
  No CMAKE_CXX_COMPILER could be found.

-- Configuring incomplete, errors occurred!
See also "C:/Users/G1745 IRON/AppData/Local/Temp/tmpvzyvoz/CMakeFiles/CMakeOutput.log".
See also "C:/Users/G1745 IRON/AppData/Local/Temp/tmpvzyvoz/CMakeFiles/CMakeError.log".
Traceback (most recent call last):
  File "C:\Python27\Lib\site-packages\llvmlite\ffi\build.py", line 152, in <module>
    main()
  File "C:\Python27\Lib\site-packages\llvmlite\ffi\build.py", line 140, in main
    main_win32()
  File "C:\Python27\Lib\site-packages\llvmlite\ffi\build.py", line 74, in main_win32
    generator = find_win32_generator()
  File "C:\Python27\Lib\site-packages\llvmlite\ffi\build.py", line 70, in find_win32_generator
    raise RuntimeError("No compatible cmake generator installed on this machine")
RuntimeError: No compatible cmake generator installed on this machine
error: command 'C:\\Python27\\python.exe' failed with exit status 1

Searching a lot, i found that i should use the following command cmake -G "Visual Studio 14 2015", but that's returning:
CMake Error: The source directory "C:/Python27/Lib/site-packages/llvmlite" does not appear to contain CMakeLists.txt.
Specify --help for usage, or press the help button on the CMake GUI.

I help would be very much appreciated.

A: i use windows 10, python 2 & python 3 and regularly use the link provided by @roganjosh to download & install pre-compiled binaries. i have just repeated this for a clean install, and yes, it works perfectly for llvmlite. for numba too.


text:
Q: How to send message to specific user I want to send messega to specific user.
I looked for facebook developer pages, but I couldn't.
Please tell me how to send(API)?
Thanks a lot.

A: There is no public send API, you should use either the Send Button social plugin or the Send Dialog to do what it is that you want.


text:
Q: What can I use for mock fetch-requests while e2e testing in protractor similar to addMockModule without Angular I am writing e2e test with protractor for a typescript module. I want to use protractor for the additional features in comparison to selenium webdriver. I am using typescript standalone so I am building a non-angular application.
I searched a lot for mocking services or fetchmock etc. But I think I am searching at the wrong place. Maybe I just didn't understood what do I really need for my problem.
At the moment I have an application where I want to test the frontend. My problem is, that the application only works with a server which is setting up many data and make it available for rest. Without this server my javascript file wont work and I wont start the server for my tests, it must be server independent.
For example: my server provide the data on a specific address 192.168.1.230 and I can fetch the data with fetch api over: 192.168.1.230/users/1.
In unit tests I have mocked my fetches, but in e2e tests I need to mock the address (maybe with selenium webdriver) and want to get a dummy response if my api is fetching this data.
How can I realise that? I use protractor with npm (nodejs) and could need a npm plugin for this.
I saw another post here with the addMockModule, but this is only for angular modules and I don't use angular.


text:
Q: htaccess file not recognizing a space in: AddType application/x-httpd-php html I am creating a CMS that allows admin to manage the .htaccess from administration. The script handles numerous aspects of the .htaccess file with everything working correctly except: AddType application/x-httpd-php html
The script writes the code correctly except it is not recognizing the space between AddType application/x-httpd-php and html
If after the script writes the code I delete the space and add it directly in with my space bar the .htaccess file works perfectly... at a total loss.
This is the code which writes that portion of the file:
# process as php
    if($process_as_php == 1){$htaccess_code .= "# Allows files to process php \r";
        $htaccess_code .= "AddType application/x-httpd-php html";
    $htaccess_code .= " \r";
    }

This is how the file is saved:
$file_handle = fopen($level.'.htaccess', 'w');
    fwrite($file_handle, $htaccess_code);
    fclose($file_handle);

Any assistance would be appreciated
Pete

A: This question was answered here:
Script to write htaccess file adding phantom unknown character causing a 500 error
While the circumstances were different, it cause was the same and the soulution likewise was the same.


text:
Q: div container shrinks after position: absolute The
 container shrinks to, well, "zero" after positioning my logo.
Could you please check what's the problem? I'd like it to be centered in the #logo
. I thought making parent
 relative and children absolute should keep logo in the
.
Html

CSS
body{
    font-family: Arial, Helvetica, sans-serif;
    font-size: 15px;
    line-height: 1.5;
    padding:0;
    margin:0;
    background-color: #DCB894;
}

.wrapper{
    margin-right: auto;
    margin-left: auto;

    max-width: 960px;

    padding-right: 10px;
    padding-left: 10px;
    border-style: solid;
    border-color: blue;
    border-width: 2px;
}

header {
    margin-top: 10px;
    background-color: #BCD34C;
}

#logo{
    border-style: solid;
    border-color: magenta;
    border-width: 2px;
    position: relative;
    height: auto;
}

#logo img {
    width: 150px;
    height: auto;
    position: absolute;
    margin: auto;
    border-style: solid;
    border-color: red;
    border-width: 2px;
}

A: Yes it should to behave something like that because position: absolute and position: fixed dose not take place from it's parent or container. When you use these two css properties they go outside regular document follow. That's why parent treat inside have no content and height not auto increase until set you height by explicitly by css properties like height: 100px (for example) or min-height: 100px (for example).
According your current structure either you set the minimum height based logo.
header {
    min-height: 100px; // 100px here logo size assumed
}

Or keep the position of logo image relative:
#logo img {
   position: relative;
}

A: I would avoid position absolute, if you wrap your image within a div you can centre your image.

    body{
    font-family: Arial, Helvetica, sans-serif;
    font-size: 15px;
    line-height: 1.5;
    padding:0;
    margin:0;
    background-color: #DCB894;
}

.wrapper{
    margin-right: auto;
    margin-left: auto;

    max-width: 960px;

    padding-right: 10px;
    padding-left: 10px;
    border-style: solid;
    border-color: blue;
    border-width: 2px;
}

header {
    margin-top: 10px;
    background-color: #BCD34C;
}

#logo{
    border-style: solid;
    border-color: magenta;
    border-width: 2px;
    position: relative;
    height: auto;
    max-width: 220px;
    overflow: hidden;
}

#logo figure {
  width:52%;
  margin: 0 auto;
}

#logo img {
    width: 100%;
    position:relative;
    border-style: solid;
    border-color: red;
    border-width: 2px;
    overflow: hidden
}

The img will take up 100% of the total space, given to it by the figure.
You can change the width of the figure and then the image will respond, keeping it centered.


text:
Q: How to remove service application from Add/Remove Programs if it is no longer listed as a service? I had a windows installer install a service I created. I tested on my dev machine rather than a test machine. The application files no longer exist and the service does not show up in the list of Windows Services under Admin Tools. I am trying to remove the entry from the Add/Remove programs. I set the installer up with a custom action of uninstalling the service when the uninstaller is run.
Even with manually copying the files to the expected location and manually adding the service in to the list of services, the uninstaller fails. I can't manage to remove it from the list of add remove programs. How can I remove it from the list?

A: All the entries shown in the Add/Remove Programs panel are found in the Registry key HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Uninstall -- you'll find your in a subkey named with a GUID (e.g. "{123409-adsf-1234...}") if it was installed from an MSI (in which case you probably want to re-run the MSI to remove cleanly you really should use msiexec /x {GUID} to uninstall, or double-click the original MSI package and choose "Remove") or it could be any name if it was installed with another setup tool.

A: Perhaps this will help:
http://setupanddeployment.com/cleanup/installer-cleanup/
http://setupanddeployment.com/cleanup/installer-cleanup-update/


text:
Q: Getting string Id from a Adapterview So I have the following code
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        String selectedItem = parent.getItemAtPosition(position).toString();
        switch (selectedItem) {
            case "Lowest Price":// handle...
                break;
            case "Price": // handle...
                break;
            default: break;
        }
        adapter.notifyDataSetChanged();
    }

but I have already have the strings in a string file which populate the adapter.
Is there a way to get the id from parent or view so that I can do something like this:
switch(id)
case R.resource.my_string

A: If you String array in your string.xml like this,
<array name="price_type">
    <item>Lowest Price</item>
    <item>Price</item>
</array>

you can directly get the value from array like this,
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    final String[] priceValues = getResources().getStringArray(R.array.price_type);

    String selectedItem = priceValues[position];

    // if you want to use more manipulation based on the item you can use the position of the value.

    adapter.notifyDataSetChanged();
}


text:
Q: Jmeter property rmi configuration In jmeter bin directory jmeter.property file, there are similar keys, I don't understand different each other.
client.rmi.localport
server.rmi.port
server.rmi.localport
server_port

A: Take a look at Remote hosts and RMI configuration

*

*client.rmi.localport - Parameter that controls the RMI ports used by RemoteSampleListenerImpl and RemoteThreadsListenerImpl (The Controller)

*server.rmi.port - To change the default port (1099) used to access the server.

*server.rmi.localport - To use a specific port for the JMeter server engine, define this property before starting the server.

*server_port - RMI port to be used by the server (must start rmiregistry with same port).

Where:

*

*client (or Controller) == JMeter Master

*server == JMeter Slave

More information:

*

*Remote Testing

*How to Perform Distributed Testing in JMeter

*Apache JMeter Distributed Testing Step-by-step


text:
Q: Can iOS app get UIPasteboardChangedNotification in background? I have seen an iphone app called CopyTranslate. When we copy something, e.g. in safari, it can give an translation of what we copied by a local notification.
So I am wondering if app can receive UIPasteboardChangedNotification even in background. Then I make a test that I build a app which can run in background for 10 minutes, and observe to UIPasteboardChangedNotification. The result is that app can not get notification in background.
Can anyone have ideas that how CopyTranslate implement its function like that? Does it check the UIPasetBoard per second? If thus, how does it know there is a new string copy instead of image copy or something else.
Thank you for any idea!
I have solved this problem by checking the changeCount of UIPasteboard per second in background.
Here are details:
I hold a property lastChangeCount in AppDelegate, and when my application comes into background, I start a infinite while loop which sleep for 1 second per iteration. And I will compare the UIPasteboard's changeCount with lastChangeCount per iteration, if they are not equal, then I know there is some new paste items in pasteboard. So I will get the string property of UIPasteboard, if it exists, I schedule a local notification to show it. If not, I means that the user may copy a image or something else, so I will do nothing.

A: A possible method is to "monitor" UIPasteboard when the app is in background for regular time intervals, say 5 secs, and then it's possible to know if there's a change in clipboard.
In order to make sure the copy content is a string, check [[UIPasteboard generalPasteboard] string]
Yet background task is limited to 600secs, (and playing mute music in background may get you rejected), so there are discussions over how to extend the time. Also, Pasterbot has declared a similar, method, see here.


text:
Q: Where have the missing letters gone? Only 4 letters are showing up. Like in the example, I send the string "abcdef", but it only shows the 4 letters "abcf". I don't know why the other letters don't show up. I'm using Atmega8 and Bray terminal. I'm already following from the datasheet [http://ww1.microchip.com/downloads/en/DeviceDoc/21822E.pdf][1]. But I've already found a dead end.
Implementation of functions
#include <avr/io.h>
#include <math.h>
#include <util/delay.h>

#define DD_SS       PINB2         //Chip select ON RC2
#define DD_MOSI     PINB3          // Master out - Slave in pin
#define DD_MISO     PINB4          // Master in - Slave out pin
#define DD_SCK      PINB5          // Clock from master
#define DDR_SPI     PORTB          // DDR_SPI

void serial_init(void)
{
    UBRRH = 0x00;
    UBRRL = 7;
    UCSRC = (1<<URSEL)|(1<<USBS)|(3<<UCSZ0)|(1 << UCSZ1);
    UCSRB = (1 << RXEN) | (1 << TXEN)| (1<<RXCIE);
}
unsigned char Usart_Receive(void)
{
    while ((UCSRA & (1 << RXC)) == 0) {};
    return UDR;
}

void Usart_Transmit(unsigned char c)
{

    PORTD= 0b00000100;  //RTS Enable
    while ((UCSRA & (1 << UDRE)) == 0) {};
    UDR = c;
    PORTD= 0b00000000;  //RTS Disable
}
void SPI_MasterInit(void)
{
    DDRB = 0b00101100;
    DDR_SPI = (1<<DD_MOSI)|(1<<DD_SCK);
    SPCR = 0b01010000;
    SPSR = 0b00000001;
}
unsigned char spi_transfer(volatile char data)
{
    SPDR = data;
    while(!(SPSR & (1<<SPIF)));
    {
    }
    return SPDR;
}
void SPI_MasterTransmit (uint8_t Data)
{
    uint16_t address;
    SPCR = (1<<SPE) | (1<<MSTR) | (0<<CPHA);
    DDR_SPI &= ~(1<<DD_SS);                // Select EEPROM
    spi_transfer(WREN);   // Send WRITE_ENABLE command
    DDR_SPI |= (1<<DD_SS);                // Release EEPROM
    DDR_SPI &= ~(1<<DD_SS);   //ss goes low
    spi_transfer(WRITE); // write data to memory
    spi_transfer  (address>>8);
    spi_transfer (address);
    spi_transfer(Data);
    DDR_SPI |= (1<<DD_SS);   //ss goes high
}
unsigned char SPI_MasterReceive(uint16_t address)
{
    unsigned long data;
    SPCR = (1<<SPE) | (1<<MSTR) | (0<<CPHA);
    //waitBusy();
    DDR_SPI &= ~(1<<DD_SS);   //ss goes low
    spi_transfer(READ);  //enable write operation
    spi_transfer (address>>8);
    spi_transfer (address);
    data = spi_transfer(0xff);
    DDR_SPI |= (1<<DD_SS);   //goes high
    return data;
}

and this is main function
int main (void)
{
    char data;
    unsigned char address;
    serial_init();
    SPI_MasterInit();
    while(1)
    {
      data = Usart_Receive();
      _delay_ms(10);
      SPI_MasterTransmit(data);
      _delay_ms(10);
      data = SPI_MasterReceive(address);    //read data from the memory
      _delay_ms(10); //pause for readability
      Usart_Transmit(data);
    }
    return 0;
}

I hope someone can help me here.  :)

A: Your USART is transmitting too fast for your receiver. By your fourth time through the main loop, the USART transmitter has overwritten the "d" with "e" and then with "f".
A way to get around this is to use interrupts for receiving data, instead of polling like you are doing now. But you won't be able to write to the EEPROM as fast as the interrupts come. Instead, you should queue up the letters into a circular array or linked list or some other data structure as they arrive, and then write them to EEPROM in the main loop as time allows.
Note that this solution will only help with bursty data; you save up the burst and then deal with it as you can. But if the USART is continuously too fast, then you will never be able to keep up.

A: To debug this issue you need to localise the place of problem and to do this you have to split your experiment on sub-tasks.
One of them is to check UART separately, the code gets here like:
   while(1)
    {
      data = Usart_Receive();
      _delay_ms(10);
      Usart_Transmit(data);
    }

The second one is to check SPI apart from UART stuff if you have JTAG, or altogether if you get managed with making UART working. For the separate SPI checking just comment Usart_Receive(); and Usart_Transmit(data); initialize data with anything and probably increment it in the while. Hope this idea helps.


text:
Q: Can an OAuth scope confirmation screen have a choice for the user? I'm quite new to OAuth and looking at a idea for a service where users have a number of item profiles. I would like the user to be able to authorize access to certain information in one item profile but not others. So rather than just a list of text scopes on an authorization view, is it possible to display a list of profiles where they can select the one they want to share access to? And can that information be passed back the client app?
A similar analogy might be that a client app could be allowed detailed access to a single GitHub organisation, but not to any other orgs a user is a member of.

A: The third paragraph of 3.3. Access Token Scope in RFC 6749 says as follows.

The authorization server MAY fully or partially ignore the scope
requested by the client, based on the authorization server policy or
the resource owner's instructions.  If the issued access token scope
is different from the one requested by the client, the authorization
server MUST include the "scope" response parameter to inform the
client of the actual scope granted.

So, authorization server implementations may enable resource owners to choice scopes. Also, you can expect scope parameter comes back along with an access token when scopes granted actually are different from the ones requested originally by a client application.


text:
Q: Edit and continue not works in very simple one line method I have very simple class method. Here it is:
  public string SendDataInHandle(string handleName, string data)
  {
      return _connectionType.SendDataInHandle(handleName, data);
  }

I put a breakpoint on this line and trying to add console.writeline like this
  public string SendDataInHandle(string handleName, string data)
    {
        Console.WriteLine("123");
        return _connectionType.SendDataInHandle(handleName, data);
    }

And got an error:
Error   1   Modifying a 'method' which contains a dynamic invocation will prevent the debug session from continuing while Edit and Continue is enabled. *.cs  248 9   *
What am i doing wrong ? Where is dynamic invocation ? How to fix it ?
.net 4.5 simple console application with target platform x86

A: It's possible from this msdn that you "modified" the current executing line by inserting the Console.WriteLine.
Check out the first bullet here: http://msdn.microsoft.com/en-us/library/ms164927.aspx
"Changes to the current statement or any other active statement.
Active statements include any statements, in functions on the call stack, that were called to get to the current statement."


text:
Q: Binomial logistic regression or binomial GAM? I have presence/absence data of a species as my dependent variable and climatic data for my  independent variables.
The present samples are found within a particular range with the absent data generally either side.
To run a regression is it best to use a binomial logistic regression or binomial generalized additive model?


text:
Q: Is it possible to allocate huge array in c? Hi all i want to use the following :
int i;
unsigned short int **graph;
graph = (unsigned short int**)malloc (sizeof(unsigned short int *) * 65535);
if (graph == NULL ) fprintf(stderr, "out of memory\n");
for (i = 0; i < 65535; i++){
    graph[i] = (unsigned short int*)malloc (sizeof(unsigned short int) *65535);
    if (graph[i] == NULL ) fprintf(stderr, "out of memory\n");
}

the size 65535 is constant
i need to build this size of graph
is it possible?
will it help if i will split it ?
Thanks!

A: There are four different issues to consider here:
1) The size of the argument of malloc. It is of type size_t, which is an unsigned integer type that is at least 16 bits and large enough to hold the size of any object or the index of any array. In practice it tends to be the platform's native word size, i.e., 32 bits for 32-bit platforms, and 64 bits for 64-bit platforms, so you are likely to need at least a 32-bit platform, but this almost certainly the case unless developing for embedded (or very retro) systems.
One should also remember that the argument may overflow and you can silently end up successfully allocating less memory than you thought you'd get (e.g., you may effectively call malloc(65534) when you thought you were calling malloc(2 * 65535)). But in this case it is very unlikely to be an issue for any platform capable of allocating this amount of memory.
2) Whether the malloc calls succeed. You are already checking for this, so simply running the code will answer this. You are allocating over 8 GB† of memory here, so it is likely that it will fail unless compiled for 64 bits (since the maximum addressable memory for 32 bits is 4 GB).
3) Whether you can actually use all the memory you've allocated. Some operating systems will overcommit memory and allow you to allocate much more memory than is actually available. You may run into trouble if you actually try to use all the memory you've allocated. This depends on the OS and the amount of memory actually available, possibly including swap.
4) Whether it is practical for the machine the program is run on to actually have that much data in memory. Even if the malloc calls succeed and the OS lets you use the memory allocated, it is still over 8 GB, which means that a typical machine should probably have at least 12 GB of RAM installed to accommodate this, the OS, and other programs. Otherwise it may swap like crazy, despite theoretically working.
You have revealed in comments that you are running a 64-bit machine with 4 GB of RAM installed, so if you compile for 64 bits the first two points are not an issue, but point 3 may be, and point 4 almost certainly will be. So, either install more RAM or figure out a different way to handle the data (e.g., if you are storing a graph as per the variable name, perhaps it is often sparse enough that you don't need to allocate for the worst case).
† "over 8 GB" comes from 65535 * sizeof(short *) + 65535 * 65535 * sizeof(short), where sizeof(short) is very likely to be 2, and sizeof(short *) (the pointer size) either 4 or 8. There is also some extra overhead for malloc's bookkeeping, but still it rounds to "over 8 GB".
Some stylistic observations:

*

*It would be better style to use one of the types from stdint.h if you want specifically 16 bits, e.g., uint16_t or uint_least16_t

*You should not cast the return value of malloc in C (unlike in C++)

*You can replace sizeof(unsigned short int *) with sizeof(*graph) and sizeof(unsigned short int) with sizeof(**graph) to avoid repetition (and allow you to change the type of graph without changing the malloc calls)

*You don't need the int in unsigned short int

A: Max allowed size will be range of integer. So if you are using 16 bit OS max size is 65535, if you are using 32 bit OS size will be 4,294,967,295.

A: The maximum size of non-arrayed data is SIZE_MAX.  SIZE_MAX is at least 65535.
SIZE_MAX is type size_t which is often the same type as unsigned but may be different.
The single largest allocation available using malloc() is SIZE_MAX.
void *malloc(size_t size);

sizeof(unsigned short int *) * 65535 may fail due to integer math overflow.
To allocate an array larger than SIZE_MAX (but each element is still <= SIZE_MAX), use calloc().
void *calloc(size_t nmemb, size_t size);
unsigned short int **graph = calloc(65535u, sizeof *graph);


text:
Q: Does enabling LLVM's MemorySanitizer change the ABI of libraries The LLVM projects MemorySanitizer has a somewhat difficult to satisfy constraint that all system libraries must also be built with MemorySanitizer.
I've been thinking about some ways to enable MSAN for a project I'm working on (it already uses ASAN and UBSAN), specifically with respect to this constraint. One possible solution I've been considering would result in a situation where when the project was compiled with -fsanitize=memory, it would link against non-instrumented versions of dynamic system libraries like libc, and libstdc++, and, say libcrypto (to add one that isn't really part of the 'toolchain'). But then at runtime, the instrumented binary would run in a special environment (basically a different userspace) where all of the system dynamic libraries had been built with -fsanitize=memory.
Is such a scheme viable? It seems to me that it depends on whether building a library with -fsanitize=memory alters its ABI, because if the library ABI differs between the instrumented and non-instrumented versions, then the image built against the non-instrumented system dynamic libraries is going to fail catastrophically at runtime when started up in the environment with the instrumented system libraries.

A:
if the library ABI differs between the instrumented and non-instrumented versions, then the image built against the non-instrumented system dynamic libraries is going to fail catastrophically at runtime

First of all, compiling with -fsanitize=memory does change ABI e.g. by adding additional (shadow) operands to function calls. This means that combining sanitized and non-sanitized code at runtime will likely crash.
On the other hand, Msan does not change link-time library ABI i.e. it does not change symbol sizes or names so external interface of library (i.e. contents of it's ELF symbol table) compiled with -fsanitize=memory does not change.
This means that linking against non-sanitized version and later running with sanitized one is ok.


text:
Q: is the iPod Touch less able to connect to Airport WDS wifi network repeaters than an iPad? Kindle also doesn't want to! I have a wireless network in my apartment.  Because the apartment is large and walls are concrete, it was very hard to get wifi coverage throughout the whole place. Therefore I have one Airport Extreme, and then multiple Airport Expresses, and I have configured the airport expresses to join and extend the wireless network that is created on the main (airport extreme) unit.
The question:  When I am far from the original (airport extreme) unit, my iPad has no problem getting a four-bars connection from the satellite airport express that is relaying the connection. BUT, my ipod touch (and my Kindle also) can NOT connect to it. They just want to connect to the main central unit.
believe me I have re-configured this thing a DOZEN times... using the crystal clear normal method to get the distributed network going across all the airports... always the same problem.
Has anyone found this to be the case -- that the iPod Touch, and a regular lowest-level kindle (bottom of the line unit as of 2012), will not connect to the WDS satellite, only the main unit?
[I will admit, i am only somewhat sure that the method I use, where I configure the units to "join and extend" the main network, is actually the same as WDS.]

A: I've pretty much solved this problem. I do not FULLY understand why, but now I can have my iPod touch (and I am hoping my kindle) attach correctly to the satellite/repeater airport express.  Here is what I did:
I did two configuration changes to my central hub airport extreme router (i.e., the one that my other routers were merely configured to "extend.")  I realize now that these are both configurations that must be done at that central router, and the repeater routers then simply mimic or reflect accordingly.
-- First, I used the most recent Airport Utility (v6.0) and clicked on my main router (which, crucially, is an airport extreme that has dual band 802.11, both 2.4ghz and 5ghz.)
-- In the airport utility, I clicked on that Extreme router and then in its funky popup window, clicked Edit.
-- Clicked the tab called Wireless.
-- Clicked on Wireless Options button.
-- the first config change I made on that page was to change the Radio Mode setting to "802.11a/n - 802.11 b/g."
     What nobody really tells you is that that hyphenated choice means that the 5GHz band will use the first of those two (namely, a and n, in other words the strong modern N standard will be used on this band ONLY) ... while the 2.4GHZ band will use only the second of those two, b/g, in other words, the devices that only can use that older weaker standard.
     So, it's kind of a segregation. I'm telling it "No, don't let the 2.4 ghz band try to handle traffic using N. That band will just take care of the old crappy clients."
-- the second config change that I made on that page was to check the check box to make a totally separate wireless network name for the 5GHZ band.  Further segregating things.  When I tried my solution without this additional step, my problem did not fix itself, though I don't fully see why.
As I said, a few questions remain in my head, but the darn thing works, so I'm happy. Among many other questions... are those airport expresses dual-band too? I didn't think they were but somehow they are repeating this dual-band strategy?  Whatever. it works.
Wanted to say thanks to Richard, whose reply caused me to get off my butt and try more investigating into this.


text:
Q: Simple polymer script not working I'm new at polymer and my first script is not working...
My code:

index.php:
<!DOCTYPE html>

    <link rel="import" href="elements/hello-world.html">

    <hello-world></hello-world>

hello-world.html (Update):
<link rel="import" href="../bower_components/polymer/polymer.html">

<dom-module id="hello-world" noscript>
<template>

Hello World!

</template>

</dom-module>

The libraries:
polymer.html: http://pastebin.com/jd1rxAuH
wecomponents.js: http://pastebin.com/yBaJpFBi

Uploaded here: https://www.sese7.de/polymer/
I don't know what i've done wrong, thanks in advance ;)

A: As can be read at Polymer Migration Guide.

The <polymer-element> tag is no longer used to define an element. In this release, these are replaced by a <dom-module> element (to define local DOM and styles) and the Polymer call (to register the element).

A working example can be seen at http://webcomponents.org/hello-world-polymer/bower_components/hello-world-polymer/ where the hello-world.html is defined similar to:
<link rel="import" href="../polymer/polymer.html">
<dom-module id="hello-world">
    <template>

Hello world

    </template>

</dom-module>


text:
Q: MKV with FLAC to MP4 with FFMPEG I have a MKV file with a H264 video track, FLAC audio track and ASS subtitle track. I want to convert the file to a MP4 but keep the video track and re-encode the audio and subtitle tracks. How do I do that?

A: Use the -c/-codec and -map options.
ffmpeg -i input.mkv -map 0 -c:v copy -c:a aac -c:s mov_text output.mp4

*

*copy enables stream copy mode which only re-muxes and does not re-encode (the video in this example).

*See the ffmpeg documentation for more info.


text:
Q: Attraction & Lorentz force, at the same time? If a conductor carrying current is placed inside a magnetic field, we know that there is the Lorentz force pushing the wire. But what about the attraction force between the wire's field and the magnet/electromagnet's field? So, isn't there really two forces involved? Attraction due to two magnetic field, and Lorentz force?
Even if the pole of the "electromagnet" can attract the conductor.

A: The experiment is simplified because it assumes the field generated by the wire to be small compared to that of the external field. That means there is a given external field and you can integrate Newtons law with the Lorentz force seperately. If that simplification doesn't hold any more, one would (in principal) have to consistently solve the coupled system of both the  Maxwell's field equation and equations of motion, which might be a bit tricky in this case.
I wouldn't say that there are two forces involved, the field of the wire might weaken the external field which in turn weakens the Lorentz-force exerted on the wire.


text:
Q: Filling Color Gradient between points I have a bunch of (x,y) type points. Corresponding to these points there is an associated value (within a specific range). These values can be used to put color to them (using some color map).
If we now use these (x,y) and color we can have a pixelated image (with a color pixel at each x,y). Is there an easy way to fill the pixels between so that I get a sensible gradient of colors.
TLDR: How to fill pixels within a boundary when you know values at nearby pixels?
The thing which makes it difficult for me is I have much more pixels to fill than the number of already colored pixels.
Also can I control the gradient type (linear, quadratic etc.)


text:
Q: better understanding middleware protection in laravel I wrote a very simple middleware, like this:
class CheckToken
{

    private $token='xxx';
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        if (! $request->tokenz == $this->token) {
            return response('Unauthorized.', 401);
        }

        return $next($request);
    }
}

Then I register it trough kernel.php, like this:
protected $routeMiddleware = [
       .....
        'CheckToken' => \App\Http\Middleware\CheckToken::class,

    ];

then Ive a very simple function in a controller guarded by this controller:
public function __construct()
    {
        $this->middleware('CheckToken');
    }

    public function push()
    {
        return view('home');
    }

Now starts what is not clear to me:

*

*how can i "protect" my page using this simple method?
I've tried to put this tag on the header of page but it seems to not works, maybe im in the wrong path:
<meta name="tokenz" content="xxx">

I put it even in the body but no results.
what ive misunderstood?

A: I believe you need to add the middleware call to the actual route:
use App\Http\Middleware\CheckAge;

Route::get('admin/profile', function () {
    //
})->middleware(CheckAge::class);

This was extracted from the Laravel 5.7 documentation: Middleware - Assigning Middleware to Routes

A: sorry i can't create a comment. but just want to help.
does $request passed a tokenz?
you can use ?tokenz=blablabla
or you can change your method to get the tokenz


text:
Q: RequireJS and functions There is a part of my main.js that contains functions like these:
function isTrue(x){...}
function resizeEditors() {...}
function updateLayout() {...}
function prettify() {...}
function setTheme(theme) {...}
function themedLayout(isDark){...}
function enablePanel(panel) {...}
function disablePanel(panel) {...}
function enableDefaultPanels() {...}
function toggleFullscreen() {...}
function toggleEditorFullscreen(selected) {...}

Is there a way to make these functions available to my main.js file's dependencies?
for example, in editors.js I'm using the isTrue function but the editors.js module can't currently find isTrue because it's inside the main.js file
editors.setShowPrintMargin( isTrue( settings.showPrintMargin ) );

edit:
how the project look like:
main.js:
require(['jquery', 'appSession', 'editors'], function ($, appSession, editors) {
    function isTrue(x){...}
    function resizeEditors() {...}
    function updateLayout() {...}
    function prettify() {...}
    function setTheme(theme) {...}
    function themedLayout(isDark){...}
    function enablePanel(panel) {...}
    function disablePanel(panel) {...}
    function enableDefaultPanels() {...}
    function toggleFullscreen() {...}
    function toggleEditorFullscreen(selected) {...}
});

editors.js:
define(['jquery', 'appSession'], function($, appSession){
    ...
    editors.setShowPrintMargin( isTrue( settings.showPrintMargin ) );
    ...
    return editors;
});

A: Yes, you can return them.
define(function () {
    return {
        isTrue: function() {
            // Code
        },
        otherFunction: function() {
            // Code
        }
    }
});

Then use them ass this
require(["main"], function(main) {

    main.isTrue(false);

});

You can learn more about defining modules on the website.

A: You could create a module containing the shared/global functionality and make it a dependency of the modules that need it:
globals.js:
define([], function() {
    function isTrue(x){}
    // rest of functions...
    function toggleEditorFullscreen(selected) {}

    return { // return functions... };
});

Then to use it:
require(["globals", "editors"], function(globals, editors) {
    // ...
    editors.setShowPrintMargin(globals.isTrue(settings.showPrintMargin));
    // ...
});

Or if you wanted to use it within the editors module, you're editors.js would look like:
define(["globals"], function(globals) {
    // ...
    setShowPrintMargin(globals.isTrue(settings.showPrintMargin));
    // ...
});

Alternatively, if you really want them to be global you should be able to do:
window.isTrue = function(valueToCheck) {
    // implementation ...
};


text:
Q: How can i add Anaconda Prompt to VScode terminal? i'm trying to add anaconda prompt to vscode terminal.
i googled it, but i found that it's not possible method cuz
terminal.integrated.shell.windows
terminal.integrated.shellArgs.windows
is now unavailable on settings.
is there any way to solve this?

A: I'm sorry to tell you that it can't be realized at present.The Python extension automatically detects existing conda environments provided that the environment contains a Python interpreter. Although the Python extension for VS Code doesn't currently have direct integration with conda environment.yml files, VS Code itself is a great YAML editor.

A: The most I could think of is setting Conda as your interpreter (in the Command  Palette type in Python Interpreter, select it, and click on the one that says "conda"). That should allow you to run your code in the conda enviornment.


text:
Q: 'NoneType' object is not iterable when using context processors I wrote a simple function that passes some info inside base.html like bellow:
def payment_check(request):
    if request.user.is_authenticated:
        context = {
            'paymentCheck':PaymentInfo.objects.filter(user=request.user)
        }
        return context

but gives me 'NoneType' object is not iterable error.


text:
Q: How to configure a private DNS server on Windows 10? Android supports Cloudfare's private DNS 1dot1dot1dot1.cloudflare-dns.com.
But on Windows 10 I couldn't find a way to set up anything other than IPv4 and IPv6 DNS.

A: Windows does not yet have built-in support for DNS over TLS, and only the very latest Insider build 19628 has built-in support for DNS over HTTPS.
In the mean time, you can install a proxy such as Stubby or Dnscrypt which presents a "normal" DNS server on localhost, then relays them over either DoH or DoT.


text:
Q: Adding solder to PCB traces to increase current flow If I have a PCB with standard 1.4 mil copper thickness. I have used a trace width calculator based on IPC-2221 to determine that a 2.72mm trace is enough to handle 5 amps for an "external layer in air".
I have seen many times on power supply and relay board that people add solder to unmasked traces to increase the safe current flow.
I am using Sn63Pb37 solder. My finish is ENIG. I know that solder is much less conductive than copper.
My question is how much does this help? If I lay a fat convex blob of solder over the entire length of the track what ballpark level of increase in safe current flow can I expect?
I am sure an exact answer relies on various circumstances but a conservative value would be helpful.
I have seen in various claims on the internet that it can increase the amount of safe current by 40%-100%, but the sources seem to contradict each other. I would like to get an educated answer.
Is there any reason why doing this is a bad idea?
[EDIT]
I am going to attempt to answer this myself based on the information at PCB Tinning to increase current about how to figure out conductivity based on cross section and KalleMP's information about solder conductivity. Please correct me if I get any of this wrong.
Assuming a 1.4 mil thick copper trace with a width of 1 mm(to make the math simple) and a convex layer of solder going .5 mm tall at the highest point.
The cross section of the trace is a rectangle 1 mm wide by 1.4 mils(0.03556 mm) tall which gives an area of 0.03556 mm2.
Assuming a circular shape a 1mm wide and .5mm tall blob's cross section is a half circle so I use pi * .5^2/2 to get an area of about 0.3927 mm2.
If I go my what KalleMP said about solder being about 9-14% the conductivity of copper I can conclude that the effectiveness of the solder should be the equivalent of 0.035343-0.054978 mm2 of copper which is a 99-154% improvement, less depending on how thick the solder blob is.
This answer seems consistent with some of what I have heard from others, but I have also read of people doing actual tests and finding it closer to 40%. Does anyone see any fault in my reasoning? Are there other factors that would reduce the improvement such as the connection between the solder and copper?
[Note] at first I posted a different solution with an error, I think I have it right now.

A: It does work, but it is hard to model reliably and you should use empirical testing to see how well it works for your boards, process, environment, solder.
There can be a lot of variance from little things that are hard to predict and measure. For example, are you soldering by hand or running though a wave machine? The resulting solder profile cross sectional area can be off by 50% or more depending on which process you use- and neither of them resemble a half circle :) .
EEVBlog feauted a video where he tests exactly this question...
EEVblog #317 - PCB Tinning Myth Busting
And a similar video...
Does putting solder on high current PCB tracks help?

A: I can't give you a definitive answer but adding a thick layer of solder over top of a copper trace on a PCB does increase the current-carrying capacity significantly, especially for pulse loads.
That thick layer of solder increases the thermal mass of the copper trace.  The increased thermal mass reduces or prevents localized hot spots in the thin layer of copper trace.
Testing is required for your specific application.  Testing that I have done on some of my products showed that I was able to safely increase the current rating on a single-sided PCB with 1 oz copper by about double.  This is on boards wave-soldered with 63/37 solder.

A: One reason people may be giving numbers like 40% rather than 100% could be as simple as different starting points. Saying that soldered 1oz traces have roughly double the current carrying capability is functionally the same as saying that the solder has the same current carrying ability as a 1oz copper trace. Thus, if you add solder to a 2oz copper trace, you will only get a roughly 50% benefit, which falls close enough in line with the 40% number given.


text:
Q: Create a Python Dictonary by taking joins of two dictionary I have a Python dictionary, like so:
{0: 'Initialised', 1: 'Processed', 3:'Finished'}

I have a second Dictionary, like so:
{0: 81, 1: 100, 3: 906}

What I want is to get:
{'Initialised':81, 'Processed':100, 'Finished': 906}

What is the most efficient way to do this?

A: Do something like this
In [31]: t1 = {0: 'Initialised', 1: 'Processed', 3:'Finished'}
In [33]: t2 = {0: 81, 1: 100, 3: 906}

In [34]: {t1[key]: t2[key] for key in t1}
Out[34]: {'Finished': 906, 'Initialised': 81, 'Processed': 100}

Without Dictionary Comprehension:
t3 = {}
for key in t1:
    t3[t1[key]] = t2[key]

A: Handles absence of keys in the second dict.
{v: d2.get(k, None) for k, v in d1.items()}
# {'Finished': 906, 'Initialised': 81, 'Processed': 100}

A: Isn't it very simple ?
Example using dictionary comprehension (which is available from Python 2.7 onwards) -
>>> d1 = {0: 'Initialised', 1: 'Processed', 3:'Finished'}
>>> d2 = {0: 81, 1: 100, 3: 906}
>>>
>>> d = {d1[k]:d2[k] for k in d1.keys()}
>>> d
{'Finished': 906, 'Processed': 100, 'Initialised': 81}


text:
Q: How to insert a List<> into a constructor? I wanted to create a class constructor that Telefono as a parameter a string to insert into a list
The compiler I reports the error: "cannot implicitly convert to void a string"
How can I fix?
 public static class Telefono
    {
        public double LevelBattery { get; set; }
        public List<String> NomeTelefono { get; set; }
        public bool TelefonoON { get; set; }

        public Telefono(string telefono)
        {
            telefono = NomeTelefono.Add(telefono); //ERROR!!!!
        }

        public void ON()
        {
            Random x = new Random();
            int Batt = x.Next(100);
            LevelBatty = Batt;

            if (Levelbattery > 10)
                TelefonoON = true;
            else
            {
                Console.WriteLine("Ricaricare subito il telefono {0}. Batteria inferiore al 10%", NomeTelefono);
                Console.ReadLine();
                TelefonoON = false;
            }

        }

A: List<T>.Add doesn't return anything. I think you just want to initialize your list and add the item:
public Telefono(string telefono)
{
    NoneTelefono = new List<string>();
    NomeTelefono.Add(telefono);
}

A: you need to add
NomeTelefono = new List<string>();

in the constructor


text:
Q: Как отобразить текст android studio Я хочу что бы при нажатии на кнопку в разделе манифеста менялся текст в android:label=""

A: Это невозможно. Манифест упоковывается в приложение как статический ресурс вместе со строками, иконками, стилями etc. Менять его во время исполнения невозможно.

A: А зачем вам это?Вы можете заменить заголовок с помощью
setTitle(int titleId)

Или
setTitle(CharSequence title)

Но в манифесте это конечно ничего не изменит.


text:
Q: eliminar fila de tabla html con Jquery o JS ¿Como eliminar la fila de una tabla html con js o jquery o css?, Tengo una tabla que muestra registros producto de una Query SQL a mi BD, agrego un botón donde abre una modal para registrar algunos datos pertenecientes a ese registro, cuando ya he terminado de llenar el form, quiero eliminar esa fila de la tabla, hasta el momento tengo una función JS que coloco en otro botón dentro de la tabla

el boton dentro de la tabla si funciona, implemente el boton dentro de la modal pero solo me elimina el encabezado de la tabla, estas es mi funcion

    function Eliminar(i) {
        document.getElementsByTagName("table")[0].setAttribute("id", "tableid");
        document.getElementById("tableid").deleteRow(i);
    }

esta es mi modal

    @

                    <button type="button" class="close" data-dismiss="modal">×</button>

Agregar Campos

                                <form action="" class="formulario" name="formulario"  id="formulario">

                                        <input type="text" id="icc" name="icc" hidden/>
<input type="text" id="txtFechaa" name="txtFechaa" />

                                            <input type="text" id="celular" name="celular" class="campos">
                                            Celular

                                        Estatus

                                            <select name="estatus" id="estatus">
                                                <option value="" disabled selected>Selecciona Opción</option>
                                                <option value="PARAD">PARAD</option>
                                                <option value="OTROS">OTROS</option>
                                            </select>

                                        <input type="button" id="btn-submit" value="Enviar">

                                </form>

                                    Exito

                                    <input  type="button" value="Aceptar" onclick="Eliminar(this.parentNode.parentNode.rowIndex)" />
                                    <button type="button" class="btn btn-success" onclick="remove(this.parentNode.parentNode.rowIndex)">Aceptar</button>

A: Puedes colocarle un id a cada tr cuando estes pintando tu tabla, así en tu función Eliminar podes ir a darle un .remove (de jquery) de la siguiente forma:
$("#fila1").remove();

Te dejo un ejemplo en JSBIN: http://jsbin.com/teduko/edit?html,console,output
Tu tabla quedaría así y tu función eliminar solamente constaría de una línea:

function eliminarFila(index) {
  $("#fila" + index).remove();
}

    Columna 1
    Columna 2
    Columna 3
    Columna 4
    Columna 5
    Columna 6
    <input type="button" onclick="eliminarFila(0);" value="Eliminar" />

    Columna 1
    Columna 2
    Columna 3
    Columna 4
    Columna 5
    Columna 6
    <input type="button" onclick="eliminarFila(1);" value="Eliminar" />

    Columna 1
    Columna 2
    Columna 3
    Columna 4
    Columna 5
    Columna 6
    <input type="button" onclick="eliminarFila(2);" value="Eliminar" />

    Columna 1
    Columna 2
    Columna 3
    Columna 4
    Columna 5
    Columna 6
    <input type="button" onclick="eliminarFila(3);" value="Eliminar" />

    Columna 1
    Columna 2
    Columna 3
    Columna 4
    Columna 5
    Columna 6
    <input type="button" onclick="eliminarFila(4);" value="Eliminar" />

A: Mejorando un poco la idea de Wanderson, lo más práctico es tener una función que se fije directamente donde está el botón y borre esa línea, de esa manera no necesitas ningún tipo de id

$(document).on('click', '.borrar', function(event) {
  event.preventDefault();
  $(this).closest('tr').remove();
});

    Columna 1.1
    Columna 1.2
    Columna 1.3
    Columna 1.4
    Columna 1.5
    Columna 1.6
    <input type="button" class="borrar" value="Eliminar" />

Acá el ejemplo funcionando: http://jsbin.com/xekofexonu/1/edit?html,js,output


text:
Q: python, windows : parsing command lines with shlex When you have to split a command-line, for example to call Popen, the best practice seems to be
subprocess.Popen(shlex.split(cmd), ...
but RTFM

The shlex class makes it easy to write lexical analyzers for simple syntaxes resembling that of the Unix shell ...

So, what's the correct way on win32?
And what about quote parsing and POSIX vs non-POSIX mode?

A: There is no valid command-line splitting function so far in the Python stdlib for Windows/multi-platform so far. (Mar 2016)
subprocess
So in short for subprocess.Popen .call etc. best do like:
if sys.platform == 'win32':
    args = cmd
else:
    args = shlex.split(cmd)
subprocess.Popen(args, ...)

On Windows the split is not necessary for either values of shell option and internally Popen just uses subprocess.list2cmdline to again re-join the split arguments :-) .
With option shell=True the shlex.split is not necessary on Unix either.
Split or not, on Windows for starting .bat or .cmd scripts (unlike .exe .com) you need to include the file extension explicitely - unless shell=True.
Notes on command-line splitting nonetheless:
shlex.split(cmd, posix=0) retains backslashes in Windows paths, but it doesn't understand quoting & escaping right. Its not very clear what the posix=0 mode of shlex is good for at all - but 99% it certainly seduces Windows/cross-platform programmers ...
Windows API exposes ctypes.windll.shell32.CommandLineToArgvW:

Parses a Unicode command line string and returns an array of pointers
  to the command line arguments, along with a count of such arguments,
  in a way that is similar to the standard C run-time argv and argc
  values.

def win_CommandLineToArgvW(cmd):
    import ctypes
    nargs = ctypes.c_int()
    ctypes.windll.shell32.CommandLineToArgvW.restype = ctypes.POINTER(ctypes.c_wchar_p)
    lpargs = ctypes.windll.shell32.CommandLineToArgvW(unicode(cmd), ctypes.byref(nargs))
    args = [lpargs[i] for i in range(nargs.value)]
    if ctypes.windll.kernel32.LocalFree(lpargs):
        raise AssertionError
    return args

However that function CommandLineToArgvW is bogus - or just weakly similar to the mandatory standard C argv & argc parsing:
>>> win_CommandLineToArgvW('aaa"bbb""" ccc')
[u'aaa"bbb"""', u'ccc']
>>> win_CommandLineToArgvW('""  aaa"bbb""" ccc')
[u'', u'aaabbb" ccc']
>>>

C:\scratch>python -c "import sys;print(sys.argv)" aaa"bbb""" ccc
['-c', 'aaabbb"', 'ccc']

C:\scratch>python -c "import sys;print(sys.argv)" ""  aaa"bbb""" ccc
['-c', '', 'aaabbb"', 'ccc']

Watch http://bugs.python.org/issue1724822 for possibly future additions in the Python lib. (The mentioned function on "fisheye3" server doesn't really work correct.)

Cross-platform candidate function
Valid Windows command-line splitting is rather crazy. E.g. try \ \\  \"  \\"" \\\"aaa  """" ...
My current candidate function for cross-platform command-line splitting  is the following function which I consider for Python lib proposal. Its multi-platform; its ~10x faster than shlex, which does single-char stepping and streaming; and also respects pipe-related characters (unlike shlex).  It stands a list of tough real-shell-tests already on Windows & Linux bash, plus the legacy posix test patterns of test_shlex.
Interested in feedback about remaining bugs.
def cmdline_split(s, platform='this'):
    """Multi-platform variant of shlex.split() for command-line splitting.
    For use with subprocess, for argv injection etc. Using fast REGEX.

    platform: 'this' = auto from current platform;
              1 = POSIX;
              0 = Windows/CMD
              (other values reserved)
    """
    if platform == 'this':
        platform = (sys.platform != 'win32')
    if platform == 1:
        RE_CMD_LEX = r'''"((?:\\["\\]|[^"])*)"|'([^']*)'|(\\.)|(&&?|\|\|?|\d?\>|[<])|([^\s'"\\&|<>]+)|(\s+)|(.)'''
    elif platform == 0:
        RE_CMD_LEX = r'''"((?:""|\\["\\]|[^"])*)"?()|(\\\\(?=\\*")|\\")|(&&?|\|\|?|\d?>|[<])|([^\s"&|<>]+)|(\s+)|(.)'''
    else:
        raise AssertionError('unkown platform %r' % platform)

    args = []
    accu = None   # collects pieces of one arg
    for qs, qss, esc, pipe, word, white, fail in re.findall(RE_CMD_LEX, s):
        if word:
            pass   # most frequent
        elif esc:
            word = esc[1]
        elif white or pipe:
            if accu is not None:
                args.append(accu)
            if pipe:
                args.append(pipe)
            accu = None
            continue
        elif fail:
            raise ValueError("invalid or incomplete shell string")
        elif qs:
            word = qs.replace('\\"', '"').replace('\\\\', '\\')
            if platform == 0:
                word = word.replace('""', '"')
        else:
            word = qss   # may be even empty; must be last

        accu = (accu or '') + word

    if accu is not None:
        args.append(accu)

    return args


text:
Q: Remove Eclipse menu option I want to remove an Eclipse menu option (Amazon Web Services)

A: If you want to really remove the AWS features you need to uninstall the AWS plug-in(s) that contribute it. In the Help menu, select Installation Details. In the resulting dialog you can find the Amazon Web Services feature(s), select it, then use the Uninstall... button to uninstall it.
On the other hand, if you just want to hide the menu item but leave the AWS features in Eclipse, see https://stackoverflow.com/a/3482357/639520


text:
Q: Could not load file or assembly 'EntityFramework.SqlServer, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' I am using ASP.NET 5 and Entity Framework 6 (precisely 6.1.3), following this link. Tried every different solution like

*

*Scrapping of Version in appconfig

*Adding <dependentAssembly>

*Reinstalling EntityFramework 6 again using Update-Package
-reinstall EntityFramework

*Check EntityFramwork.SqlServer

*Cleared %temp% and did clean build along with standalone rebuild

I get error here
[DbConfigurationType(typeof(CodeConfig))]
public class MyContext : DbContext
{
public MyContext()
        : base("DefaultConnection") <-- error here
    {
    }
 }

But still couldn't resolve this error, any helpful links would be appreciated

Could not load file or assembly 'EntityFramework.SqlServer, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' or one of its dependencies. The system cannot find the file specified.":"EntityFramework.SqlServer, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"

Stack Trace
at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
   at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
   at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
   at System.Activator.CreateInstance(Type type, Boolean nonPublic)
   at System.Data.Entity.Utilities.TypeExtensions.CreateInstance[T](Type type, Func`2 exceptionFactory)
   at System.Data.Entity.Utilities.TypeExtensions.CreateInstance[T](Type type, Func`3 typeMessageFactory, Func`2 exceptionFactory)
   at System.Data.Entity.Infrastructure.DependencyResolution.DbConfigurationManager.<.ctor>b__1()
   at System.Lazy`1.CreateValue()
   at System.Lazy`1.LazyInitValue()
   at System.Lazy`1.get_Value()
   at System.Data.Entity.Infrastructure.DependencyResolution.DbConfigurationManager.GetConfiguration()
   at System.Data.Entity.Infrastructure.DependencyResolution.InternalConfiguration.get_Instance()
   at System.Data.Entity.DbConfiguration.get_DependencyResolver()
   at System.Data.Entity.DbContext.InitializeLazyInternalContext(IInternalConnection internalConnection, DbCompiledModel model)
   at System.Data.Entity.DbContext..ctor(String nameOrConnectionString)
   at myproject.data.myprojectContext..ctor() in D:\Projects\Personal\myproject\myproject.data\myprojectContext.cs:line 12
   at myproject.data.Infrastructure.DatabaseFactory.Get() in D:\Projects\Personal\myproject\myproject.data\Infrastructure\DatabaseFactory.cs:line 9
   at myproject.data.Repository`1.get_DataContext() in D:\Projects\Personal\myproject\myproject.data\Repository.cs:line 28
   at myproject.data.Repository`1..ctor(IDatabaseFactory databaseFactory) in D:\Projects\Personal\myproject\myproject.data\Repository.cs:line 21
   at myproject.data.Repository.ProfileRepository..ctor(IDatabaseFactory databaseFactory) in D:\Projects\Personal\myproject\myproject.data\Repository\ProfileRepository.cs:line 9

Web.Config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework.SqlServer, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <connectionStrings>
    <add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="...." />
  </connectionStrings>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>

A: First check which version EF you are using. Check the your version.
If you want to upgrade your version you can manage EF upgrade from NuGet.
Go to your Project solution - > 'Manage NuGet packet for Solution', click 'Manage' on 'Entity Framework'.
Now, Check your app.config . Maybe here wrong version number. The name="entityFramework" should have the correct version number.
Other then this, you should try installing the nuget package for EntityFramework.SqlServer by using following command in package manager console.

Install-Package EntityFramework.SqlServer -Version 7.0.0-beta6 -Pre

A: The parameter of base (DbContext constructor) can be a nameOrConnectionString. See DbContext(string).
So you should add name= to the parameter string.
[DbConfigurationType(typeof(CodeConfig))]
public class MyContext : DbContext
{
    public MyContext()
        : base("name=DefaultConnection")
    {
    }
}

See also this example: Derived context


text:
Q: Нужно ли делать проверку на Assigned перед вызовом Free или FreeAndNil? Довольно часто в коде встречается вот такая конструкция:
MyObj: TObject;

..

if Assigned(MyObj) then
  FreeAndNil(MyObj);

или:
if Assigned(MyObj) then
  MyObj.Free;

Логика пишущего код скорее всего такая - "проверим указатель на валидность, перед тем как к нему обращаться".
Вопрос, нужна ли проверка if Assigned перед вызовом FreeAndNil или Free?

A: Нет, такая проверка не нужна.
Процедура Assigned не проверяет валидность указателя, как многие иногда полагают, она лишь проверяет указатель на nil (справка).
Метод Free уже содержит проверку на nil в себе (проверяется по исходникам TObject.Free).
Процедура FreeAndNil присваивает указателю nil и так же вызывает Free, в котором присутствует эта проверка (также проверяется по исходникам SysUtils.FreeAndNil).


text:
Q: jQuery: Convert to a single tag I want to convert the below HTML to single tag:
Before :

        Child1

        Child2

        Child1

        Child2

After :

  <button>Child1</button>
  <button>Child2</button>

  <button>Child1</button>
  <button>Child2</button>

i tried with wrapping/unwrapping. But it does not work. This I want to be generic.

A: Try this (demo):
$('div[class^="Parent"]').each(function(index, parent) {
  var html = [];
  $('a', parent).each(function(index, child) {
      html.push('<button>'+$(child).html()+'</button>');
  });
  $(parent).html(html.join(''));
});

It assumes that there is a pattern to the parent divs but that that isn't some common class name.

A: One way to do it:
$("a").unwrap().wrap("<button>").parent().text(function () {
    return $(this).text();
});

http://jsfiddle.net/Tomalak/Gct7H/
Another one in the same spirit:
$("a").unwrap().replaceWith(function () {
    return $("<button>", {text: $(this).text()});
});

PS: In reality you would want to select something more specific than just $("a"). Maybe $("#container a") or $("a.someClass"), depending on your markup.