Unable to change the title of header links

Question: I am using a wordpress theme. I have configured it successfully, but when I try to place social icons, for instance, facebook on top, I need to change the title of the same from "Theme on facebook" to "click here to like". I tried to change the theme-options.php file under admin folder as well as header files, but to no success. Even I founded and replaced every title with "facebook", but it is still being showed as "Theme on facebook".
The below code under the file header-extensions.php is printing this code.
/****************************************************************************************/

if ( ! function_exists( 'theme_socialnetworks' ) ) :

/**

 * This function for social links display on header

 *

 * Get links through Theme Options

 */

function theme_socialnetworks( $flag ) {

    global $themee_theme_options_settings;

   $options = $theme_theme_options_settings;

    $theme_socialnetworks = '';

    if ( ( !$theme_socialnetworks = get_transient( 'theme_socialnetworks' ) ) && ( 1 == $flag ) )  {

        $theme_socialnetworks .='

';

                $social_links = array();

                $social_links_name = array();

                $social_links_name = array( __( 'Facebook', 'theme' ),

                                            __( 'Twitter', 'theme' ),

                                            __( 'Google Plus', 'theme' ),

                                            __( 'Pinterest', 'theme' ),

                                            __( 'Youtube', 'theme' ),

                                            __( 'Vimeo', 'theme' ),

                                            __( 'LinkedIn', 'theme' ),

                                            __( 'Flickr', 'theme' ),

                                            __( 'Tumblr', 'theme' ),

                                            __( 'Myspace', 'theme' ),

                                            __( 'RSS', 'theme' )

                                            );

                $social_links = array(  'Facebook'      => 'social_facebook',

                                                'Twitter'       => 'social_twitter',

                                                'Google-Plus'   => 'social_googleplus',

                                                'Pinterest'     => 'social_pinterest',

                                                'You-tube'      => 'social_youtube',

                                                'Vimeo'         => 'social_vimeo',

                                                'Linked'            => 'social_linkedin',

                                                'Flickr'            => 'social_flickr',

                                                'Tumblr'            => 'social_tumblr',

                                                'My-Space'      => 'social_myspace',

                                                'RSS'               => 'social_rss'

                                            );

                $i=0;

                foreach( $social_links as $key => $value ) {

                    if ( !empty( $options[ $value ] ) ) {

                        $theme_socialnetworks .=

                            '
'.get_bloginfo( 'name' ).' '.$social_links_name[$i].'
';

                    }

                    $i++;

                }

                $theme_socialnetworks .='

';

        set_transient( 'theme_socialnetworks', $theme_socialnetworks, 86940 );

    }

    echo $theme_socialnetworks;

}

endif;

/****************************************************************************************/

I even removed the full div, but it is still printing it.
Comment: _"but do you expect me to post that hell lot of code here"_ – no, I expect you to do what I already said – identify _relevant_ parts of code, and post them here.
Comment: What code have you tried? Post something from your header or the part which takes care of the social media links.
Comment: Just clear your cache and try again.
Comment: I was very sure this question was going to come, but mate, this is not an HTML/javascript/CSS issue that I am facing that I can post a code. I even cannot make a fiddle. Do you get my point?? The best way to debug it would be to check the link that I have posted and downloading it on your localhost and accessing it by a WYSIWYG editor to find all the links where it says "Facebook". Am I sounding good @berentrom ??
Comment: When I inspect your them that show on anger tag of your FB link. I think it can change on your header.php file on them folder.
Comment: sorry @Kannan couldn't get you .. Can you please elaborate so that I shall do it live ??
Comment: ok Sir @CBroe, let me try doing that one for you :)
Comment: Sir @CBroe, I have updated my question as per your guidance. You can have a look. (I appreciate your criticism when you did not got what you came to look for, but at the same time, I shall appreciate your contribution when I founded the MOST RELEVANT area which is where the issue is coming from.) Thank you :)
Answer: Go to line 353 in library/structure/header-extensions.php to find the code for the output of these icons.
The layout is {BLOG NAME} on {SOCIAL NETWORK NAME}. It uses get_bloginfo( 'name' ) to get the name of your site. Is or has the title of your site been "Attitude"?
The icons use a transient and it's not clear from this file how that transient is cleared so if you've changed your site name and it's still showing up that will be why.
Run the following at the top of your functions.php to be sure.
delete_transient( 'attitude_socialnetworks' );

Remove after you've run once.
UPDATE: I just noticed you wanted to use "Facebook" etc as the titles. In that case you would modify line 353 of that file to:
'
'.get_bloginfo( 'name' ).' '.$social_links_name[$i].'
';

Make sure to run the delete transient code after making this change.
Comment: Let me just try that .. +1 for your time and efforts .. Hope this works :)
Comment: No @Nathan it still shows the same, infact, I also removed the `%1$s on %2$s`, but it still prints this sting and shows the same :(
Comment: Did you delete the transient? If it's still showing like this you'll need to trace back the code from the header output.
Comment: I just deleted the full `` code, but it is still printing :O How can this happen?? - @Nathan
Comment: Was the UL code inside the transient?
Comment: Here is the code http://jsfiddle.net/qAA5b/ (under the HTML section) - @Nathan
Comment: Did you delete the transient like I told you to? Anything that appears inside that transient will remain the same for the next day. You can remove it entirely but until the transient expires or you delete it everything will stay the same.
Comment: I have kept it as you mentioned on functions.php file, but I removed it when you had mentioned in your answer. There is no transient file now - @Nathan
Comment: I'm struggling to explain this but I can assure you the issue stems from the transient.
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/47939/discussion-between-nathan-lee-and-nathan-dawson)


How to set numpy matrix boundries to zeros?

Question: I have numpy 10×10 matrix
image=np.ones((10,10))

I want to set its boundaries to zero.
h,w=image.shape
image[:,0:2] = 0
image[:,w-2:w] = 0
image[0:2,:] = 0
image[h-2:h,:] = 0

Is there more efficient way to do this?
Thanks
Answer: Make the zeros first then assign the ones to the middle of the zeros.
>>> import numpy as np
>>> a = np.zeros((10,10))
>>> b = np.ones((6,6))
>>> a[2:-2,2:-2] = b

Or if the ones already exist.
>>> a = np.ones((10,10))

Make the zeros and do a similar assignment,
>>> b = np.zeros_like(a)
>>> b[2:-2,2:-2] = a[2:-2,2:-2]

You can use slices also if you are going to use it many times.
>>> s = slice(2,-2)
>>> b[s,s] = a[s,s]

Comment: I actuly used this solution
>>> b = np.zeros_like(a)
>>> b[2:-2,2:-2] = a[2:-2,2:-2]
but can I find more efficient way
Answer: Here I'm assuming that you want a 10x10 matrix, where the central 6x6 block are ones while the rest are zeros. You can use np.pad for this (but you don't need to create a larger matrix beforehand):
image = np.ones((6, 6))
padded = np.pad(image, (2, 2), mode='constant')

Answer: I think you are using the right approach. In order to make this point apparent, I'm going to compare your solution to the other solutions proposed so far (please, notice that I have taken the liberty to refactor your code):
import numpy as np

def pad_anas(img, width=2):
    img[:width, :] = 0
    img[-width:, :] = 0
    img[:, :width] = 0
    img[:, -width:] = 0
    return img

def pad_wwii(img, width=2):
    b = np.zeros_like(img)
    b[width:-width, width:-width] = img[width:-width, width:-width]
    return b

def pad_diehard(img, width=2):
    cropped = img[width:-width, width:-width]
    padded = np.pad(cropped, (width, width), mode='constant')
    return padded

First, we check that the codes work as expected:
In [66]: x = np.random.randint(low=0, high=10, size=(10, 10))

In [67]: x
Out[67]:
array([[4, 7, 7, 5, 7, 2, 7, 8, 0, 0],
       [6, 0, 3, 8, 7, 6, 3, 7, 9, 6],
       [0, 6, 9, 2, 6, 6, 3, 3, 1, 3],
       [7, 1, 5, 1, 4, 1, 5, 0, 3, 0],
       [9, 5, 1, 6, 5, 6, 5, 2, 6, 3],
       [8, 7, 7, 5, 9, 0, 2, 6, 4, 2],
       [3, 7, 0, 2, 5, 0, 5, 0, 6, 5],
       [3, 9, 9, 7, 6, 4, 8, 6, 9, 2],
       [6, 0, 5, 2, 9, 5, 9, 1, 2, 8],
       [6, 1, 5, 6, 9, 7, 2, 3, 7, 4]])

In [68]: pad_anas(x.copy())
Out[68]:
array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 9, 2, 6, 6, 3, 3, 0, 0],
       [0, 0, 5, 1, 4, 1, 5, 0, 0, 0],
       [0, 0, 1, 6, 5, 6, 5, 2, 0, 0],
       [0, 0, 7, 5, 9, 0, 2, 6, 0, 0],
       [0, 0, 0, 2, 5, 0, 5, 0, 0, 0],
       [0, 0, 9, 7, 6, 4, 8, 6, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])

In [69]: np.all(pad_anas(x.copy()) == pad_wwii(x))
Out[69]: True

In [70]: np.all(pad_anas(x.copy()) == pad_diehard(x))
Out[70]: True

It is worth pointing out that your approach changes img in place (that's why I passed a copy of x in the calls to pad_anas()). Let us now measure execution time:
In [71]: %timeit pad_wwii(x)
4.91 µs ± 477 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

In [72]: %timeit pad_diehard(x)
27.3 µs ± 2.86 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

In [73]: %timeit pad_anas(x)
2.53 µs ± 186 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

The results above make it evident that your approach is the best performer (similar results are obtained when using larger arrays or different widths).
Answer: Though I have the feeling there should be an outperforming one-liner for this "inverse slicing" or "inplace padding", I couldn't figure it out.
What I have to add is that (at least for large margins m) the following modification seems to slightly reduce the runtime:
img[:m, :] = 0
img[-m:, :] = 0
img[m:-m, :m] = 0
img[m:-m, -m:] = 0


valid-url not accessible from @heroku-cli/plugin-buildpacks

Question: This is the error I am getting constantly while trying to upload my app to Heroku no wonder what I am doing wrong.
I have updated node_modules reinstalled them
have cli installed and running in vs code.
<code>npm ERR! valid-url not accessible from @heroku-cli/plugin-buildpacks
remote:
remote:        npm ERR! A complete log of this run can be found in:
remote:        npm ERR!     /tmp/npmcache.Zudji/_logs/2021-10-11T07_16_45_740Z-debug.log
</code>

UPDATE -
little update! actually what was happening is i was missing the npm version and node version in pakage.json i added them in my package.json file but somehow it was not getting updated in the git repository even after several commits so what i did is i used: git push -f origin master. To force push it in the repository and as soon as it gets updated Heroku started reading it and the build succeeded thanks for the help though.
Answer: little update! actually what was happening is i was missing the npm version and node version in pakage.json i added them in my package.json file but somehow it was not getting updated in the git repository even after several commits so what i did is i used: git push -f origin master. To force push it in the repository and as soon as it gets updated heroku startedn reading it and the build succeeded thaks for the help though.:sparkles: :sparkles: :sparkles: :sparkles: :sparkles: :sparkles:
Comment: Hello! I think it would be more helpful if you used some formatting in your answer, so others could clearly see what is code, period and sentences.


Add no carrinho com Ajax sem atualizar a página - Laravel

Question: Estou tentando usar Ajax em um form para adicionar produtos no carrinho sem atualizar a página mas não estou conseguindo, se alguém puder me ajudar.
Estou usando Laravel 5.3 baseado neste site:
HTML
<form id="form_ideal" action="/cart/add" method="post" name="add_to_cart">
 {!! csrf_field() !!}
<input type="hidden" name="product" value="{{$product->id}}" />
<input type="hidden" name="qty" value="1" />
<button class="btn-add-to-cart"> Buy Now </button>
</form>

Script que estou tentando:

O que acontece é que ao clicar no botão de add ao carrinho ele mostra a mensagem de sucesso mas não atualiza a quantidade no menu, fica "0", só atualiza depois que dou F5 na página,
Desculpa se tiver fazendo algo errado mas comecei a pouco tempo a mexer com Laravel, ajax, essas coisas..
Answer: Se você atualiza e aparece quer dizer que você já implementou essa função, então é só passar essa quantidade para o client, para atualizar carrinho com o método html do J-query, exemplo...
em /cart/add devolva a quantidade assim.
$retorno = array('quantidade' => $quantidadeNoCarrinho, 'msg' => 'sucesso!');
echo json_encode($retorno);
exit();

em success pegue essa quantidade
success: function(retorno) {
                alert(retorno.msg);
                $('.quantidade').html(retorno.quantidade)
                }

Comment: Olá Felipe, esse primeiro código eu coloco no controller? e o segundo no script? Desculpe como eu disse comecei a pouco tempo e não entendo muito ainda, Obrigado
Comment: O primeiro é no php, um simples echo, apontando um json, o segundo é j-query, repare que é uma parte do seu código já pronto só fiz umas modificações.


How to determine what websites or local applications are using JVM/JRE

Question: We run a large Windows shop -- tens of thousands of workstations. Most have a version of the Sun/Oracle Java Virtual Machine (JVM) installed.
With all the security issues around the JVM, we'd like to better determine what folks are using Java for on our PCs. So for example, we'd be interested in better knowing the local Windows applications that invoke the JVM for some functionality or understanding the web sites which include Java that cause the JVM plugin to fire off.
Does anyone have experience or good ideas on how to find this kind of information out? For example, is there some way to configure the JVM to log the application that invoked it or what web sites it's interacting with? Or is information like this already somewhere like the event log?
Answer: I am not a Windows administrator but I believe you could invoke WMIC.exe remotely and get information about what Java process are currently running on remote systems.  Also, you may be able to remotely access a Registry on domain member machines.
Comment: Thanks. We have SCCM in place and have been tracking whether or not Java's being used on our workstations, so we definitely can remove it from workstations that don't need it. The trouble we're having is determining what the folks who are using Java are actually using it for. We were hoping that there was a way to log this information so that we could gather it up later.
Comment: Not that I have ever heard of.  I don't think there is such a thing.  All you can do is monitor the systems using Windows tools.  With WMIC you can get the full execution path (and args) of a Java program (if you know what the system PATH is).


R Association rules - is my understanding correct?

Question: I'm a developer and I've being playing around with R association rules to create a recommendation system. My stats understanding is a little basic. So I've created a set of rules with varying levels of confidence and I can use this to make predictions. However what I thought would be interesting would be to design a report a little like Excel's Shoppimg Basket analysis looking at the baskets and show their total value (i.e. basket occurence * value).
If I took the left hand side and right side of the rules generated by e.g. The rules with 0.8 confidence or higher. What in basic terms is that. Is it the most likely basket?
Comment: You need to consider both values: "Support" and "Confidence". In the other words "lift" give you a better insight about the importance of a rule. As an example: you have only one observation that someone that bought milk also bought cheese.  You do not have any other observation about milk and cheese. In this scenario your confidence is 1 but this rule can not be very reliable because you have only 1 support that back your rule.
Comment: Ok so is support the number of times a rule occurs. Where does lift fit into this? Cheers.
Comment: Support indicates the frequency of a rule. Lift shows how much an  antecedent increase the probability of the consequence. We can say if a lift is greater than 1 the antecedent positively affect the consequence. The more is better, we can say , for example, if lift is 1.25 the antecedent increase the probability of occurrence of the consequence by 25% .
Comment: Right. So in my particular case I'd like to examine the most popular baskets. I guess the highest support is the number to sort by. Would it be fair to say the left hand combined with the right hand would be the whole basket?
Comment: That's true. You can say their combination is the whole basket and support shows the most popular baskets. but again be careful about the interpreting the results. You might have some baskets with high supports with low confidence. It means, although the left hand item happened many times with the right hand one but it is very likely that the left hand one occur with the other items, as well.
Comment: That's great. I understand a lot better. Cheers.
Comment: @MFR, please consider developing your comments into an official answer.
Comment: @gung sure, I'll do shortly
Answer: An association rule is an an implication of expression of the  form $X$ results in $Y$ and the strength of an association rule can be measured in terms both values:Support and Confidence. Both of them are great metrics but can cause some confusion. Support is important because a rule that has low support may occur by chance. Confidence measure the reliability of the inference made by rule.  In the other words Lift give you a better insight about the importance of a rule.
Lift shows how much an antecedent increase the probability of the consequence. We can say if a lift is greater than 1 the antecedent positively affect the consequence. The more is better, we can say , for example, if lift is 1.25 the antecedent increase the probability of occurrence of the consequence by 25%
In your example, you can say the combination of the right hand and left hand items is the whole basket and support indicates the most popular baskets. But again be careful about the interpreting the results. You might have some baskets with high supports with low confidence. It means, although the left hand item happened many times with the right hand one, it is very likely that the left hand one occur with the other items, as well.
I don't go to mathematics behind them since they are very simple.


Existence of absolutely continuous measure

Question: Does there exists a finite measure $\mu$ on the $\sigma-$algebra of Lebesgue measurable subsets of $\mathbb{R}$ such that $\mu << m$ and $m <<\mu$, where $m$ is the Lebesgue measure?
My attempt is to use the Radon-Nikodym theorem to arrive at a contradiction but I am stuck. Any help will be appreciated.
Comment: How about $\mu(A)=\int_A\exp(-x^2)m(dx)$?
Comment: How do we compute $\mu(E)$ if $m(E)=0$?
Comment: I realized that I think your $\mu$ will actually work. Thank you!
Answer: Pick your favorite positive function $f\in L^1(\mathbb{R},\mathrm dm(x))$ and define
$$
\mu(A)=\int_A f(x)\;\mathrm d m(x)
$$
for $A$ a Lebesgue measurable set.
Comment: Hmmm, should $f$ be necessarily integrable on $\mathbb{R}$?
Comment: @JohnThompson I missed the important caveat that the measure be finite! Of course yes take $f$ to be $L^1$
Comment: I agree that any such integrable $f$ will work. Thanks!
Comment: @JohnThompson sure thing. Good luck
Answer: How about defining the function
$$
\phi(x) = {\pi \over 2} + \arctan(x)
$$
and defining, for every interval $A = ]a, b[$ in $\mathbb{R}$, even if $a = -\infty$ or $b = +\infty$ or both,
$$
\mu(A) = \phi(b) - \phi(a),
$$
taking the necessary limits if the interval is not bounded?
The idea of $g(x)$ is to map unbounded intervals to bounded ones, guaranteeing the constructed measure will be finite.
I suppose $g(x) = \phi'(x)$ can be seen as a Radon-Nykodym derivative that will do the job.
Answer: Take $\mu(A) =\sum \frac {m(A \cap (-n,n))} {2^{n}}$.


Longest 3rd and 4th down conversions

Question: In week 9 of 2017 season LA Rams converted a 3rd and 33 and scored a touchdown on the same play against the New York Giants.
Inspired by this, I'm wondering what are the longest 3rd and 4th down conversions in the history of the NFL in the regular and the post seasons. Also provide the same stats for longest 3rd/4th down and goal conversions.
Comment: When you say "conversion", would a 70 yard pass on 4th and 1 be considered a long conversion or a short conversion?
Comment: A short conversion
Answer: It was surprisingly difficult to find solid data on this - individual play data is only readily available back to 1994, so consider this accurate up to that point. Anyway, the longest 3rd down conversion I could find was Viking Leroy Hoard running 53 yards up the middle on 3rd and 37 against the Broncos on 10/31/99.
The longest 4th down conversion since 1994 was the Bill's Rob Johnson throwing a bomb for a 40 yard touchdown to Peerless Price against the Colts on 4th and 34 on 9/23/01.
The longest down since 1994 was 3rd and 50 yards, faced by two teams: the Vikings vs. the Packers (12/20/99) and the Redskins vs. the Bengals (9/23/12). Neither was converted.
The longest 4th down since 1994 was a 4th and 48 by the Raiders against the Chiefs on 10/13/13. They unsurprisingly punted.
I can't find a way to filter for 3rd/4th and goal, but hopefully this at least partially scratches your itch. All plays found with this tool.

Longest 3rd and 4th down conversions


NumPy `a.resize` adds non-zero values

Question: I was writing an adjacency matrix, and was trying to use the np.ndarray.resize to add all-zero rows and columns. According to the np.resize documentation:

If the new array is larger than the original array, then the new array is filled with repeated copies of a. **Note that this behavior is different from a.resize(new_shape) which fills with zeros instead of repeated copies of a.

However, I tried both the np.resize and the np.ndarray.resize, and they both add an unexpected value. My question is Why is this happening? (I know how to go around the problem, but I don't know why it's happening).
import numpy as np

class MatrixGraph:
  def __init__(self):
    self.nodes = np.array([], dtype=int)

  def add_node(self, node):
    if node >= len(self.nodes):
      # self.nodes.resize((node+1, node+1))
      self.nodes = np.resize(self.nodes, (node+1, node+1))

  def from_edges_list(self, edges, bidirectional=False):
    for edge in edges:
      self.add_node(edge[0])
      self.add_node(edge[1])
      self.nodes[edge[0], edge[1]] = 1
      if bidirectional:
        self.nodes[edge[1], edge[0]] = 1

  def edges_list(self):
    return list(zip(*np.where(self.nodes)))

g = MatrixGraph()
g.from_edges_list(((1, 2), (1, 4), (4, 2), (2, 5), (5, 4), (3, 5), (3, 6), (6, 6)))

print(g.edges_list())
print(g.nodes)

Prints
[(0, 5), (1, 2), (2, 0), (2, 3), (3, 1), (3, 2), (3, 6), (4, 2), (4, 6), (5, 6), (6, 3), (6, 6)]
[[0 0 0 0 0 1 0]
 [0 0 1 0 0 0 0]
 [1 0 0 1 0 0 0]
 [0 1 1 0 0 0 1]
 [0 0 1 0 0 0 1]
 [0 0 0 0 0 0 1]
 [0 0 0 1 0 0 1]]

Notice that there are a lot of edges that I didn't try adding. Moreover, I don't even have the 0 node, and it still populates it.
Edit 1: Here are the visualizations of the expected graph and the graph that the MatrixGraph frankensteins:
Expected:

Got:

Edit 2: When using the np.ndarray.resize (commented out in the example code above), I get a different result (still incorrect tho):
[(0, 5), (1, 2), (2, 3), (3, 1), (3, 2), (3, 6), (4, 6), (6, 6)]
[[0 0 0 0 0 1 0]
 [0 0 1 0 0 0 0]
 [0 0 0 1 0 0 0]
 [0 1 1 0 0 0 1]
 [0 0 0 0 0 0 1]
 [0 0 0 0 0 0 0]
 [0 0 0 0 0 0 1]]

Comment: Use `np.pad` to add columns or rows.
Comment: The zero fill makes some sense when expanding a 1d array.  Or adding new rows.  But if you change the number of columns data will be shifted. The new zeros always appear at the end - in a flattened sense.
Answer: # this example was taken from ndarray.resize doc
b = np.array([[0, 1], [2, 3]])
b.resize(2, 3) # new_shape parameter doesn't have to be a tuple
print(b)
#array([[0, 1, 2],
#       [3, 0, 0]])

The new array is filled with zeros, but the data changes aswell. The new array contains the original data, but in a row-wise manner.
Simple workaround:
def add_node(self, node):
    if node >= len(self.nodes):
        original_len = len(self.nodes)
        if original_len == 0:     # when array empty, assuming square matrix
            self.nodes = np.zeros((node, node))
        else:     # this adds zeros according to missing rows and cols
            to_be_added = node - len(self.nodes) + 1
            self.nodes = np.hstack((self.nodes, np.zeros((original_len, to_be_added))))
            self.nodes = np.vstack((self.nodes, np.zeros((to_be_added, original_len+to_be_added))))

Comment: Yea, I have a similar workaround, which works, though not ideal. My question is why do I see the behavior
Comment: Emmm, that's literally what I put in the question as well... Not sure what you are trying to say. Elaborate?
Comment: yup, noticed that, sorry... this is how the ndarray works, which is not ussable for your application
b = np.array([[0, 1], [2, 3]])
b.resize(2, 3) # new_shape parameter doesn't have to be a tuple
b
# array([[0, 1, 2],
#       [3, 0, 0]])
Comment: according to doc: https://numpy.org/doc/stable/reference/generated/numpy.ndarray.resize.html
3rd example
Comment: I edited the post... hope I was able to describe how the ndarray.resize works
Answer: You have an array, e.g. 2×2 matrix
1 2
3 4

You expected — after resizing it to 3×3 — that the original matrix will remain the same and zeroes will fill positions to the right and down of it, i.e. you expected as a result the matrix
1 2 0
3 4 0
0 0 0

But it is not the case. NumPy keeps its arrays in memory as a continuous sequence of elements (a vector), and info about its shape as a meta info.
It means that the original 2×2 matrix keeps in memory as
1 2 3 4

and after resizing it fill it by zeroes (or by repeating it in the case of using the ndarray method instead of a NumPy function) after the last position of its memory representation
1 2 3 4 0 0 0 0 0

Then show it (and works with it by index calculations) as
1 2 3
4 0 0
0 0 0

How to correct your method add_node():

First approach — create a new, zero-filled matrix, and then place the original one to the left upper corner of it:
def add_node(self, node):
  if node >= len(self.nodes):
    rows, cols = self.nodes.shape
    temp = np.zeros((node+1, node+1), dtype=int)
    temp[:rows, :cols] = self.nodes
    self.nodes = temp

Second approach — use the NumPy's pad() function — you may control, where you want to pad and how many rows / columns*):
def add_node(self, node):
  if node >= len(self.nodes):
  to_add = node + 1 - len(self.nodes)
  self.nodes = np.pad(self.nodes, ((0, to_add), (0, to_add)))

The explanation:
For 2-dimensional array one form of np.pad() is
np.pad(array, ((before_top, after_bottom), (before_left, after_right)))

e.g after the a = np.pad(a, ((2, 4), (0, 3))) command
                           0, 0, 0, 0, 0
                           0, 0, 0, 0, 0
            1 2   will     1, 2, 0, 0, 0
            3 4   become   3, 4, 0, 0, 0
                           0, 0, 0, 0, 0
                           0, 0, 0, 0, 0
                           0, 0, 0, 0, 0
                           0, 0, 0, 0, 0

*) Thanks to hpaulj's comment.
Comment: No need to remove pad elements, just use `np.pad(a,((0,1),(0,1)))` to fully control what's added on all 4 sides.
Comment: @RafazZ, you're welcome. Please see my simplified 2nd approach in my edited answer  thanks to [hpaulj](https://stackoverflow.com/users/901925/hpaulj)'s comment.

NumPy `a.resize` adds non-zero values


How can I programmatically deactivate multiple user accounts?

Question: I have tried the following code, but something doesn't work, could you please help. I need to deactivate several accounts at once, if they satisfy the conditions:
$ids = \Drupal::entityQuery('user')
  ->condition('roles', 'student')
  ->condition('field_school_id', $node_id)
  ->execute();
$users = User::loadMultiple($ids);

$storage_handler = \Drupal::entityTypeManager()->getStorage("user");

foreach($users as $user){
  $entity = $storage_handler->load($user->id());
  $entity->set("status", 0);
  $storage_handler->save($entity); // THE PROBLEM IS IN THIS LINE
}

Answer: The problem is that you load the users two times. In the foreach loop you already have the loaded entity available in $user.
Change your foreach loop to look like this and it should work:
foreach ($users as $user) {
  $user->set("status", 0);
  $user->save();
}

You can also remove the $storageHandler since you don't use that any more.


Calculate correlation for discrete-like values from two columns of DataFrame in Pandas

Question: Here's the code snippet:
df = pd.DataFrame(data=[1,1,2,2,3,3,3], columns =list('A'))

def m(x):
    if x == 1:
        return 2
    if x == 2:
        return 3
    if x == 3:
        return 1
    return -1
df['B'] = df['A'].map(m)
print df.head(n=10)

   A  B
0  1  2
1  1  2
2  2  3
3  2  3
4  3  1
5  3  1
6  3  1

As we can see, column B is created by mapping value from column A, thus they should have correlation of value 1, but what I got from below is all not satisfying. Could anyone give me some idea on how to calculate correlation of discrete data for two columns? Great thanks!
df['A'].cov(df['B'])
-0.47619047619047611
df['A'].corr(df['B'], method='spearman')
-0.68000000000000016
df['A'].corr(df['B'], method='kendall')
-0.50000000000000011
df['A'].corr(df['B'])
-0.58823529411764708

Comment: The question doesn't appear to be about statistics unless you read it. As you can see in the answer - fortunately posted before closing - the problem is about statistical misunderstanding, not about coding. It should be reopened.
Answer: There is nothing wrong in your calculation. However, your mapping is not linear and therefore correlation between your variables is not 1 nor -1.
I suggest trying mapping 3 to 4 instead of 1 and compute correlation again. Then you should get correlation = 1.
For a different test, mapping 1 to 3, 2 to 2 and 3 to 1 should produce correlation = -1.
And please notice that correlation is just a measure on how much the variables are linearly related. If they are related by a deterministic mapping but that mapping is not linear, correlation will be low.
Comment: The point is that there's could be scenario with A->B, B->C and C->A, which I intend to dig out the correlation without having to change it manually since I can't see the correlation beforehand.
Comment: It's easy to prove that if  A->B, B->C and C->A is a linear relation, A=B=C. Or equivalently, if A->B, B->C and C->A correlation is not 1 nor -1. If you just want to compute the correlation, you already know how to do it with Pandas - you already did. Then, I don't see what is the problem.


Can't find BaseGameUtils under android-basic-samples-master. New alternatives?

Question: This might seem stupid, but I spend a long time trying to find BaseGameUtils library under android-basic-samples-master. From this download, I simply cant find anything about BaseGameUtils. I am a mac user and using Android Studio. Please help, thank you!
I just found out that in a commit on Nov 29, 2017, they removed BaseGameUtils from this download. What are we using right now?
Comment: How do you know you need it?
Comment: I am using it for sign in button for google. It comes from a tutorial.
Comment: could you provide a link to the tutorial here, maybe the Utils class was created separately from the google samples code
Comment: Here is the link https://code.tutsplus.com/tutorials/google-play-game-services-leaderboards--cms-20700
Comment: It's under Prepare Your IDE, under step 4
Comment: that's an old tutorial, so they might have removed it from the sample, but it was forked here: https://github.com/grantland/android-samples/tree/master/BaseGameUtils
Comment: If I am adding BaseGameUtils for my game, do I add the jar under lib under BaseGameUtils? And I am adding it as a jar dependency right?
Comment: That's right, as explained in step 5
Answer: I just looked at the current example and take things from it!


Proving that $T$ is self-adjoint (or that $A,B$ are vertical to each other)

Question: I'm facing the following problem:
Let $X$ be a Hilbert space, $A,B$ be subspaces of $X$ such that $X=A\oplus B$ and $T\in B(X)$ such that $T\vert_A=\text{Id}_A$, $T\vert_B=-\text{Id}_B$. Prove that $T=T^{-1}$ and that $T^*=T$.
The first statement is easy; indeed, if $x=a+b$, then $Tx=a-b$, therefore $TTx=a+b=x$, thus $TT=\text{Id}_X$ and we are done.
But I really can't move on with the second statement. I proved that $T^*=T$ if and only if $A\bot B$:
Indeed, if $T^*=T$, then $<Tx,y>=<x,T^*y>=<x,Ty>$ for all $x,y$, which yields $<Tx-x,y+Ty>=0$. If $a,b\in A,B$ respectively, then for $x=b, y=a$ we have that $<a,b>=0$.
The converse is obvious by taking random $x,y$ and writing them in the form $a+b$ where $a\in A, b\in B$. But I can't prove that $A\bot B$. I tried taking the closure of $A$ and writing $X$ as $X=\overline{A}\oplus\overline{A}^{\bot}$ ,and, since $\overline{A}^\bot=A^\bot$, $X=\overline{A}\oplus A^{\bot}$ but I couldn't move on. Any ideas?
Comment: @daw $A\bot B \implies T=T^*$ is obvious as i say. So, by proving this equivalence, i prove that the problem "prove that $T=T^*$" is the same as "prove that $A\bot B$". Please reread my question and comment and revise.
Comment: I do not understand your question. In the third paragraph, you  prove indeed that $T=T^*$ implies $A\perp B$.
Comment: @daw I want to prove that $T=T^*$. My only progress was that $T=T^*\iff A\bot B$. The third paragraph is this proof, but I can't prove that $A\bot B$.
Comment: The part between 'Indeed' and $\langle a,b\rangle=0$ IS the proof of $T=T^*$ $\Rightarrow$ $A\perp B$. Please reread your question and comment and revise.
Answer: Your problem in understanding here might be that "verticality" of $A$ and $B$ are due to the definition of the direct sum of Hilbert spaces.
For arbitrary Hilbert spaces $(A,\langle\cdot,\cdot\rangle_A)$, $(B,\langle\cdot,\cdot\rangle_B)$, one defines the direct sum as ordered pairs of the form
$$
A\oplus B=\lbrace (a,b)\,|\,a\in A,b\in B\rbrace
$$
which turns into a vector space with componentwise addition and scalar multiplication. Then $A\oplus B$ becomes a Hilbert space under the scalar product
$$
\big\langle (a_1,b_1),(a_2,b_2)\big\rangle_{A\oplus B}:=\langle a_1,a_2\rangle_A+\langle b_1,b_2\rangle_B\,.\tag{1}
$$
Now it is customary to write these elements of not as ordered pairs $(a,b)$, but as a sum $a+b$ (by identifying $A$ with $A\times\lbrace 0\rbrace\subset A\otimes B$ and same with $B$). With this identification, every $x\in A\oplus B$ can be uniquely expressed as $x=a+b$ for some $a\in A$, $b\in B$. So in some sense it is by definition that
$$
\langle x,Ty\rangle=\big\langle a_1+b_1,(\operatorname{Id}_Aa_2-\operatorname{Id}_Bb_2)\big\rangle=\langle a_1+b_1,a_2-b_2\rangle\overset{(1)}=\langle a_1,a_2\rangle-\langle b_1,b_2\rangle=\ldots= \langle Tx,y\rangle\,,
$$
because $A\oplus B$ by definition (1) / construction / assumption are "orthogonal".
Comment: Thank you for your answer
Answer: Your arguments are all correct and You have to assume $A\oplus B$ really means the orthogonal sum. If it is not orthogonal by construction as in Frederiks answer and You take the definition $A\oplus B=\{a+b:a\in A,b\in B\}$ where $A\cap B=\{0\}$ then You get simple counterexamples like the finite-dimensional $X=\mathbb{R}^2=\langle\begin{pmatrix}1\\1\end{pmatrix}\rangle\oplus\langle\begin{pmatrix}0\\1\end{pmatrix}\rangle$ and $T(\begin{pmatrix}1\\1\end{pmatrix})=\begin{pmatrix}1\\1\end{pmatrix}$ and $T(\begin{pmatrix}0\\1\end{pmatrix})=-\begin{pmatrix}0\\1\end{pmatrix}$. Then $T$ is a bounded operator that fulfills $T_{|A}=Id_A$ for $A=\langle\begin{pmatrix}1\\1\end{pmatrix}\rangle$ and $T_{|B}=-Id_B$ for $B=\langle\begin{pmatrix}0\\1\end{pmatrix}\rangle$ but is not self-adjoint, what You proved and can check by finding its matrix to an orthogonal basis (e.g. to the standard basis, this yields $\begin{pmatrix}1&0\\2&-1\end{pmatrix}$)
Comment: @PeterMelech Thank you,the counter-examples were helpful indeed.
Comment: That is a nice counterexample to hopefully further clear up OP's misconception!
Comment: Thanks! Hopefully it is not even confusing, $\langle .,.\rangle _2\neq \langle .,. \rangle _{A\oplus B}$ if $A\not\perp B$ with respect to $\langle .,.\rangle _2$.


How can i create a multithread in C for windows?

Question: I dont know how can I make threads in C, i saw a review about pthread.h library but then i heard that its only for Linux OS, i have a function that its a timer, i want to created a thread with that function but i dont know either the library i need to use and syntax's to write the code, if someone could provide me a simple code with threads, or tell me what things i need to put and the parameter of the functions.
Here its the function i create that countdown the specific time the user apply:
i need to make a thread with that function.
Function (Countdown):
#include <stdio.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>

void countdown(int second)
{
    int secs = 1;
    time_t unix;
    struct tm * timeinfo;
    time(&unix);
    timeinfo = localtime(&unix);
    int t1 = timeinfo->tm_sec;
    int t2 = timeinfo->tm_sec;
    int i = 0;

    while(1 == 1)
    {
       time(&unix);
       timeinfo = localtime(&unix);
       if((t1 + i)  == timeinfo->tm_sec)
       {
              system("cls");
              printf("Time left %d\n", timeinfo->tm_sec - t2 - second);
              i++;
       }
       if(timeinfo->tm_sec >= (t1 + second))
       {
           system("cls");
           puts("Your time its done");
           break;
       }

    }
}

int main()
{
    int limit;
    printf("How much time would you like (In secs): ");
    scanf("%d", &limit);
    countdown(limit);

    system("PAUSE");
    return 0;
}

Comment: Hi. You could use CreateThread from win32 api
Comment: You don't need to create threads to use a [timer](https://learn.microsoft.com/en-us/windows/win32/winmsg/timers).
Answer: Here is a simple guide to WinAPI threads:
http://www.cs.rpi.edu/academics/courses/netprog/WindowsThreads.html (Archived)
That being said, C is a minimalistic language, does not have built-in threading like Java (nor the enormous extra libraries). It was meant as a general language to build on top of it.
On Unix-like systems, there are system-wide standard C libraries beyond the ANSI/ISO standard, which are part of the POSIX standard, the pthreads are POSIX-threads.
Windows C libraries are MS makes things their own way. You can use frameworks that provide multi-OS support like GLib or Qt (Windows, Linux, other *nix). There are also ports and compatibility layers to use POSIX facilities inside windows. Cigwin gives you a full POSIX environment besides the libraries, The MinGW compiler allows you to use ports of POSIX functions on top of Win32 layers.
Frameworks like GLib and Qt are best to keep your code multi-platform, they hide the OS specifics, allowing a more general approach.
GLib is part of the GTK libraries for GUI development, and Qt is also a GUI development framework but in C++.
Comment: Your link is broken.
Comment: @Thor-x86_128 the [edit] link does work, but you need full editing privilege (at 2k rep) for your edit to be applied immediately; so for now it will be added to the suggested edits queue. I've approved your edit and improved it. See more about editing here: https://stackoverflow.com/help/privileges/edit. Thanks for contributing!
Comment: The "edit" button for this answer is not working. Here's the working link: https://web.archive.org/web/20121023005749/http://www.cs.rpi.edu/academics/courses/netprog/WindowsThreads.html
Answer: The tags suggest you're using Windows. The Win32 api has a CreateThread function that can be used to launch a new thread. However, when you're using the C runtime (which you are) then you should use the _beginthread function by including process.h.
The reason to use _beginthread is that it initializes thread specific state information that the C runtime requires to execute correctly within a thread.
Answer: If you're familiar with pthreads and/or want a cross-platform codebase, you can use MinGW and pthreads-win32.  I've recently used it in an application of mine and it seems to work great.  If you're developing exclusively for Windows, its probably worth your time to learn the WinAPI threading stuff as redcomet suggested.
Answer: The C standard library does not have the thread concept. A thread is usually a concept in OS. You can use win32api to handle threads just like you use pthread in linux(not so equal actually..)
To know more about win32api, please go to the MSDN.
How to create thread with win32api:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms682516(v=vs.85).aspx
Answer: Here is a sample program for the Single Threading and Multi-threading for Win32API written in C.
SingleThread_Win.c
#include <stdio.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>

#include<Windows.h>

void countdown(int second)
{
    int secs = 1;
    time_t unix;
    .....
    .....
}

DWORD WINAPI funThread(void *x)
{
    int c = (int*)x;
    countdown(c);
    return 0;
}

int main()
{
    int limit;
    printf("How much time would you like (In secs): ");
    scanf("%d", &limit);

    HANDLE  myhandle;
    DWORD threadId;
    myhandle = CreateThread(NULL, 0, funThread, (void *)limit, 0, &threadId);
    if (myhandle == NULL)
    {
        printf("Create Thread Failed. Error no: %d\n", GetLastError);
    }
    WaitForSingleObject(myhandle, INFINITE);
    CloseHandle(myhandle);

    system("PAUSE");
    return 0;
}

MultiThreading_Win.c
#include <stdio.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#define NUM_THREADS 5    // Define number of threads here or take as user input
#include<Windows.h>

void countdown(int second)
{
    int secs = 1;
    time_t unix;
    .....
    .....
}

DWORD WINAPI funThread(void *x)
{
    int c = (int*)x;
    countdown(c);
    return 0;
}

int main()
{
   int limit;
   printf("How much time would you like (In secs): ");
   scanf("%d", &limit);
   //scanf("%d", &NUM_THREADS);    //Take number of threads as Input

   HANDLE *arrayThread;
   arrayThread = (int*)malloc(NUM_THREADS * sizeof(int));
   DWORD ThreadId;

   for (int i = 0; i < NUM_THREADS; i++)
   {
       arrayThread[i] = CreateThread(NULL, 0, funThread, (void *)limit, 0, &ThreadId);
       if (arrayThread[i] == NULL)
       {
           printf("Create Thread %d get failed. Error no: %d", i, GetLastError);
       }
   }

  WaitForMultipleObjects(NUM_THREADS, arrayThread,TRUE,INFINITE);
  DWORD lpExitCode;
  BOOL result;

  for (int i = 0; i < NUM_THREADS; i++)
  {
    CloseHandle(arrayThread[i]);
  }

  system("PAUSE");
  return 0;
}


jQuery Tab Menu Set Active Menu and load the content

Question: I have jQuery tab menu call ajax.
Menu is working perfect, but now I want when page loaded it always show the first tab to be loaded (means active).
You can see the fiddle here: https://jsfiddle.net/waspinator/rw8ujfg3/

 Contacts

 Friends list

Awaiting request

JS
$('[data-toggle="tabajax"]').click(function(e) {
var $this = $(this),
    loadurl = $this.attr('href'),
    targ = $this.attr('data-target');

$.get(loadurl, function(data) {
    $(targ).html(data);
});

$this.tab('show');
return false;
});

In this case, I want Contact content loaded on page loaded. How can set this?
Answer: This should work. Just abstract the function, and bind it to the event, but also call it on load with the first tab selected to call it on. (EDIT: Sorry I got the spacing on your function wrong before because I mis-copied it. Also, tested it and changed a few things to work out a kink or two.)
function doAjaxStuff(event, tab) {
  var $this = tab || $(this)
    var $this = tab || $(this),
        loadurl = $this.attr('href'),
        targ = $this.attr('data-target');

    $.get(loadurl, function(data) {
        $(targ).html(data);
    });

    $this.tab('show');
    return false;
}

doAjaxStuff(null, $('.nav-tabs li:first-child a'))

$('[data-toggle="tabajax"]').click(doAjaxStuff);

Comment: Not working, can you please try to update in the fiddle?
Comment: I copied this straight from the fiddle just now. Copy/paste and it should work! : ) (also updated the fiddle).
Answer: $('#contacts_tab').trigger('click'); if you are allowed to use the id.


Basic AutoLisp Variable, Function Passthrough

Question: Okay, I seem to be having trouble passing a simple variable through to another variable in a function. I don't see what I'm doing wrong here. Why is passing the variable with a string converted to nil, but passing the raw strings remain unchanged?
;; Main Procedure
(defun C:Debug01(/ dirPath sResult)

    ;; Pulls and shows directory of current file
    (setq dirPath (getvar 'dwgprefix))
    (princ (strcat "\n \n" dirPath "\n \n"))

    ;; Basic Function
    (setq sResult (fcnBasic "Message 1" dirfile "Message 3" "Title"))
    (princ (strcat " \nResulting output : " sResult "\n "))
    (princ)
)

;; A Basic Function
(defun fcnBasic (message1 message2 message3 main / sReturn)

    ;; Displaying values
    (princ (type message1)) (princ (strcat " : " message1 "\n"))
    (princ (type message2)) (princ (strcat " : " message2 "\n")) ;; Message 2 should equal "C:\Users\Garrettb\Documents" with a type of STR.
    (princ (type message3)) (princ (strcat " : " message3 "\n"))
    (princ (type main))     (princ (strcat " : " main "\n"))

    ;; Returning a value
    (setq sReturn message2)
    (return sReturn)
)

Answer: In line:
(setq sResult (fcnBasic "Message 1" dirfile "Message 3" "Title"))

You pass variable dirfile  which is not initialized in function C:Debug01. Maye somewhere is, I don't know.
You set value of variable dirPath which is not the same as dirfile ;)
Comment: Thank you. `Dirfile` should have been `dirPath`. I don't know how many times I reviewed the code and missed it.


Jazz Piano Diminished/Tritone Sub Exercise

Question: I need a little help understanding what a particular exercise is trying to teach me. For reference, this is in the Phil DeGreg Jazz Keyboard Harmony book, exercise 2-4A. It's labeled 'Diminished / Tri-tone Sub'.
The first line has the guide tone chords listed for CM7, C#dim7, Dm7, D#dim7, Em7, Eb7, Dm7, Db7, CM7.
While I can see that some of these chords are intended to be diminished substitutions, what are they substituting for?
Answer: They are substituting for secondary dominants of the next chord in the progression. The C♯°7 substituting for A7 which is the dominant of D and the D♯°7 substituting for B7 which is the dominant of E. The only diffrence between the diminished 7th chords and the secondary dominants is only one note which is only a half step difference so there is a lot of common ground between the chords being the A and the B♭ in the A7 vs. C♯°7 and the B and the C in the B7 vs. D♯°7.
The tritone subs are also substitutions for the dominants of the next chords in the progressions, however they resolve in an opposite way of typical dominants. So for example the D♭7 to CMaj7 is a substitution for G7 to CMaj7 and the resolutions follow similar patterns like so:

D♭7    CMaj7     G7
D♭ -->   C   <-- D
F  -->   E   <-- F
A♭ -->   G   <-- G
C♭ -->   B   <-- B


Prob. 2, Sec. 1.4 in Kreyszig's Functional Analysis Book: Any Cauchy sequence with a convergent subsequence converges

Question: Here is Prob. 2, Sec. 1.4 in the book Introductory Functional Analysis With Applications by Erwine Kreyszig.

If $\left( x_n \right)$ is Cauchy and has a convergent subsequence, say, $x_{n_k} \to x$, show that $\left( x_n \right)$ is convergent with the limit $x$.

My effort:

Let $(X, d)$ be the metric space in which $\left( x_n \right)$ is a Cauchy sequence, and let $\varphi \colon \mathbb{N} \to \mathbb{N}$ be a strictly increasing function such that the sequence
  $\left( x_{\varphi(n)} \right)$ converges to a point $x$ of $X$. And, we can put $$n_k = \varphi(k) \ \mbox{ for all } k \in \mathbb{N}.$$
Then, given a real number $\varepsilon > 0$, we can find a natural number $N$ such that $$ (1) \ \ \ \  d \left( x_m, x_n \right) < \frac{\varepsilon}{2} \ \mbox{ for any pair } (m, n) \mbox{ of natural numbers such that } m > N \mbox{ and } n > N.$$
Now for each $k \in \mathbb{N}$, we know that $n_k = \varphi(k) \in \mathbb{N}$; moreover, $$ n_k = \varphi(k) < \varphi(r) = n_r \ \mbox{ if $k \in \mathbb{N}$, $r \in \mathbb{N}$, and $k < r$},$$ because $\varphi$ is a strictly increasing function.
Thus, $n_1 = \varphi(1) \in \mathbb{N}$ and so  $n_1 \geq 1$. Let $k$ be any natural number, and suppose that $$n_k = \varphi(k) \geq k.$$ Then since $\varphi$ is a strictly increasing function and since $k+1 \in \mathbb{N}$, therefore we can conclude that
  $$n_{k+1} = \varphi(k+1) > \varphi(k) \geq k.$$
  But $\varphi(k+1) \in \mathbb{N}$. So we can conclude that $\varphi(k+1) \geq k+1$. Hence by induction it follows that $$n_k = \varphi(k) \geq k \mbox{ for all } k \in \mathbb{N}. $$
Thus we know that, for each $k \in \mathbb{N}$, (i) $\varphi(k) \in \mathbb{N}$ and (ii) $\varphi(k) \geq k$.
Now since $$\lim_{k \to \infty} x_{\varphi(k)} = \lim_{k \to \infty} x_{n_k} = x, $$
  therefore we can find a natural number $K$ such that $$ (2) \ \ \ \ d\left( x_{n_k}, x \right) = d\left( x_{\varphi(k)}, x \right) < \frac{\varepsilon}{2} \ \mbox{ for any natural number } k \mbox{ such that } k > K.$$
Now let $M$ be any natural number such that $M > \max \left( K, N \right)$. Such an $M$ exists since the set of natural numbers is not bounded above (or by the Archimedian property of $\mathbb{R}$).
Let $n \in \mathbb{N}$ such that $n > M$. Then we note that
  $$n_{M+1} = \varphi(M+1) \geq M+1 > M > K$$ so that (2) can be used, and we also note that $$n_{M+1} \in \mathbb{N}, \ \ \ n \in \mathbb{N},  \ \ \ n_{M+1} > M > N, \ \ \ \mbox{ and } \ n > N$$
  so that (1) can be used.
Then, from (1) and (2) above, we see that,
  $$ d\left( x_n, x\right) \leq d \left( x_n, x_{n_{M+1}} \right) + d \left( x_{n_{M+1}}, x \right) < \frac{\varepsilon}{2} + \frac{\varepsilon}{2} = \varepsilon,$$
  for any natural number $n > M$.
Thus we have shown that, corresponding to  every real number $\varepsilon > 0$, we can find a natural number $M$ such that $$ d \left( x_n, x \right) < \varepsilon \ \mbox{ for any natural number } n > N.$$
  Hence the sequence  $\left(x_n \right)$ converges in the metric space $(X, d)$ to the point $x \in X$.

Is the above proof correct? If so, then is the presentation good enough? If not, then where lies the flaw?
Comment: Here's my attempt at a proof.  Let $\epsilon > 0$.  Because $(x_n)$ is a Cauchy sequence, there exists a positive integer $N$ such that if $i,j > N$ then $d(x_i,x_j) < \epsilon/2$.  Because $(x_n)$ has a subsequence that converges to $x$, there exists an integer $k > N$ such that $d(x_k,x) < \epsilon/2$.  It follows that if $m > N$, then $d(x_m,x) \leq d(x_m,x_k) + d(x_k,x) < \epsilon/2 + \epsilon/2 = \epsilon$.  This shows that $(x_n)$ converges to $x$.
Comment: Related: https://math.stackexchange.com/questions/354965/
Comment: looks excellent! (+1)
Comment: I don't think you need to explain all that about $n_k\ge k$ thing in such a detail, unless it's the first time you encounter concept of subsequence;
Answer: The above proof is correct, but there's a lot of parts that can be trimmed. For one, you don't really need to introduce the function $\phi$ at all. It just introduces confusion, and you can always write $n_k$ instead of $\phi(k)$ and lose no clarity.

So, a trimmed down proof:
Let $(x_n)_{n\in\mathbb N}$ be a Cauchy sequence, and let $(x_{n_k})_{k\in\mathbb N}$ be a convergent subsequence of it. Also, let $x=\lim_{k\to\infty} x_{n_k}$.
Let $\epsilon > 0$.
Then,

there exists some $N$ such that if $m,n\ge N$, we have $d(x_n, x_m)<\frac{\epsilon}{2}$.
there exists some $K$ such that if $k\ge K$, we have $d(x, x_{n_k})<\frac\epsilon2$.

Set $N'$ to be the first value of the sequence $(n_K, n_{K+1},\dots)$ that is greater than $N$, and let $n>N'$.

From point (2), we know that $d(x, x_{N'})<\frac\epsilon 2$
From point (1), we know that $d(x_{N'}, x_n)\leq \frac\epsilon 2$ (because $N'>N$ and $n>N$.

Then, $$d(x, x_n) \leq d(x, x_{N'}) + d(x_{N'}, x_n) < \frac\epsilon 2 + \frac\epsilon2=\epsilon$$ and the proof is over.


Reducing Neck Pickup Dissonance

Question: A common problem with single-coil pickups is severe dissonance in the neck position, known by a few names like Stratitis. I know it can be reduced by properly adjusting the pickup height in relation to the strings, but are there any other significant factors in play, like pickup construction or the setup of the instrument?
FWIW, I ask because I have a Telecaster with a very finicky neck pickup- it's stock, but I did remove the cover. If I play anything more complex than single notes or major chords, especially with overdrive or distortion, I'll get this awful discordant sound, even after I've carefully adjusted the height. I don't have this problem with the bridge pickup, and it's not easily noticeable when the pickups are in parallel.
Answer: Nobody so far has actually discussed stratitis yet. Well, it probably isn't the issue!
Before I say why, another thing: pickup damage is almost certainly not the issue either. Symptoms of pickup damage are:

Dull sound due to resonance damping by shortcuts between windings. Happens when the isolation is faulty.
Loud thudding sound when you touch the pickup, or feedback even while you're holding all the strings. These problems are caused if some windings aren't properly held in place by the wax cast, or if magnets are loose.
Uneven level between the strings. caused by aged or broken (or wrongly oriented!) magnets.
In the extremest, simply no sound or extremely quiet sound, or dropouts – caused if the wire's broken somewhere in the winding.

None of these effects can really cause "discordant" sound.
As for stratitis. That is the effect of strong magnets exerting significant mechanical pull on the strings. This is a very nonlinear effect, and disturbs the strings' harmonic vibration. The overtones then come out not as exact multiples of the fundamental frequency, but slightly (and quite unpredictably) off. Hence, it causes inharmonicity.
Now, since the magnets are permant magnets (they aren't turned off by the pickup switch), you can't really say "stratitis affects only a single pickup". It may be caused by only a single pickup, but it affects the entire guitar, even when it's not plugged in at all. So if you only notice the problem when using the neck pickup, it's probably not stratitis.
At least not stratitis alone, that is. Some degree of inharmonicity by itself isn't necessarily bad: a similar effect (caused not by magnets but string stiffness) is actually quite important for the characteristic sound of upright pianos, as well as the plucked strings of violins, cellos or jazz guitars. It can however become nasty when particularly affected frequencies are boosted too much. Perhaps that's the issue with your neck pickup. So one thing you should try (apart, of course, from adjusting the pickup height) is to change the pickup's resonance frequency. This can easily be done by wiring a small capacitor (try 3.3 nF) parallel to the pickup. Perhaps this solves the problem (regardless if it's caused by stratitis, or e.g. some nasty resonance of the neck).
Answer: Hmm sounds like possibly you could have a bad pickup? I've had some guitars have great sounding positions, and just one bad one. Usually it was always down to just the pickup itself. I have to ask how old is your Tele? Vintage or new? Also do you happen to know if your pickup pole pieces are Alnico or Ceramic? This can also help to know what could be going on.
If your pickups are Alnico, they could be losing their magnetism and you're experiencing issues in your tone when you're on just the neck pup. I had one guitar I remember, a strat, with the same kind of issues you're talking about. I tried the capo trick too and that wasn't the issue at all. It was an old strat 70s, the pickups had been swapped out before form the previous owner. He said the neck and middle pups were off a 60s issue strat and Alnico, and the bridge was a newer ceramic generic pup he pulled out of a different Japan copy strat.
The bridge has the best loudest tone on it being ceramic pole pieces. The neck and middle on the alnico pole piece pups sounded like crud. I found I'd have to turn my volume up which only made it sound even worse and broken up in spaces. And mind you the pup heights were set at a reasonable low height so the strings weren't being pulled down by the pickups. The simple fact was that those old 60s alnico pickups, had lost their strength.
I got a neck and middle pickup out of a MIM Fender strat I had laying around, the middle pup was also reverse wound so that was a nice upgrade for this strat. The problem however was completely solved! No more Stratitis! The new neck and middle pickup also being Ceramic, had the best tone and I or whoever else owns it later, will never have to worry about those old alnico pickups losing their magnetism. They really should of switched over to just ceramic pole pieces but people love the sound of old dying pickups.
If you can't find a solution on your own, if you can get a hold of a new pickup for neck, try installing it and see if your issue is gone. It might just be a weak pickup on its last leg. Even the newer guitars that are built with Alnico pole pieces will go bad over time quick. Especially those who lay their guitars against their amps lol Those magnets on those speakers are killing your Alnico pole pieces in a matter of time. I know some dudes who leave their guitars like that cause they think it looks cool like they're always ready to play. But they're always complaining their guitars just don't sound right anymore lol
Good luck with it, hope you can solve the issue and get it back to playing.
Comment: It's new, 2009, made in Mexico. The pickup itself sounds quite good, I think, and it's actually noticeably louder than the bridge, but I suppose it could still be damaged. I might try and find something cheap on Ebay, see if that helps.
Comment: If it sounds good to you then, you might not have to replace it. Since you say it sounds noticeably louder than the bridge, maybe the neck is up too high than the rest of the pickups and its giving the thrown off sound. You could try lowering it a little and see how it sounds in relation to the rest of the pickups. If it sounds like perfect, the pickup maybe a hot wound and its just too close to the strings in height. A little lowering could even it all out. However if doing all that still doesn't fix it, if you can live with it I'd say just keep it, instead of getting a new one.
Comment: Stratitis is a particular problem caused by _too strong_ (and/or too close) magnets. When Alnico pickups loose their power, they loose sound too of course, but this doesn't cause dissonance and has nothing to do with stratitis.
Answer: Would it be accurate to describe your problem as an oscillation sound especially noticeable when using distortion? Making even one string sound out of tune with itself and making it very difficult to intonate the guitar? If that is accurate, lower your neck pickup in a go no go manner until the oscillation is gone. The magnetic field of the pick-up is dragging on the strings, not allowing them to move as they should
Answer: Suggestion - try testing the guitar with a capo on the first fret.  If the problem goes away, then I suggest the problem is just a badly cut nut or poor break angle.
Comment: No such luck, I tried this some time ago and it didn't help whatsoever. I also tried adjusting the pickup with a capo at the twelfth fret, trying to get a clearer sound (fewer harmonics?) and that helped a little bit.

Reducing Neck Pickup Dissonance


MenuItemDefinition property "requiredPermissionName" is missing from 5.2.0 release (and pre-release)

Question: There seems to be a breaking change in the latest release (5.2.0)
To replicate:

download the latest stable template for mvc core
Update all nuget packages to latest stable

The property requiredPermissionName is no longer available
Any steps to overcome would be appreciated...
Sample Code from Template (.net core MVC)
public class GpNavigationProvider : NavigationProvider
{
    public override void SetNavigation(INavigationProviderContext context)
    {
        context.Manager.MainMenu
            .AddItem(
                new MenuItemDefinition(
                    PageNames.Home,
                    L("HomePage"),
                    url: "",
                    icon: "home",
                    requiresAuthentication: true
                )
            ).AddItem(
                new MenuItemDefinition(
                    PageNames.Tenants,
                    L("Tenants"),
                    url: "Tenants",
                    icon: "business",
                    requiredPermissionName: PermissionNames.Pages_Tenants
                )

Compile Error:

Severity   Code    Description Project File    Line    Suppression State
  Error   CS1739
  The best overload for 'MenuItemDefinition' does not have a parameter named 'requiredPermissionName'
  ...\5.1.1\aspnet-core\src\Gp.Web.Mvc\Startup\GpNavigationProvider.cs   29  Active
Comment: also tried against pre-release version of template...
Answer: The change is straightforward:
// requiredPermissionName: PermissionNames.Pages_Tenants,
permissionDependency: new SimplePermissionDependency(PermissionNames.Pages_Tenants),

requiredPermissionName was deprecated in version 2.2 in July 2017.
It was removed in version 5.2 that was released yesterday, after 3 major versions and more than 2.5 years.
References:

aspnetboilerplate/aspnetboilerplate#2289 (ABP 2.2)
aspnetboilerplate/aspnetboilerplate#5191 (ABP 5.2)
Comment: The template(s) will be updated: [aspnetboilerplate/aspnetboilerplate#5306 (comment 588239620)](https://github.com/aspnetboilerplate/aspnetboilerplate/issues/5306#issuecomment-588239620)


Using specific types based on typeof inside generic function

Question: I want to have a generic function for a few types such as long, TimeSpan and DateTime.
public static T Parse<T>(string text)
{
    T store;

    if(typeof(T) == typeof(TimeSpan)
        store = (T)((object) new TimeSpan(0, 1, 0));
    else
    {
        T.tryParse(text, out store);
    }
    return store;
}

Is there a better way than the double T/object cast?
The t.tryParse does not compile, how can I accomplish something similar?
Comment: What is the compilation error?
Answer: It feels to me like it would be better to have an overloaded method in this case. There's nothing really generic about calling TryParse - Int32.TryParse is an entirely different method from Int64.TryParse etc. That will get you away from the double cast, too (which I agree is ugly, but unfortunately hard to avoid). It also means you'd be specifying which types you can genuinely support.
One alternative is to use a Dictionary<Type, Func<string, object>>:
// Add some error checking, obviously :)
Func<string, object> parser = parsers[typeof(T)];
return (T) parser(form.Text);

then set up the dictionary with something like:
static readonly Dictionary<Type, Func<string, object>> parsers =
    new Dictionary<Type, Func<string, object>>()
{
    { typeof(int), x => int.Parse(x) },
    { typeof(TimeSpan) x => new TimeSpan(0, 1, 0) },
    ...
}

If you want to use TryParse instead of Parse, you'll need to create your own delegate type due to the use of out parameters (which aren't supported in Func/Action). Life becomes a little harder at that point.
As an aside, why are you using an out parameter instead of a return value?
Comment: The out in the Parse function was to match the out in the TryParse call. My question only had an except of the real code that does return a bool that represent the outcome of TryParse.
I will shortly look into the answer, thanks.
Comment: Removed the out in response to your question to keep my question focused.


Symfony 2.6 logout back button (CakePHP)

Question: After trying a lot of different ways (success handler, cache directives, changing routes, overriding methods, etc.) I haven't been able to logout a user (using the FOSUserBundle) disabling her to see previous pages when pressing the back-button of the browser.
Is there a way to do it in Symfony 2.6?
In CakePHP this works perfectly in a Controller
public function logout() {

    session_destroy();
    $this->Auth->deny('*');
    $this->Auth->shutdown('*');
    $this->Session->setFlash('Logout succesful - no back button issue.');
    return $this->redirect($this->Auth->logout());

}

Answer: Add the following headers to the top of the page in your application:
 header("Cache-Control: no-cache, no-store, must-revalidate");
 header("Pragma: no-cache");
 header("Expires: 0");

Answer: You can redirect to logout page:
return $this->redirectToRoute('fos_user_security_logout');

Answer: You need to send no-cache directive to the browser
Try this solution https://stackoverflow.com/a/41566590/1154919


Extracting significance of gam smoothing terms

Question: I have a time course data to which I'd like to fit a gam and have easy interpretability, and by that I mean obtaining coefficient estimates for each of the splines.
These are my data:
df <- data.frame(y = c(0.15,0.17,0.07,0.17,0.01,0.15,0.18,0.04,-0.06,-0.08,0,0.03,-0.27,-0.93,0.04,0.12,0.08,0.15,0.04,0.15,0.03,0.09,0.11,0.13,-0.11,-0.32,-0.7,-0.78,0.07,0.04,0.06,0.12,-0.15,0.05,-0.08,0.14,-0.02,-0.14,-0.24,-0.32,-0.78,-0.81,-0.04,-0.25,-0.09,0.02,-0.13,-0.2,-0.04,0,0.02,-0.05,-0.19,-0.37,-0.57,-0.81),
                 log2.time = rep(c(-1, 0, 1, 1.58,2, 2.58, 3, 3.32, 3.58, 4.17, 4.58, 5.58, 6.17, 7.39),4))

I thought I'd use the mgcv R package, using this model:
fit <- mgcv::gam(y ~ s(log2.time), data = df, method = "REML")

Using summary(fit), I get:
> summary(fit)

Family: gaussian
Link function: identity

Formula:
y ~ s(log2.time)

Parametric coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept) -0.10893    0.01681  -6.479 3.65e-08 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Approximate significance of smooth terms:
               edf Ref.df     F p-value
s(log2.time) 4.101  5.036 46.36  <2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

R-sq.(adj) =  0.809   Deviance explained = 82.3%
-REML = -27.673  Scale est. = 0.015829  n = 56

So, overall the log2.time smoothing term is significantly different from zero. But as stated above I would like to obtain a coefficient for each of the splines, along with their standard errors and a measure of whether they are significantly different from zero.
Should I be using cubic splines for this purpose, with this model:
fit <- mgcv::gam(y ~ s(log2.time,bs='cr'), data = df, method = "REML")

And can the spline coefficient estimates be obtained as follows:
spline.coefs <- coef(fit)[-1]
spline.knots <- fit$smooth[[1]]$xp

for(s in 2:length(spline.knots)){
  spline.coefs[s-1] <- spline.coefs[s-1]/(spline.knots[s]-spline.knots[s-1])
}

And then would the coefficient standard errors be:
spline.coefs.se <- sqrt(diag(vcov(fit, unconditional  = TRUE)))[-1]

And finally, can p-values for the spline coefficient estimates be obtained?
Answer: The diagonal of the variance matrix of the model parameters contains the variances of all the coefficients. If you take the square root of the diagonal elements you'll get the standard errors of the intercept plus the spline coefficients:
> fit <- mgcv::gam(y ~ s(log2.time,k=3), data = df, method = "REML")
> vcov(fit)
                 (Intercept) s(log2.time).1 s(log2.time).2
(Intercept)     3.122736e-04  -1.059763e-18  -3.707237e-20
s(log2.time).1 -1.059763e-18   3.968441e-03   3.479426e-08
s(log2.time).2 -3.707237e-20   3.479426e-08   3.122736e-04
> sqrt(diag(vcov(fit)))
   (Intercept) s(log2.time).1 s(log2.time).2
    0.01767127     0.06299556     0.01767127

If you use vcov(fit, unconditional  = TRUE) you'll get a (Bayesian) covariance matrix adjusted for having estimated the smoothness parameter, $\lambda$. Without this, the uncertainty on the spline coefficients is too small as it assumes $\lambda$ is known.
The values shown by coef(fit) are the parameters for the two thin plate spline basis functions used in the model. They are not the slopes of the fitted spline itself however; the slope or first derivative of the spline is varying throughout the range of $x$. You can estimate the slope of the spline at any point using finite differences if you want that, and compute a confidence interval on that slope.
There is only one spline here, built up from two basis functions (well three depending on how you look at it, but one of those is the intercept). Your use of "spline" and "slope" are a little confusing — if you care to clarify I will update this answer should elements of it be irrelevant or lacking.
Note that your model was actually fitted using k = 3 and then the constant basis function was dropped, hence a maximum of 2 degrees of freedom for the smoother. However even this has been penalized a little; if you don't want penalization (smoothness selection, or estimation of $\lambda$), use fx = TRUE.
Update:
If you want piecewise-linear fits then you can achieve this with the b-spline basis bs = 'bs':
fit <- mgcv::gam(y ~ s(log2.time, bs='bs', k = 3, m = 1), data = df,
                 method = "REML")

where m = 1 now refers to the order of the spline, not the penalty. In this model the hinge point of the fit is in the middle of the data. Removing the k = 3 results in the default fit with k = 10.
The coefficients are still not the slopes of the linear sections however. You should be able to extract the derivative of the spline from the b-spline basis but I haven't worked out how to coax mgcv into yielding that info just yet. However, you can get this with finite differences.
library('mgcv')
devtools::install_github('gavinsimpson/gratia')
library('gratia') # for finite differences-based derivatives
library('ggplot2')
library('cowplot')
theme_set(theme_bw())

## fit piecewise-linear model
fit <- gam(y ~ s(log2.time, bs='bs', m = 1), data = df,
           method = "REML")
## new locations to evaluate everything at
newdf <- with(df, data.frame(log2.time = seq(min(log2.time),
                                             max(log2.time),
                                             length = 100)))
## extract model coefs
b <- coef(fit)
## get the Xp matrix, the prediction matrix for the spline
Xp <- predict(fit, newdf, type = "lpmatrix")
## evaluate 1st derivative at new locations
d <- fderiv(fit, newdata = newdf)

## stick everything together
pltdf <- data.frame(log2.time  = newdf$log2.time,
                    spline     = Xp[,-1] %*% b[-1],
                    derivative = d[[1]][['s(log2.time)']][['deriv']])

## individual plots
p1 <- ggplot(pltdf, aes(x = log2.time, y = spline)) +
    geom_line()
p2 <- ggplot(pltdf, aes(x = log2.time, y = derivative)) +
    geom_step()
## combine
plot_grid(p1, p2, align = 'hv', axis = 'lrtb', ncol = 1)

Comment: @dan what do you mean by a "spline slope"?
Comment: @dan that `for` loop is doing something very odd. It looks like you are trying to estimate the rate of change between knots but doing that using the estimated coefficient for the basis function. Are you thinking of this model as fitting a piece-wise linear model? Anyway, `coef()` already gives you the model coefficients, you don't need to compute them. And the SEs I mentioned are for the things returned by `coef()` not the thing you are computing. I'll try to dig out code to plot the basis functions being used in this model as the coefs correspond to those basis functions.
Comment: @dan you can do piecewise linear fits in mgcv using the b-spline basis. I've added an example of achieving this. MARS may be the way to go here --- a bit of overkill as it is supposed to be used with a large number of predictor variables. I guess it would work and it would select the knot location for you. The code I showed in the update will compute the derivatives for your original `fit` with a low-rank cubic spline (but you won't want `geom_step()` for `p2`; use `geom_line()` instead) if you want to see the derivatives of that much smoother model, even with `k = 3`.
Comment: Thanks a lot @Gavin Simpson. I've updated my post to better reflect what I'm after. Hope it makes it easier to address.
Comment: I meant spline coefficient. Sorry about that - bad use of term. Post is updated.
Comment: Thanks a lot @Gavin Simpson. I think that perhaps a piecewise linear spline regression, perhaps optimizing the location of knots, might better address my needs in this problem. Perhaps the `MARS` algorithm (implemented in the `earth` `R` `package`), might work well here. So perhaps it's not worth your time bothering with looking for code that plots the basis function.


Como se comporta um método assíncrono executando um método síncrono em Python?

Question: Em Python um método assíncrono é capaz de executar em paralelo, mas se dentro dele eu tiver uma função "normal", ela também será executada de forma assíncrona ou a partir daquele momento a execução será "travada" e outras funções não poderão ser executadas "ao mesmo tempo"?
def funcao_normal():
    # algum código aki...

async def funcao_assincrona():
    # algum código aki...
    funcao_normal()

await funcao_assincrona()

Comment: Tem conhecimento sobre o conceito de corotinas?
Comment: Não, na vdd acabei de chegar nesse negócio de assíncrono, mas agora sei o nome que eu tenho que procurar (corotinas né?) Obg @Woss
Answer: Quando você chama um código síncrono de uma função assíncrona o event loop ficará travado até a função síncrona retornar. Ou seja, caso seja uma chamada não bloqueante (e.g. uma função que apenas formata strings) não haverá tanto problema. No entanto, se for uma chamada bloqueante como acesso a banco de dados, o event loop pode ficar travado por mais tempo do que o esperado não dando chance a outras corotinas rodarem.
O ideal é não fazer chamadas síncronas bloqueantes a partir de código assíncrono, mas caso seja necessário, a forma correta é criar um executar e colocar a função síncrona para rodar dentro dele:
async def async_func():
    executor = concurrent.futures.ThreadPoolExecutor(max_workers=3)
    loop = asyncio.get_event_loop()
    result = await loop.run_in_executor(executor, sync_function, *args_for_sync_func)

Dessa forma, a função síncrona rodará no event loop atual.


Native (C#, C++) UI plugins for Cordova Windows?

Question: For Cordova iOS and Cordova Android it is possible to create plugins that create native UI on top of your app - you just include the libraries in your plugin and execute their API. Example for Android InAppBrowser.
For Cordova Windows, the native code is HTML and Javascript, hence the InAppBrowser plugin also adds a standard HTML tag for a Webview (or even plain Iframe) to get the same effect.
But you can also create plugins for Cordova Windows that use C# or C++ native code via a Windows Runtime Component. A public example is the globalization plugin that uses a <code>.winmd</code> file to offer APIs to the Javascript code  (source code for this). This works great and is pretty awesome.
Unfortunately all the plugins that I could find use this C#/C++ native plugin mechanism only to receive some method call, do something with the parameters and return some data. None of those open any windows or create any other GUI (that might for example be offered by an external C# SDK).
How can one create a plugin for Cordova Windows that creates User Interface with native (C#, C++) code? Is this possible at all?
Answer: Got a response in a Apache Cordova mailing list that I am reproducing here:

Unfortunately, No.  C#/C++ Portable Class Library ( PCL ) code cannot
  render on top of the web component.
  The libraries that you can use are limited in PCLs and for projects
  targeting Windows Store it is not possible to render UI.
  If the entire cordova-windows platform were re-architected to be a C# or
  C++ based application, with a native webview container in which to render,
  then everything is possible.  This is a long risky road though ...
  everything from the cordova.js and the bridge would have to change, and
  every plugin would need to be rewritten.


How to make jquery radio button function run on page load?

Question: EDIT: Thanks for the replies! Unfortunately using .trigger('change') or .change() to manually run the event doesn't work properly. If the user changes the value of one set of radio buttons, but doesn't change the other, the maths doesn't add up. Any other suggestions?
I have this form
It mostly works as I want it to, but I would like the jquery function to run on page load as well as when the user changes the radio button selection. How would I do this?
var price=$("input[name='courierrepairprice']").val();
price = Number(price.replace(/[^0-9\.]+/g,""));
var postage_out=0;
var postage_in=0
$("input[name='outwardpostage']").change(function()
{
   postage_out=$(this).val();
   tot_price=parseFloat(price,10)+parseFloat(postage_out,10)+parseFloat(postage_in,10)
   tot_price=tot_price.toFixed(2)

   $('.tot_price').text('£'+tot_price);
});
$("input[name='returnpostage']").change(function()
{
   postage_in=$(this).val();
   tot_price=parseFloat(price,10)+parseFloat(postage_out,10)+parseFloat(postage_in,10)
   tot_price=tot_price.toFixed(2)
   $('.tot_price').text('£'+tot_price);
});

Answer: Use .trigger('change') or .change() to manually simulate an event
var price=$("input[name='courierrepairprice']").val();
price = Number(price.replace(/[^0-9\.]+/g,""));
var postage_out=0;
var postage_in=0;

function calculate(){
    console.log('calc', price, postage_out, postage_in)
    var tot_price = price + postage_out + postage_in;
    tot_price=tot_price.toFixed(2)

    $('.tot_price').text('£' + tot_price);
}

$("input[name='outwardpostage']").change(function() {
    postage_out = parseFloat($(this).val());
    calculate();
}).filter(':checked').trigger('change');
$("input[name='returnpostage']").change(function() {
    postage_in =  parseFloat($(this).val());
    calculate();
}).filter(':checked').trigger('change');

Demo: Fiddle
Comment: Actually it doesn't work properly :-/ . The maths doesn't add up if a user clicks on one set of radio buttons but doesn't click the other
Comment: @Chris I didn't look at the calculation portion since the question was regarding page load
Comment: The calculation portion worked fine before. I'm guessing it's because the ".trigger('change')" part only runs the event for that function, rather than running both functions. Should I open a new question for this?
Comment: Thanks Arun I really appreciate it :-)
Answer: call your change event again after at the end of the change function to autoinvoke the change call....
 $("input[name='outwardpostage']").change(function()
 {
  postage_out=$(this).val();
  tot_price=parseFloat(price,10)+parseFloat(postage_out,10)+parseFloat(postage_in,10)
  tot_price=tot_price.toFixed(2)

  $('.tot_price').text('£'+tot_price);
}).change();  //<--here ..same for other change event

Comment: Thanks for the reply! Unfortunately it doesn't work properly :-( . The maths doesn't add up if a user clicks on one set of radio buttons but doesn't click the other
Comment: not getting you.. what do you mean... can u show some example
Comment: Yes certainly - you can see it in Arun's fiddle: http://jsfiddle.net/arunpjohny/kdK9H/
Comment: I'm guessing it's because the ".trigger('change')" part only runs the event for that function, rather than running both functions.
Answer: Another approach is to move code inside the change function to obvious function and call it ones on load and then in change listeners.
$(document).load(function(){
    var doAction = function(){

    };

    $("input[name='returnpostage']").change(function()
    {
      doAction();
    };

    doAction();
});

Answer: Hi you can try this one also
var price=$("input[name='courierrepairprice']").val();
price = Number(price.replace(/[^0-9\.]+/g,""));
var postage_out=0;
 var postage_in=0
$("input[name='outwardpostage']").change(function()
{
postage_out=$(this).val();
tot_price=parseFloat(price,10)+parseFloat(postage_out,10)+parseFloat(postage_in,10)
tot_price=tot_price.toFixed(2)

$('.tot_price').text('£'+tot_price);
}).change();
$("input[name='returnpostage']").change(function()
{
postage_in=$(this).val();
tot_price=parseFloat(price,10)+parseFloat(postage_out,10)+parseFloat(postage_in,10)
tot_price=tot_price.toFixed(2)
$('.tot_price').text('£'+tot_price);
}).change();

JS Fiddle Demo Demo
Comment: Thanks for the reply! Unfortunately it doesn't work properly :-( . The maths doesn't add up if a user clicks on one set of radio buttons but doesn't click the other
Answer: DEMO FIDDLE
code-
var price=$("input[name='courierrepairprice']").val();
price = Number(price.replace(/[^0-9\.]+/g,""));
var postage_out=0;
var postage_in=0;
var fndo = function()
{
 postage_in=$(this).val()||postage_in;
 tot_price=parseFloat(price,10)+parseFloat(postage_out,10)+parseFloat(postage_in,10)
 tot_price=tot_price.toFixed(2)
 $('.tot_price').text('£'+tot_price);
};

$("input[name='outwardpostage'], input[name='returnpostage']").change(fndo);
$(document).ready(fndo);

Here I used a function object and called on change and document ready, added a condition for postage_in to prevent being undefined when called by document because there will be no value for document
Comment: Thanks for the reply. Unfortunately it doesn't work. In your fiddle the total price displayed on page load doesn't take postage costs into account.


how to fix null to be returned in flutter?

Question: I have written this code for a complaint application. this is the screen where the user puts in the detailed info about the complaint. I have added an image picker to import images from the gallery or camera. but after I lot of research changing of code, this still shows this error. Someone please help as this is taking days.
My code;
class ComplaintNo1 extends StatefulWidget {

 @override
  _ComplaintNo1State createState() => _ComplaintNo1State();
}

class _ComplaintNo1State extends State<ComplaintNo1> {

  late File imageFile;

  _openGallery(BuildContext context) async{
    final picture = await ImagePicker().pickImage(source: ImageSource.gallery);
    this.setState(() {
      imageFile= picture as io.File;
    });
    Navigator.of(context).pop();
  }

  _openCamera(BuildContext context) async{
    final picture = await ImagePicker().pickImage(source: ImageSource.camera);
    this.setState(() {
      imageFile= picture as io.File;
    });
    Navigator.of(context).pop();
  }

  Future<void> _showChoiceDialog(BuildContext context) {
    return showDialog(context: context, builder: (BuildContext context) {
      return AlertDialog(
        title: Text('Make a choice!'),
        content: SingleChildScrollView(
          child: ListBody(
            children: <Widget>[
              GestureDetector(
                child: Text('Gallery'),
                onTap: () {
                  _openGallery(context);
                },
              ),
              Padding(padding: EdgeInsets.all(8.0)),
              GestureDetector(
                child: Text('Camera'),
                onTap: () {
                  _openCamera(context);
                },
              )
            ],
          ),
        ),
      );
    });
  }

   Widget _decideImageView() {
    if(imageFile == (null)) {
      return Text('No Image Selected!');
    }
    else {
      Image.file(imageFile,width: 100,height: 200);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Icon(
            Icons.camera_alt,
          ),
          ElevatedButton(onPressed: () {
            _showChoiceDialog(context);
          }, child: Text('Select Image'),
          ),
           _decideImageView(),
          SizedBox(
            width: 20.0,
            height: 20.0,
          ),
          TextFormField(
            decoration: InputDecoration(
              border: OutlineInputBorder(),
              labelText: 'Title of complaint',
              prefixIcon: Icon(Icons.title),
              labelStyle: TextStyle(
                fontSize: 20.0,
                color: Colors.blueAccent,
              ),
            ),
          ),
          SizedBox(
            width: 20.0,
            height: 20.0,
          ),
          TextFormField(
            decoration: InputDecoration(
              border: OutlineInputBorder(),
              labelText: 'Time',
              prefixIcon: Icon(Icons.access_time),
              labelStyle: TextStyle(
                fontSize: 20.0,
                color: Colors.blueAccent,
              ),
            ),
          ),
          SizedBox(
            width: 20.0,
            height: 20.0,
          ),
          TextFormField(
            decoration: InputDecoration(
              border: OutlineInputBorder(),
              labelText: 'Starting date',
              prefixIcon: Icon(Icons.date_range),
              labelStyle: TextStyle(
                fontSize: 20.0,
                color: Colors.blueAccent,
              ),
            ),
          ),
          SizedBox(
            width: 20.0,
            height: 20.0,
          ),
          TextFormField(
            decoration: InputDecoration(
              border: OutlineInputBorder(),
              labelText: 'Description of complaint',
              prefixIcon: Icon(Icons.description),
              labelStyle: TextStyle(
                fontSize: 20.0,
                color: Colors.blueAccent,
              ),
            ),
            maxLines: 5,
          ),
        ],
      ),
    );
  }
}

And this is the error
The body might complete normally, causing 'null' to be returned, but the return type is a potentially non-nullable type.
Answer: Your _decideImageView() method is not returning the Image Widget
You've just to add the return keyword to your method :
Widget _decideImageView() {
  if(imageFile == (null)) {
    return Text('No Image Selected!');
  }
  else {
    return Image.file(imageFile,width: 100,height: 200);
  }
}

Comment: Thank you so much but after adding the return this error is being shown. **LateInitializationError: Field 'imageFile' has not been initialized.**


Flatten nested dictionary to key and joined string value

Question: I need help with a function to flatten a nested dictionary in the following format:
dict_test = {
    "id" : "5d4c2c0fd89234260ec81",
    "Reference Number" : "JA-L800D-191",
    "entities_discovered" : {
        "OTHER_ID" : [
            "L800DFAG02191"
        ],
        "CODE_ID" : [
            "160472708",
            "276954773"
        ]
    },
    "label_field" : [
        "ELECTRONICS",
        "HDMI"
    ],
    "numeric_field" : [
        491,
        492
    ],

}

The function I was working with, flattens the dictionary to one dimension (key:value) as I want, but doesn´t join the values within the same key iteration.
def flatten(d):
    agg = {}
    def _flatten(d, prev_key=''):
        if isinstance(d, list):
            for i, item in enumerate(d):
                new_k = '%s.%s' % (prev_key, i) if prev_key else i
                _flatten(item, prev_key=new_k)
        elif isinstance(d, dict):
            for k, v in d.items():
                new_k = '%s.%s' % (prev_key, k) if prev_key else k
                _flatten(v, prev_key=new_k)
        else:
            agg[prev_key] = d

    _flatten(d)
    return agg

My current output is:
{
    "id" : "5d4c2c0fd89234260ec81",
    "Reference Number" : "JA-L800D-191",
    "entities_discovered.OTHER_ID.0" : "L800DFAG02191",
    "entities_discovered.CODE_ID.0" : "160472708",
    "entities_discovered.CODE_ID.1" : "276954773",
    "label_field.0" : "ELECTRONICS",
    "label_field.1" : "HDMI",
    "numeric_field.0" : 491,
    "numeric_field.1" : 492
}

But actually I´m looking for something like (joining the values into the same string and separated by , or |):
{
    "id" : "5d4c2c0fd89234260ec81",
    "Reference Number" : "JA-L800D-191",
    "OTHER_ID" : "L800DFAG02191",
    "CODE_ID" : "160472708, 276954773",
    "label_field" : "ELECTRONICS, HDMI",
    "numeric_field" : ¨491, 492¨
}

Comment: If your `list` does not contain any other `dict` or `list` items, then you could change the code inside `if isinstance(d, list)` branch to: `agg[prev_key] : ', '.join([str(i) for i in d])`
Answer: You can use join() built-in method to join values together.
def do():
    dict_test = {
        "id": "5d4c2c0fd89234260ec81",
        "Reference Number": "JA-L800D-191",
        "entities_discovered": {
            "OTHER_ID": [
                "L800DFAG02191"
            ],
            "CODE_ID": [
                "160472708",
                "276954773"
            ]
        },
        "label_field": [
            "ELECTRONICS",
            "HDMI"
        ],
        "numeric_field": [
            491,
            492
        ],
    }

    new_dict = {}
    for key, value in dict_test.items():
        if isinstance(value, dict):
            for _key, _value in value.items():
                if isinstance(_value, list):
                    new_dict.update({_key: ', '.join([str(item) for item in _value])})

        elif isinstance(value, list):
            new_dict.update({key: ', '.join([str(item) for item in value])})

        else:
            new_dict.update({key: value})

    return new_dict

if __name__ == '__main__':
    print(do())

Output:
{
    'id': '5d4c2c0fd89234260ec81',
    'Reference Number': 'JA-L800D-191',
    'OTHER_ID': 'L800DFAG02191',
    'CODE_ID': '160472708, 276954773',
    'label_field': 'ELECTRONICS, HDMI',
    'numeric_field': '491, 492'
}

Comment: I find this too long than necessary!
Comment: I appreciate your feedback, I just wrote it quickly, I will edit it as soon as I can.
Answer: def recursive_flatten_dict(tmp, dict_test):
    for i,v in dict_test.items():
        if type(v) == type({}):
            recursive_flatten_dict(tmp,v)
        else:
            tmp[i] = v
    return tmp

recursive_flatten_dict({},dict_test)

Answer: def flatten(dict_test):
    for key in ['label_field', 'numeric_field']:
        dict_test[key]= ', '.join([str(c) for c in dict_test[key]])

    for c in dict_test['entities_discovered'].keys():
        dict_test[c]= ', '.join(dict_test['entities_discovered'][c])

    return dict_test

The above function does the job. I hope this what you are looking for?
Answer: Simple recursion using a generator:
def flatten(d):
   for a, b in d.items():
     if isinstance(b, dict):
        yield from flatten(b)
     else:
        yield (a, b if not isinstance(b, list) else ', '.join(map(str, b)))

print(dict(flatten(dict_test)))

Output:
{
 'id': '5d4c2c0fd89234260ec81',
 'Reference Number': 'JA-L800D-191',
 'OTHER_ID': 'L800DFAG02191',
 'CODE_ID': '160472708, 276954773',
 'label_field': 'ELECTRONICS, HDMI',
 'numeric_field': '491, 492'
}


Getting MySQL record count with C#

Question: I would like to know how can I get record count of a query with C#.
Here is the code that I use..
    MySqlDataReader recordset = null;
    query = new MySqlCommand("SELECT * FROM test ORDER BY type_ID ASC", this.conn);
    recordset = query.ExecuteReader();

    while (recordset.Read())
    {
        result.Add(recordset["type_ID"].ToString());

    }
    return result;

Answer: I was using a SELECT COUNT(*) and expected an int to be returned.  You may need this to get a usable value:
mysqlint = int.Parse(query.ExecuteScalar().ToString());

Answer: A couple of things...
The SQL statement you would use is:

SELECT COUNT(*) FROM test

However, when using the MySQL Connector/Net to connect to MySQL through C# there is some care to be given when handling query results.
For example, as cited in this question and on Microsoft Connect int.Parse("0") equivalently known as Int32.Parse("0") can throw a FormatException on some machines.
I have found that Convert.ToInt32 handles this case nicely.
So your code will be something like this:
using (var conn = new MySqlConnection(cs))
{
    conn.Open();
    using (var cmd = new MySqlCommand("SELECT COUNT(*) FROM test", conn))
    {
         int count = Convert.ToInt32(cmd.ExecuteScalar());
         return count;
    }
}

Remember to make use of using statements in order to ensure that the MySQL objects get disposed of properly.
Answer: You're adding a new element in result for each row. Depending on the type of result you should be able to do something like result.Count after the while loop completes.
Comment: @she hates me: Just curious, but why why would you need the row count before the loop?
Comment: @she hates me: If the result set is small, iterate through it once and store the rows in a list, then get the count, then iterate through the stored list to get all the rows again. The second time you iterate through you know how many elements you have and you can do whatever you were doing that needs the count here.
Answer: You could run another query first to get the count :
query = new MySqlCommand("SELECT count(*) as theCount FROM test ORDER BY type_ID ASC", this.conn);

but in truth, you are probably best changing the problem so you wont need the count until after you have populated the list.
Comment: You shouldn't run more queries than you need to.  Doing so will make the application run a bit more slowly.  You can do this with one query.

Getting MySQL record count with C#


How to display text next to image drupal view?

Question: I have created a view displaying unordered list of fields - image, Title, descriprion.
How do I get the title and description to display next to image, eg
<code> IMAGE | Title
         Description
</code>
Comment: the use of css floats immediately comes to mind
Comment: when I use float left on the image field it seems to display all the images in a row I want the images to all stay in there seperate rows and just have the title and descriprion fields display to the right of the images
Comment: try this
on class for title field
.your_title_class {clear:both }
Answer: The simplest solution to your problem is, on right side in views there is a format option set it to Unformatted list, in settings do not select Add views row classes and Add striping (odd/even), first/last row classes.
Below that is Show:Fields | Settings , click settings and select Provide default field wrapper elements and then select the fields mentioned below it to be displayed inline, which in your case is image Title and description.
Also the Table Format is good option but it creates a lot of problem in CSS customization.
Answer: You can use Views Fieldset module ,it will allow you to container for set of fields in views (fieldset) and then you can have image in one fieldset(let say image_fieldset) and other related fields in second fieldset(let say other_fields_field_set)
<code>//finally some css tweaks like
.say image_fieldset {
float:left;
}
</code>
css as per you need
Answer: A simple solution is to use a Table Format for the views display with 3 different fields without labels. It will never break!


Is my if statement/code-test correct Swift

Question: My instructor said that this code test should evaluate to:
 parrotTrouble(isTalking: true, hour: 6) → true
 parrotTrouble(isTalking: true, hour: 7) → false
 parrotTrouble(isTalking: false, hour: 6) → false

In xcode, mine is true, false, true.
With the code given, this seems true. I'm not sure, though. What am I doing wrong if anything?
Question:
"We have a loud talking parrot. The "hour" parameter is the current hour time in the range 0..23. We are in trouble if the parrot is talking and the hour is before 7 or after 20. Return true if we are in trouble."
 func parrotTrouble(isTalking: Bool, hour: Int) -> Bool {

    if hour < 7 {
        return true
    } else if hour > 20 {
        return true
    } else {
    return false
    }
}

parrotTrouble(isTalking: true, hour: 6)
parrotTrouble(isTalking: true, hour: 7)
parrotTrouble(isTalking: false, hour: 6)

Comment: You never look at the `isTalking` parameter. You can use `&&` to combine two booleans with the AND operation (TRUE if both sides are TRUE -- FALSE otherwise)
Answer: You need to check isTalking as well as the hour:
Here's the real simple version:
func parrotTrouble(isTalking: Bool, hour: Int) -> Bool {
    return isTalking && (hour < 7 || hour > 20)
}

The longer version:
func parrotTrouble(isTalking: Bool, hour: Int) -> Bool {
    if isTalking {
        if hour < 7 {
            return true
        } else if hour > 20 {
            return true
        }
    }
    return false
}

Comment: `return isTalking && !(7...20 ~= hour)`, slightly shorter? :p (accidentally removed my comment)
Comment: See my update to make it clear. I was simply showing the body of your method.


Find the minimum number of colors to color any Map on Torus.

Question: I am finding the minimum number of colors to color any map on torus.
I have drawn how complete graph $K_5$ can be embedded on a torus.

I know that the chromatic number of this graph is $5$ and we define the chromatic number as the smallest number of colors needed to color the vertices of so that no two adjacent vertices share the same color.
I want to know how the embedding of $K_5$ on torus implies that we need more than four colors to color any map on torus.
Please help me.
Answer: If you construct the dual graph to your embedding (so that each vertex is the capital of a country) then you will see five countries each of which shares a border with all the others.
You may need as many as seven colors, The dual graph is $K_7$.

https://mathworld.wolfram.com/TorusColoring.html