ArrayList versus List

Question: Qual o motivo de no C# devemos dar preferência de usar o List ao invés de ArrayList?
Answer: Porque List é genérica e ArrayList não é. O tipo do dado de ArrayList é um object, ou seja pode por qualquer coisa nela. Em linguagens estáticas isto não é adequado, você perde a segurança de tipos, não pode mais confiar no conteúdo da lista. Já List<T> determina qual é o tipo que pode colocar nela, então todo o código é confiável que só terá elementos daquele tipo específico e de tipos derivados dele que obviamente são compatíveis com este tipo. O próprio compilador consegue garantir a segurança de tipos.
Não é só segurança, é performance também. Evita-se assim o casting e o boxing (tipos por valor só podem ser colocado por referência em um ArrayList, isto é péssimo.
O ArrayList existe porque C# 1 não tinha genéricos ainda. A solução quando precisava da segurança de tipos era criar uma nova estrutura parecida com o ArrayList, mas que internamente tinha um tipo específico, assim daria a segurança e performance, porém fazer uma para cada tipo que precisasse era praticamente inviável.
Ainda é possível usar List<object> se desejar aceitar qualquer tipo de objeto na lista, mas raramente isto é o desejado. Também é possível usar List<dynamic> onde o compilador nem verifica o acesso ao objeto, que tem vantagens e desvantagens. Quando usa o List<object> toda vez que pegar o elemento só pode acessar os membros do tipo Object, a não ser que faça um cast  para o tipo que deseja. Dá trabalho, o código fica confuso e verboso, é lento, e pode gerar erros facilmente se não tomar muito cuidado.
Exemplo:
using System.Collections;
using System.Collections.Generic;

public class Program {
    public static void Main() {
        var array = new ArrayList() { 1, "texto" };
        var total = 0;
        foreach (var item in array) {
            //total += item; //se tirar o comentário dá erro quando tentar somar a string
        }
        //array[1].Contains("t"); //mesmo sendo string não pode acessar Contains() porque o tipo é object
        ((string)array[1]).Contains("t");
        var list = new List<int>() { 1, /*"texto"); //<-- Error at compile process //ddaria erro aqui*/ };
        total = 0;
        foreach (var item in list) total += item;
    }
}

Veja funcionando ideone. E no .NET Fiddle. Também coloquei no GitHub para referência futura.
Answer: List<T> é uma classe genérica. Ela suporta armazenar valores de um tipo específico sem a necessidade de forçar de ou para object.
ArrayList simplesmente armazena referencias de objeto. Como uma coleção genérica, List<T> implementa a IEnumerable<T> interface genérica e pode ser usada facilmente no LINQ (sem precisar de Cast ou OfType).
ArrayList pertence aos dias em que C# não tinha genéricos. É depreciado em favor de List<T>. Você não deve usar ArrayList em um novo código que alveja .NET> = 2.0, a menos que tenha que se conectar a uma API antiga que o use.
referência: stackoverflow.com/a/2309699/4190610
Comment: https://stackoverflow.com/a/2309699/4190610

ArrayList versus List


JAGS array indexing

Question: I have a relatively simple multivariate response problem that seems to causing me problems with array indexing.  I've scraped/rewworked the model program down to the bare essentials and hopefully haven't cut/replaced too much. I hav3 265 total observations, 5 different groups of responses, each with 53 replications.
<code># Notes:
# N= total number of samples = 265
# K= number of clusters = 5
# T = number of observations in each clusters =53
# P = nterms=number of independent variables = 10
#
model {
  for (j in 1:K) {   #K
      for (i in 1:T) {  #T
          y[i,j] ~ dnorm(mu[i,j], tau)
          mu[i,j]<-  b0 + b[1]*x[i,j,1] + b[2]*x[i,j,2] + b[3]*x[i,j,3] + b[4]*x[i,j,4] +     b[5]*x[i,j,5] + b[6]*x[i,j,6] + b[7]*x[i,j,7] + b[8]*x[i,j,8] + b[9]*x[i,j,9] + b[10]*x[i,j,10]   # error
    #            mu[i,j]<-  b0 + b[1]*x[i,j,1]+ b[2]*x[i,j,2]  # no error
         }
      }
# mean <- b0+ inprod(x[i,j,], beta[])
# priors ------------------
b0 ~ dnorm(0,0.001)  # prior on constant term
for(i in 1:nterms) {
       b[i] ~ dnorm(0,0.001)
    }
    tau ~ dgamma(1.0E-3, 1.0E-3)
    sigma <- 1 / sqrt(tau)
}
</code>
My data input is coming from an R script (data input snippet):
<code>input<- "GB_migration.csv"
obs.raw<-read.table(input, header = TRUE, sep = ",")

P<-10
K <- 5
T <- 53
N <- nrow(obs.raw)
Y.raw <- obs.raw[,2]
X.raw <- obs.raw[,1:P+2]

X<-unlist(X.raw)
dim(X)<-c(T,K,P)

Y<-unlist(Y.raw)
dim(Y)<-c(T,K)
</code>
….snip ….
The error code I get when I run it with all 10 independent variables:

Error in jags.model("Migration.mod", jags.data, n.adapt = 500,
  n.chains = 2) :    RUNTIME ERROR: Compilation error on line 10. Unable
  to resolve node mu[1,1] This may be due to an undefined ancestor node
  or a directed cycle in the graph

I feel like I'm missing something basic with the array indexing, but I cannot seem to put my finger on it. (I've un-nested as many of the vector operations as I could to try to track this down.Hopefully the code still makes sense. )
Thanks in advance for any insight. Dave
Comment: That's an error you would get, for example, when there is something wrong with your indexing, and you have a lot of indexing so... double check it (say, remove stuff until it works) thats my tip.
Comment: If you add terms one by one and it fails with `b[6]*x[i,j,6]` (because 6>K) then incorrectly assigned matrix dimensions are the problem.
Comment: Did you pass `nterms` as well as `P` to JAGS somewhere?
Answer: So there aren't a lot of things left that can go wrong here but since there's no toy data to look at I can't help you much more than this: nterms is less than 10 or the full array of x's is not defined.  There are no cycles, so one of the b's or x's is undefined.  If you would like a better answer, please post a minimal working/failing example.

JAGS array indexing


Python (falcon) transition is read only

Question: I'm running into a strange error -psycopg2.errors.ReadOnlySqlTransaction: transaction is read-only when i'm trying to read data from my redshift database from my python application. I'm not trying to modify the database so i'm not sure why this happens. I'm using a postgresql plugin (psycopg2) version 2.8.4. And python version 3.5 -I have lot of other queries that i'm running in the same approach and they work without a problem, so i'm a little confused what could be causing this.
Here is the query i'm running
SELECT
    stat_date,
    age,
    name,
    SUM(spent) as spent,
FROM (

    SELECT stat_date, age,name, spent
    FROM mview_a
    WHERE id in ('id1', 'id2')

UNION ALL

    SELECT stat_date, age,name, spent
    FROM mview_b
    WHERE id in ('id1', 'id2')

UNION ALL

    SELECT stat_date, age,name, spent
    FROM mview_c
    WHERE id in ('id1', 'id2')

UNION ALL

    SELECT stat_date, age,name, spent
    FROM view_d (combination of multiple mviews)
    WHERE id in ('id1', 'id2')

UNION ALL

    SELECT stat_date, age,name, spent
    FROM mview_e
    WHERE id in ('id1', 'id2')

)

GROUP BY 1;

And this is how i pass my query along with params
dw = self.get_conn(conn)
results = dw.fetch_all_query(query, params=params, **kwargs)

And the database calls fails on this line from psycopg2 package.
self.execute_query(q, dict_cursor=dict_cursor, params=params,
                   readonly=readonly, autocommit=autocommit, conn=False)

Comment: This has lot missing. Have no idea what `dw.fetch_all_query` is doing?  Or how that leads to `self.execute_query(...)`? Or what `q` actually is in `self.execute_query(q, ...)`
Comment: @AdrianKlaver it just calls execute_query which is coming from psycopg2. The dw is just to specify what data source is being used.
Comment: There is no `execute_query` in psycopg2. And you still have not told us what `query` and `q` refer to. As long the information provided is incomplete the chances of an answer are slim.
Comment: My bad, i thought it was clear. The q is referring to the query, and query is the query i shared in the post. I didn't think this would have been related to low-level implementation of psycopg2 or the code. I have other code blocks that are using the exact same logic and working. So i was thinking the transition-is-read-only error should be related some configs adjustments. Eventhough, i'm not trying to write anything in the database, it's weird i am seeing it.

execute_query is a wrapper function that calls cursor.execute() from psycopg2 with the parameters @adrian
Comment: What happens if you run the query in `psql` using `BEGIN read only; `?
Answer: In my case, the issue was happening because one of the mviews i use is a combination (union all) of two different mviews and for some reason, psql was throwing an error saying transaction is read only. The error message was pretty unclear to solve this.

Python (falcon) transition is read only


Meaning of var [foo] = bar?

Question: I seen a code snippet like the below. Can anybody please tell me what
var [input] = data; var [checkbox, payee, amount]  = data2;

means?
function example(data,data2){
var [input] = data;
var [checkbox, payee, amount]  = data2;
............
............
}

Comment: it's a [destructuring assignment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) by taking an array as value to assign
Comment: Possible duplicate of [Square Brackets Javascript Object Key](https://stackoverflow.com/questions/32515598/square-brackets-javascript-object-key)
Comment: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Computed_property_names
Answer: As Nina Scholz stated in her comment, it's a destructuring assignment.
If data2 was an array of [1, 2, 3], then var [checkbox, payee, amount]  = data2; is the same as:
    var checkbox = data2[0]; // 1
    var payee = data2[1]; // 2
    var amount = data2[2]; // 3

Rest parameter
You can using destructuring with rest parameter like in the example below, to save multiple elements into an array.

const digits = [1, 2, 3, 4, 5];
const [one, ...other] = digits;
console.log(one);
console.log(other);

Omitting values
You can ignore the values you're not interested in, like this:

const myArray = ["car", "cat", "house", "dog", "window", "mouse"];
const [, cat, ,dog, , mouse] = myArray;
console.log(cat, dog, mouse);

or like this:

const myArray = ["John", "Mary", "Steve", 0, 1, 2];
const [name1, name2, name3] = myArray;
console.log(name1, name2, name3);
Answer: This is just the destructuring assignment

var t = [1,2];

var [a,b] = t;

console.log(a);
console.log(b);

When used on arrays, it assigns consecutive array elements to variables introduced at the left side of the assignment operator.
Answer: It's a destructuring assignment with an array/iterable object (with implemented Symbol.iterator) with values to assign.
The value goes into the variable with the same index as the given data.
For getting only some parts at a certain index, you could use an object with indices as keys.

var array = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten'];
    [zero, one] = array,
    { 3: three, 10: ten } = array;

console.log(zero);
console.log(one);
console.log(three);
console.log(ten);
Answer: This is Destructuring assignment.

The destructuring assignment syntax is a JavaScript expression that
  makes it possible to unpack values from arrays, or properties from
  objects, into distinct variables.

As per your example,
var data = [1];
var [input] = data;
console.log(input); //1

Meaning of var [foo] = bar?


Functions, small query.

Question: I am interpreting the definition of a function as:' A function has a specific set of inputs (domain) and outputs (range), governed by a specific rule (function).
Is that correct?
What is a co-domain?
Does a function have to be one-to-one, to be a function?
For example:
$$f(x) =x^2 $$is not a function but $$f(x) =x^2\quad for\quad x\ge0\quad is? $$
What does the following, mean? (in the context of the definition of a function).
$$ x\in X\quad y\in Y ,\ such\ that \ f:X\to Y$$
The only thing I can understand is $f:X \to Y$.
Which reads as the function $f$ such that $X$ results in$Y$, right?
I don't quite understand the notation
$$ x\in X\quad y\in Y$$
And lastly in this context, what is the difference in the use of capital letters and lowercase letters, for example if i wrote:
$$ x\in X\quad y\in Y ,\ such\ that \ f:x \to y$$,
How would this be incorrect, as usually a function is written as $f(x) =y$, right?
I do apologise if this is all trivial and simple to understand.
Thank you for you assistance in advance.
Answer: The idea underlying what you call a "definition of function" sounds pretty accurate to me. Given two sets $A$ and $B$, a function $f:A\rightarrow B$ is a "rule", as you wrote, which sends each element of $A$ to one and only one element of $B$. Note that this definitions is made by three components: the set $A$ (the domain), the set $B$ (the codomain) and the rule $f$.
With this definition in mind, which is a clear version of yours, some of your questions have an immediate answer, some others are just nonsense.
E.g., when you write $f(x)=x^{2}$, you do give the "rule", but who is the domain? Who is the codomain?
ABOUT THE NOTATIONS. We often use capital letters to denote sets and lowercase letters to denote sets' elements. For example, $x \in X$ denote an element $x$ of a set $X$. With this in mind, we write as before $f:X \rightarrow Y$ to denote "a function $f$ with domain the set $X$ and codomain the set $Y$", while the notation $f: x \mapsto y$ denote "a function $f$ that sends an element $x$ to an element $y$".
Answer: 1) Yes, that is correct.
2) Co-domain is the superset of range. The set of elements where the values of our function can be.
3) No. One-to-one is a special kind of function. What you read somewhere is:
Relation is not a function if for some $x\in X$ there are 2 or more $y_1,y_2\in Y$ such that $f(x)=y_1$ and $f(x)=y_2$.
4) $x\in X, y\in Y$, such that $f:x\mapsto y$ means:
For every $x\in X$, there is $y\in Y$ such that $f(x)=y$.
5) Uppercase letters represent sets, for example $X=\left\{1,2,3,4,5 \right\}$, and lowercase letters represent elements, for example $x=1$. Now we want to say that function is defined for every element $x$ from set $X$.

Functions, small query.


For a small home network, is there any point to running Squid?

Question: For a small home network -- two laptops, two desktops, plus the main server -- should I expect much gain by running Squid on the main server?  I fully understand the value of running a caching name server for a small home network, but I'm not sure if there is any value to running an HTTP caching proxy.
The main server does full NAT for all other computers on the network, in case it matters.
Answer: You probably won't really see much gains in network performance.
What you do get is

A place where you can block annoying sites
you can integrate clamav to help block malware before it gets to your windows systems.
You can watch the access logs and see what computers are doing what.  And possibly see requests from systems that where infected by malware.  Or see when some stupid application is checking every 5 minutes for application updates.
Protect the Kiddies from sites you feel are objectionable when combined with blacklists.
Comment: I'd say you get decent improvement if the internet link is a slow one, like dial-up or satellite.
Answer: I don't think it's worth it.  You might see a small speed-up on commonly used pages (if they're used by both machines), but you're not going to save enough bandwidth or time to make it worth the hassle, IMO.
Answer: If you have a small network, there's not much to be gained.  I've had squid running on our home network.   Last time I measured it, it was reducing the traffic by 6-8%.  There's also the gain you get by removing the effect of latency on TCP setup.  But unless multiple users are hitting the same site, the re-visit hits are likely as not going to come from your browser's cache anyway.   If I didn't know the squid was running I'd be hard pressed to tell the difference.
Answer: If they all run the same operating system, and the update system on said operating system is caching-friendly, using a web cache would mean that you download each update once, not (in your case) four times.
YMMV.
Comment: Mind you, if they run Windows, you may win more by setting up WSUS than Squid. So yeah. Definitely YMMV.
Answer: Next to nothing or even slower unless all 4 computers go to the exact same websites all the time and still there wont be anything to get happy about, i properly spent all the time you would save typing this message :S
Answer: If you block all outbound traffic except for that from squid, you can get a nice view of what is sending traffic out of your network that you didn't otherwise know about.  Some stuff will just bounce off your firewall and the rest you can see in your squid logs.


How to theme D7 search results

Question: The default search results in D7 seem to include details of the node author, date, number of comments as seen here but I don't want these in my search results.
I have copied search-result.tpl.php and search-results.tpl.php to my theme file. I have added
print '
'. check_plain(print_r($info_split, 1)) .'</pre';

to search-result.tpl.php. The result is here ie showing the array with [user] [date] [comment] etc
What do I need to do to exclude author / date / number of comments from the search results? If it involves my theme's search-result.tpl.php what should be the contents of search-result.tpl.php ?
Answer:
Copy search-result.tpl.php into your theme folder..

Override above tpl using below code..
<?php

/**
 * @file
 * Default theme implementation for displaying a single search result.
 *
 * This template renders a single search result and is collected into
 * search-results.tpl.php. This and the parent template are
 * dependent to one another sharing the markup for definition lists.
 *
 * Available variables:
 * - $url: URL of the result.
 * - $title: Title of the result.
 * - $snippet: A small preview of the result. Does not apply to user searches.
 * - $info: String of all the meta information ready for print. Does not apply
 *   to user searches.
 * - $info_split: Contains same data as $info, split into a keyed array.
 * - $module: The machine-readable name of the module (tab) being searched, such
 *   as "node" or "user".
 * - $title_prefix (array): An array containing additional output populated by
 *   modules, intended to be displayed in front of the main title tag that
 *   appears in the template.
 * - $title_suffix (array): An array containing additional output populated by
 *   modules, intended to be displayed after the main title tag that appears in
 *   the template.
 *
 * Default keys within $info_split:
 * - $info_split['module']: The module that implemented the search query.
 * - $info_split['user']: Author of the node linked to users profile. Depends
 *   on permission.
 * - $info_split['date']: Last update of the node. Short formatted.
 * - $info_split['comment']: Number of comments output as "% comments", %
 *   being the count. Depends on comment.module.
 *
 * Other variables:
 * - $classes_array: Array of HTML class attribute values. It is flattened
 *   into a string within the variable $classes.
 * - $title_attributes_array: Array of HTML attributes for the title. It is
 *   flattened into a string within the variable $title_attributes.
 * - $content_attributes_array: Array of HTML attributes for the content. It is
 *   flattened into a string within the variable $content_attributes.
 *
 * Since $info_split is keyed, a direct print of the item is possible.
 * This array does not apply to user searches so it is recommended to check
 * for its existence before printing. The default keys of 'type', 'user' and
 * 'date' always exist for node searches. Modules may provide other data.
 * @code
 *   <?php if (isset($info_split['comment'])): ?>
 *
 *       <?php print $info_split['comment']; ?>
 *
 *   <?php endif; ?>
 * @endcode
 *
 * To check for all available data within $info_split, use the code below.
 * @code
 *   <?php print '
'. check_plain(print_r($info_split, 1)) .'
'; ?>
 * @endcode
 *
 * @see template_preprocess()
 * @see template_preprocess_search_result()
 * @see template_process()
 *
 * @ingroup themeable
 */
?>
<li class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php print render($title_prefix); ?>
  <h3 class="title"<?php print $title_attributes; ?>>
    <a href="<?php print $url; ?>"><?php print $title; ?>

  <?php print render($title_suffix); ?>

    <?php if ($snippet): ?>
      <p class="search-snippet"<?php print $content_attributes; ?>><?php print $snippet; ?>

    <?php endif; ?>

Clear Cache

Author / date / number of comments from the search results is getting rendered using below code
<?php if ($info): ?>

<?php print $info; ?>

<?php endif; ?>

which we removed from above overridden tpl....
You can also remove it using below function in your theme template.php
function YOURTHEME_preprocess_search_result(&$variables) {
  $variables['info'] = '';
}

Comment: Pay attention that there're 2 templates relevant to the search results page 'search-result.tpl.php' and 'search-results.tpl.php' :) one for the page and one for each result.
Comment: I have clearly mentioned search-result.tpl.php .. I don't get the point out of above comment... Is it pointed to OP ?
Comment: Yes, and for other readers as well. It may be handy so I thought to mention it.
Comment: +1 for helpful answer. Any idea how to override/theme the default page title and move the search box on the results page? I'd rather have the heading "Search Results" be more prominent.

How to theme D7 search results


A book on solved Probability problems

Question: I was looking for a book to practice Probability problems with solutions to get intuition of Probability and I see Schaum's series is kind of most respected on solved problems.  But I wonder which on is good out of so many Schaum'e Series on Probability
Comment: It is probably (pun intended) heretical to say on stats.SE that if your goal is to learn _probability_, you should avoid any book with "Statistics" or "Probability and Statistics" in its title; stick with "Probability" alone, preferably without qualifiers such as "for engineers and scientists" or "econometrics and finance".  That being said, I have always been partial to Hsu's "Probability, Random Variables, and Random Processes" in the Schaum's Outline Series.
Comment: Graduate level: https://www.amazon.com/Exercises-Probability-Grimmett-Stirzaker-Publisher/dp/B00BG70UDS
Comment: https://researchportal.hw.ac.uk/en/publications/problems-and-exercises-in-probability-theory Problems and exercises in probability theory
Serguei Foss, D. Korshunov, I. Asymont
Answer: Mosteller's Fifty Challenging Problems in Probability with Solutions though it's more recreational type problems than exercises.
Answer: An Introduction to Probability Theory and its Applications Volume 1 by William Feller
http://libgen.io/search.php?req=feller+volume+1&lg_topic=libgen&open=0&view=simple&res=25&phrase=1&column=def

A book on solved Probability problems


Creating a tar file with checksums included

Question: Here's my problem : I need to archive to tar files a lot ( up to 60 TB) of big files (usually 30 to 40 GB each). I would like to make checksums ( md5, sha1, whatever) of these files before archiving; however not reading every file twice (once for checksumming, twice for tar'ing) is more or less a necessity to achieve a very high archiving performance (LTO-4 wants 120 MB/s sustained, and the backup window is limited).
So I'd need some way to read a file, feeding a checksumming tool on one side, and building a tar to tape on the other side, something along :
tar cf - files | tee tarfile.tar | md5sum -

Except that I don't want the checksum of the whole archive (this sample shell code does just this) but a checksum for each individual file in the archive.
I've studied GNU tar, Pax, Star options. I've looked at the source from Archive::Tar. I see no obvious way to achieve this. It looks like I'll have to hand-build something in C or similar to achieve what I need. Perl/Python/etc simply won't cut it performance-wise, and the various tar programs miss the necessary "plugin architecture". Does anyone know of any existing solution to this before I start code-churning ?
Comment: Certainly sounds like a useful addition to `tar` if you decide to write it ;)
Comment: Not your question, but with `7z` you can choose the hash and print it in a way that `sha1sum` and `sha256sum` can understand: http://7zip.bugaco.com/7zip/7zip_15_09/MANUAL/cmdline/commands/hash.htm (and http://www.sami-lehtinen.net/blog/using-7-zip-hashing-to-compare-directories-and-files )
Try it: `7z h -scrcsha256 mydir/* | sed --regexp-extended 's, +[0-9]+ +,  ,g' > mydir.sha256sum ; sha256sum -c mydir.sha256sum` (tested with p7zip Version 15.09 beta)
Answer: Before going ahead and rewriting tar, you may want to profile the quick-and-easy method of reading the data twice, as it may not be much slower than doing it in one pass.
The two pass method is implented here:
http://www.g-loaded.eu/2007/12/01/veritar-verify-checksums-of-files-within-a-tar-archive/
with the one-liner:
  tar -cvpf mybackup.tar myfiles/| xargs -I '{}' sh -c "test -f '{}' &&
  md5sum '{}'" | tee mybackup.md5

While its true that md5sum is reading each file from disk in parallel with tar, instead of getting the data streamed through the pipe, Linux disk cacheing should make this second read a simple read from a memory buffer, which shouldn't really be slower than a stdin read. You just need to make sure you have enough space in your disk cache to store enough of each file that the 2nd reader is always reading from the cache and not getting far enough behind to have to retrieve from disk
Comment: It actually works quite fine, it looks limited by the CPU ability to crunch md5 ( ~280MB/s on one core).
Answer: Here's an example Python script. It calculates the checksum of the file as its being added to the archive. At the end of the script, the checksum file is added to the archive.
import hashlib,os
import tarfile
def md5(filename):
    ''' function to get md5 of file '''
    d = hashlib.md5()
    try:
        d.update(open(filename).read())
    except Exception,e:
        print e
    else:
        return d.hexdigest()

root="/home"
outtar=os.path.join(root,"path1","output.tar")
path = os.path.join(root,"path1")
chksum_file=os.path.join(root,"path","chksum.txt")
tar = tarfile.open(outtar, "w")
o_chksum=open(chksum_file,"w")
for r,d,f in os.walk(path):
    for files in f:
        filename=os.path.join(r,files)
        digest="%s:%s"%(md5(filename) , filename)
        o_chksum.write(digest+"\n")
        tar.add(os.path.join(r,files))

tar.add(chksum_file)
tar.close()
o_chksum.close()

When you untar, use the chksum_file to verify the checksum
Comment: Yes that's something like this that I thought about, but usually these sort of libraries load the file in RAM before manipulating it, and my files are at least 20 GB....
Answer: I think that your problem is a design issue of tar as tar does not allow random access/positioning inside the archive file via a content table, thus all protocols will be file and not buffer based.
Thus you may look at different formats like PAX or DAR which allow random access.
Comment: Unfortunately the tar output is mandatory, because it's what the workflow is based upon.
Answer: Recent archives formats generally include some hash for file verification, but they have a similar issue: you can't always choose your own hashing function, nor keep a local copy of the hashes.
You might want to save a local copy of the hashes, distinct from the one embedded in the archive itself: for instance if the archive is stored offline (on tapes or a data centre which is expensive to read from) and you want to verify a local copy of a file/directory.
7zip has several options like 7z h with custom hash and 7z l -slt to list all hashes and whatnot but what if you want a list of md5 or sha1 hashes? You can use -bb and -bs to control verbosity and reuse the George Notaras method mentioned in the accepted answer:
7z a -bsp1 -bb3 dir.7z dir 2>&1 \
| grep "^+" | sed 's,^+ ,,g' | xargs -d "\n" -I § -P 1 sh -c "test -f '§' && sha1sum '§'" \
| tee dir.sha1


Scope received in directive is not the same as the scope where directive really lives

Question: I have this directive, which basically attaches a file to a model through file-model="..." (the entire purpose of this directive is because ng-model doesn't work in <input type="file"> in angularjs)
angular.module('myApp').directive('fileModel', ['$parse', function ($parse) {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {

            console.log(scope); // DEBUG

            var model = $parse(attrs.fileModel);

            element.bind('change', function() {
                scope.$apply(function() {
                    model.assign(scope, element[0].files[0]);
                });

                if (attrs.ngChange) {
                    scope.$apply(attrs.ngChange);
                }
            });
        }
    };
}]);

And I also have a bootstrap-ui modal, modal.html:

        <input type="file" file-model="excelFile" ng-model="dummy" ng-change="uploadFile()" />

With its corresponding bootstrap-ui controller:
angular.module('myApp').controller('modalController', ['$scope', '$modalInstance', '$scope', function ($scope, $modalInstance, $scope) {

    $scope.uploadFile = function() {
        console.log($scope); // DEBUG

        var formData = new FormData();
        formData.append('file', $scope.excelFile); // empty!

        ...
    };
}]);

I invoke the modal from another controller like this:
$scope.openModal = function () {

    var modalScope = $scope.$new();

    modalScope.somePassedData = "I pass data this way";

    var modalInstance = $modal.open({
        templateUrl: 'views/modal.html',
        controller: 'modalController',
        scope: modalScope,
    });

    ...
};

So... if you notice the three comments:

First comment // DEBUG
Second comment // DEBUG
Comment // empty!

It seems that the scope used by the directive is not the same as the scope where the <input type="file"> is living, and because of this I'm getting an empty file.
What am I doing wrong with scopes?
Also I should mention that this worked fine without using bootstrap ui-modal... so it must have something to do with the scope of the modal
Comment: The answer is here: `var modalScope = $scope.$new();`. `$scope.$new()` creates a new child scope that inherits from `$scope`. So anything in `$scope` should be in `modalScope` too. But you are saying that you "invoke the modal from another controller". Controllers have isolated scopes, so most likely `$scope.excelFile` is in another scope than `modalScope`, right?
Comment: You've seen [this related SO post](http://stackoverflow.com/questions/18716113/scope-issue-in-angularjs-using-angularui-bootstrap-modal?rq=1) right, and you tried to initialize `$scope.input={}` and it didn't work?
Comment: Sorry I'm not following you... but I did tried to initialize $scope.excelFile in the scope of the modal
Comment: I read the link and it is not the case in here, because the passed scope is already initialized. The second "// DEBUG" is throwing a different scope from the first "// DEBUG". So my problem is not a null or undefined scope but a different one.
Answer: Two things to test:

Verify that your uploadFile function is called after your directive's event handler (since they are listening to the same event). If it isn't, you should increase the priority of your fileModel directive to be greater than that of ngChange (which is 0).
Try using the resolve property to pass in data to your modal instead of creating a new scope. According to the documentation, $modal creates a child scope of the one you pass in, so you may be running into the prototypal inheritance issue with your primitive value.
Comment: Regarding (1): all the directive code is being called before the uploadFile() method (checked). Regarding (2): Hmm i will try, even though for all my modals in the past I have been passing a new scope from the parent


strange predicted values from LOESS model

Question: I am trying to predict density function using LOESS in R. However, the predicted values I got are not in the estimated LOESS line.
#Generate data
n<-10000
a1<-a2<-0.1
a3<-a4<-0.2
a0<-0.1

u1 <-rnorm(n,0,1)
u2 <-runif(n,0,1)
u3 <-rbinom(n,1,0.5)
u4 <-rpois(n,5)

lambda<-exp(a0+a1*u1+a2*u2+a3*u3+a4*u4)

###Compute the density of the variable
x<-lambda
dens<-density(x,bw=0.15,na.rm=TRUE)
gr <- data.frame(with(dens, x), as.vector(dens$y))
names(gr)<-c("xgr","ygr")

###Use loess to smooth the density function
y.loess <- loess(ygr~xgr, data=gr)

###Predict the density using the data
pred.y <- predict(y.loess, newdata=data.frame(xgr=x))

###Plot results
plot(dens,col=1)
###Add loess lines
lines(y.loess,col=2,lty=2)
###add new predictions onto the plots and they are not on the LOESS line!
points(x,pred.y,col=3)

This is really driving me crazy. Any help will be appreciated.
Comment: Check the `span` of your `loess`.... (I will write a proper answer soon)
Answer: I believe you have the correct idea but unfortunately you are "betrayed" by the default span values used by loess. Please see the following code example amending your original version:
set.seed(123) ;     n<-10000
a1<-a2<-0.1 ;      a3<-a4<-0.2;     a0<-0.1

u1 <-rnorm(n,0,1)
u2 <-runif(n,0,1)
u3 <-rbinom(n,1,0.5)
u4 <-rpois(n,5)
lambda<-exp(a0+a1*u1+a2*u2+a3*u3+a4*u4)

###Compute the density of the variable
x<-(lambda)
dens<-density(x,bw=0.15,na.rm=TRUE)
gr <- data.frame(with(dens, x), as.vector(dens$y))
names(gr)<-c("xgr","ygr")

###Use loess to smooth the density function
yLoess <- loess(ygr~xgr, data=gr,span=0.1)
yLoess0 <- loess(ygr~xgr, data=gr)

###Predict the density using the data
predY <- predict(yLoess, newdata=data.frame(xgr=x))
predY0 <- predict(yLoess0, newdata=data.frame(xgr=x))
###Plot results
plot(dens,col=1)
###Add loess lines
lines(yLoess,col=2,lty=2)
###add new predictions onto the plots
points(x,predY0,col='green') # We clearly oversmooth
points(x,predY,col='blue')   # Much better :)

In general when your smoothed estimates show some kind of unwanted inertia, for example in your case: density estimates having repeated negative values, it hints that the smoothing bandwidth/window/span is larger than what you would probably like.
(By the way, try to avoid using dots (.) in variable names. It is a relic from the past. Within R dots (.) can mean nothing or they can mean simple methods dispatches (e.g. data.frame (dot means  nothing), print.lm (dot means method dispatch)); this can be confusing for someone reading your code.
In addition if at some point you decide to write C/C++ (the standard low-level language to connect to R) you will find out that : 1. dots in names are not allowed, 2. to access individual members of a structure, the dot operator is used, i.e. you will have to change your naming convention. Keep it simple and use the same naming convention everywhere. :) )


Impact on changing the data type from char to varchar2

Question: Can anyone tell me will there be any impact on changing the datatype of a column from char to varchar2.
Because the issue i am facing is when i fire a select query i.e
select * from table_name where column_name in ('X','Y','Z');

The above query is returning only few rows. And recently the column_name data type was changed from char to varchar. The rows returned are the rows after the data type was changed.
Comment: that depends on your database system, the amount of data, the type of queries and the type of index you are using.
Answer: A varchar2 datatype, when stored in a database , uses only the space allocated to
it. If you have a varchar2(100) and put 50 bytes in the table, it will use 52 bytes
(leading length byte).
A char datatype, when stored in a database table, always uses the maximum length and is
blank padded.  If you have char(100) and put 50 bytes into it, it will consume 102
bytes.
So in your case probably its only giving the rows from the space allocated to varchar and hence only few rows are returned i believe.
Refered from : http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:1542606219593
Comment: Thank you so much, found the same reason at http://www.oratable.com/char-varchar-difference/ as well. Could you please tell me how to select all the rows tried doing rpad(value,numberofbytes) but it's returning only the rows which were inserted when the datatype of the column was char.


Best way to store what type of possible classes are available?

Question: Currently I'm doing this:
public static class IngredientDataStorage
{

    public static List<Ingredient> GetIngredientList()
    {
    List<Ingredient> availIngredientsList = new List<Ingredient>()
       {
        new Butter(), new Cinnamon(), new Chocolate()
       };
    return availIngredientsList;
    }

   public static Dictionary<int, Ingredient> GetIngredientDictionary()
    {
       Dictionary<int, Ingredient> availIngDict = new Dictionary<int, Ingredient>()
      {
       {3, new Chocolate() },
       {2, new Butter() },
       {4, new Cinnamon() }
      };
      return availIngDict;
   }

public static List<int> GetIDList()
  {
    var IDList = new List<int>();
    foreach (Ingredient ingredient in GetIngredientList())
    {
        IDList.Add(ingredient.ID);
    }
    return IDList;
   }

public static void PrintAvailIngredients()
  {
    List<Ingredient> ingredientList = IngredientDataStorage.GetIngredientList();

    foreach (Ingredient ingredient in ingredientList)
    {
        ingredient.PrintInfo();
    }
  }
}

Is there a better way to store data about what available ingredients there are than doing something like this? In this case I have 3 ingredients - butter, cinnamon, and chocolate. I store them in a list here, a dictionary here, and also have a method to give the IDs of these objects as well as to print out all the ingredients to the console.
Answer: The main principle to apply is that for a given type of change, you want to only need to change one part of your code. Google "Single Responsibility Principle" and "Open/Closed Principle." Your list could probably be derived from your dictionary, or vice versa, for example, to avoid duplication (although as your code stands, there doesn't appear to be any correlation between the order of items in your list, the order of items in the dictionary, or the order of the IDs associated with those values--is that on purpose?).
There are a lot of ways to approach this, and which one works best will depend largely on what this will be used for, and the likely reasons for change in your code. For example:

Consider how you want ID values to be represented. What happens if two different developers are adding new Ingredient classes at the same time, and end up using the same ID value.
Consider using reflection to scan your entire assembly for ingredients, so adding a new class is all that's required to add an ingredient to your data structures.
If the different ingredients only have different values for their properties, they probably shouldn't be separate classes at all. You can just have a list of Ingredients declared somewhere, with each one assigned an ID, a Name, etc.
If the code doesn't need to do anything different depending on which specific ingredients are used, you may want to store that list in a database or a file somewhere rather than in the code itself.
If the IDs need to be persistent, you'll need to use a storage mechanism that keeps the ID values consistent. If they don't, you could assign a unique ID value when you read/scan the different ingredient options, and avoid assigning each one an explicit number in your code or data store.
Comment: [Reflection](https://learn.microsoft.com/en-us/dotnet/framework/reflection-and-codedom/reflection) allows you to write code that inspects things like classes, properties, and methods, at runtime. So you could write a simple LINQ query, for example, that gives you all the classes that implement a certain interface, or which have a certain custom attribute on them. Then you can call the constructors of those classes to create instances of them.
Comment: That makes a lot of sense! What is reflection?


To output the closing price, total dividends of each year from a time-series dataframe

Question: My dataframe look like this:
            Open   High    Low  Close    Volume  Dividends  Stock Splits
Date
2015-08-07  16.64  16.64  16.64  16.64         0        0.0             0
2015-08-11  16.51  16.59  16.14  16.16  11408900        0.0             0
2015-08-12  15.88  15.88  15.16  15.27  24258500        0.0             0
2015-08-13  15.33  15.69  15.33  15.58   8237600        0.0             0
2015-08-14  15.59  15.83  15.59  15.78   4399600        0.0             0
...           ...    ...    ...    ...       ...        ...           ...

2020-08-03  19.75  19.75  19.45  19.45   7352600        0.0             0
2020-08-04  19.70  19.99  19.64  19.69   4250500        0.0             0
2020-08-05  19.87  19.98  19.59  19.83   3414080        0.0             0
2020-08-06  20.11  20.56  20.02  20.40   6128100        0.0             0
2020-08-07  20.52  20.69  20.40  20.60   8295000        0.0             0

I like to select the closing price of each year and also calculate the average "Volume" and Total Dividends for the year.
The output to like this:
2015  20.52...

2016  21.53...

2017  25.33...

....

Any help would be very much appreciated. Thanks!
Answer: It's just a simple case of use resample() then define which aggregates you want from the columns.
import yfinance as yf
import pandas as pd
import datetime as dt
end=dt.datetime.today()
start=end-dt.timedelta(59)
tickers=['WBA']

df = yf.download(tickers,group_by=tickers,start=start,end=end,interval='5m')
print(df.resample("Y").agg({"Volume":"mean","Close":"last"}).to_string())

output
                                Volume  Close
Datetime
2020-12-31 00:00:00-05:00  72404.45197  41.52


Hyper-V VM doesn't boot off SCSI hard drive

Question: I've converted a VMWare VMDK to a VHDX. The guest is a Windows 8.1 VM.
When this is attached to a generation-1 Hyper-V VM as an IDE drive, it boots up fine.
When the same VHDX is attached to a generation 2 Hyper-V VM (forced to use SCSI), it fails to boot off the same disk (checked boot order, it fails disk and hits CDROM and network).
The Hyper-V host is a Windows Server 2012 R2 (+updates/patches).
Does anyone know how to get this working as a generation 2 Hyper-V VM. I'm hoping it's not a limitation that I must use IDE (flashback 90s) in order to order to do something as basic as ... boot!
Comment: Despite age, this is one of first results for this task. It is doable, and is actually tied to BIOS vs (U)EFI. While MS offered scripts for Windows guests, only way to do it for Linux guests is to do it manually. For more info please see this question: https://serverfault.com/questions/654828/convert-hyper-v-linux-machine-to-gen-2
Answer: You can't just take a boot disk from a generation 1 guest and have it boot in a generation 2 guest. Your generation 1 disk is likely still using the MBR, your generation 2 disk requires an GPT/EFI partition or converted to GPT/UEFI to boot.
There are some documented manual and scripted methods to convert the virtual machine from generation 1 to generation 2, however these methods would be used at your own risk.
The first link from the manual method is actually from a series of articles on generation 1/generation 2 virtual machines and is a good read.

There is no way in Hyper-V to change the generation of a virtual
  machine. Neither is there a means to migrate a generation 1 virtual
  machine to a generation 2 virtual machine.
However, there is a longer answer which is supported in certain
  circumstances, due to the use of standard inbox tools and capabilities
  for deployment. Let's rule out first what definitely cannot be
  migrated. The obvious categories are any virtual machine running a
  32-bit guest operating system; any virtual machine not running Windows
  (although there may be other solutions I'm not aware of); any virtual
  machine running a version of Windows prior to Windows 8/Windows Server
  2012.
At a high level, the steps I'm going to follow are:

Disable the recovery environment
Make a copy of the Windows image as installed
Create a new VHDX
Partition it in GPT format and make it bootable
Put the copy of Windows we previously made onto the new disk
Create a new generation 2 virtual machine and attach the new VHDX
Fix up the recovery environment
Comment: To confirm, the `Convert-VMGeneration` script referenced in your answer DID solve my issue. Thanks.


Why Should We Standardize Regression Variables?

Question: Many textbooks and articles (such as this one) advise to standardize variables before entering them into our regression models; i.e., (variable - mean) / standard deviation
However, I just came across a counter example. How do you rationalize this?
Let's say:
$$Y = 2X$$
$$X = \{-3, -2, -1, 0, 1, 2, 3 \}$$
$$Y = \{-6, -4, -2, 0, 2, 4, 6 \}$$
After standardizing,
$$X_{sd} = \{-1.3887301, -0.9258201, -0.46291,  0.0,  0.46291,  0.9258201,  1.3887301 \}$$
$$Y_{sd} = \{-1.3887301, -0.9258201, -0.46291,  0.0,  0.46291,  0.9258201,  1.3887301 \}$$
$$\Rightarrow Y_{sd} = X_{sd}$$
So, in this example, if we standardize the variables, the desired slope (i.e., the effect size) vanishes!!!
Comment: No slope coefficient will have units of y / units of this x if you standardize this x or y or both. I never standardise. I do sometimes shift predictors, for example intercept and slope if calendar year is a predictor are often absurd so use instead say year $-$ 2000 (or some other convenient year within the data range).
Comment: Many similar questions, some: https://stats.stackexchange.com/questions/48360/is-standardization-needed-before-fitting-logistic-regression, https://stats.stackexchange.com/questions/287370/standardization-vs-normalization-for-lasso-ridge-regression, https://stats.stackexchange.com/questions/223432/standardising-non-normally-distributed-predictors-for-regression, https://stats.stackexchange.com/questions/99761/do-you-ever-center-and-standardize-variables-in-multiple-regression, https://stats.stackexchange.com/questions/342140/standardization-of-continuous-variables-in-binary-logistic-regression
Answer: The article you are referring (correctly) advises to center covariates involving higher order polynomal terms or interactions. The reason is simple: it reduces collinearity across related terms and thus improves stability of coefficient estimates and their interpretation.
Your example does not make much sense because $Y$ seems to be the response variable. Any transformation on the response changes the result, including standardization.
Comment: Not all covariates. But those involving interactions and polynomial terms are candidates for centering.
Comment: So, you mean we should only standardize the covariates and not the response variable, right? That makes sense, thank you.
Answer: If you transform the target variable, you would need to back-transform the predictions to get the predicted values on the appropriate scale. Since linear regression is a linear model, in your example this is the same as transforming the $\beta$ parameter.
<code>> x <- c(-3,-2,-1,0,1,2,3)
> y <- 2 * x
> xz <- x / sd(x)
> yz <- y / sd(y)
> lm(yz~xz)

Call:
lm(formula = yz ~ xz)

Coefficients:
(Intercept)           xz
          0            1

> predict(lm(yz~xz)) * sd(y)
 1  2  3  4  5  6  7
-6 -4 -2  0  2  4  6
> coef(lm(yz~xz))[2] * sd(y) * xz
[1] -6 -4 -2  0  2  4  6
</code>
So nothing is wrong, you scaled the data and got the scaled parameters and predictions.
You don't need to standardize the data by default. There are scenarios when you would need to do this, e.g. using polynomials, as mentioned in the linked post, or when using regularization, or for some models other than linear regression.


Prove that $g$ is also continuous at $x=0$.

Question:
Let $f:\mathbb{R} \to \mathbb{R}$ be such that $f$ is continuous at $x=0$. For any $r\in\mathbb{R}$, define $g(x) = f(rx)\;\forall x \in \mathbb{R}$. Prove that $g$ is also continuous at $x=0$.

Proof:
If $f(x)$ is continuous at $x=0$, then
$$\forall \epsilon\;\exists \delta\; s.t\;|x-0|<\delta \implies |f(x)-f(0)|<\epsilon$$
Let $x = ry$.
$$\forall \epsilon\;\exists \delta\; s.t\;|ry-0|<\delta \implies |f(ry)-f(0)|<\epsilon$$
$$\therefore g(y)=f(ry) \text{ is continuous at } y=0.$$
Is this proof correct ? If not please explain how to prove the result.
Comment: You have the right idea, although normally, we would say something like, for any $y$ such that $|y| < \delta/r$, then $g(y) = f(ry)$ satisfies $|g(y) - g(0)| = |f(ry)-f(0)| < \varepsilon$.
Comment: If you do not insist on "$\epsilon - \delta$", then more simple is use concept of composition of 2 continuous functions.
Answer: No, it is not correct. You did not prove that there is a $\delta>0$ such that $|x|<\delta\implies|g(x)-g(0)|<\varepsilon$.
If $r=0$, then the statement is trivial. Otherwise, given $\varepsilon>0$, take $\eta>0$ such that $|x|<\eta\implies|f(x)-f(0)|<\varepsilon$. Let $\delta=\frac\eta{|r|}$. Then\begin{align}|x|<\delta&\iff|rx|<\eta\\&\implies|f(rx)-f(0)|<\varepsilon\\&\iff|g(x)-g(0)|<\varepsilon.\end{align}


Asp.Net Razor com Json

Question: tenho uma duvida e já pesquisei em diversos sites mas não obtive a resposta. Desenvolvo sistemas em .Net com C# no padrão MVC e utilizo a apresentação na tela na forma tradicional View com Razor.
Acontece que tenho percebido que vários sistemas web disponibilizados ultimamente tem apresentado cada vez mais uma experiencia ao usuário igual a uma aplicação Desktop, ou seja, com quase nada de Reloads por requisição e uma maior interatividade com os eventos dos campos.
Muitos destes sistemas utilizam Knockout, Vue, Aurelia e principalmente AngularX em suas Views, ou melhor, utilizam somente o MC e o V fica por conta de outra tecnologia.
Agora vem a minha questão, como não domino nenhuma destas tecnologias (ainda), com a experiencia de vocês, qual seria a melhor forma para trabalhar com as Views de tal forma que eu conseguisse criar as sistemas com uma experiencia ao usuário mais próxima das fornecidas pelas tecnologias citadas anteriormente mantendo omeu padrão de desenvolvimento MVC com Razor? Pelo poder que as Views geradas com Razor oferece, muito provavelmente eu não devo estar utilizando algum recurso que esta ferramenta possa disponibilizar?! - Pelo que pude observar uma das coisas que "devo"
trabalhar para chegar no resultado esperado é trabalhar com Json (até ai tudo bem) como se a minha aplicação fosse uma Web API - estou certo?
Espero ter sido claro na apresentação da minha duvida.
Desde já agradeço pela força!
Comment: Se o que você quer é só que partes do seu sistema seja assíncronos, você pode pesquisar por partial view, ajax forms ou a sugestão do Cigano mesmo...
Comment: Aline, obrigado pelas dicas. Quando você diz ajax forms é o mesmo que Ajax.BeginFor() ? se sim , vc acredita que este pode resolver em grande partes os meus questionamentos?
Comment: Se forem só partes do sistema que tu quer enviar dados ou manipular se forma assíncrona, vai funcionar sim.
Answer:
Pelo que pude observar uma das coisas que "devo" trabalhar para chegar no resultado esperado é trabalhar com Json (até ai tudo bem) como se a minha aplicação fosse uma Web API - estou certo?

Melhor ainda: trabalhar com a Web API propriamente dita. A Web API surgiu exatamente na sua constatação: como fazer o sistema MVC trabalhar sem depender da camada de apresentação?

qual seria a melhor forma para trabalhar com as Views de tal forma que eu conseguisse criar as sistemas com uma experiencia ao usuário mais próxima das fornecidas pelas tecnologias citadas anteriormente mantendo omeu padrão de desenvolvimento MVC com Razor?

Primeiro, desenvolvendo os métodos que respondam à nova camada de apresentação dentro do próprio sistema MVC. Depois, migrando essa estrutura para um sistema puramente em Web API. Eu tenho um curso que explica como fazer isso, se estiver interessado (a ementa é a mesma).
Ou seja, dado um método que normalmente devolve uma View:
public ActionResult DevolveView()
{
    ...
    return View(objetos);
}

Você faz uma cópia deste método de forma a devolver um JSON estruturado:
public JsonResult DevolveView()
{
    ...
    return Json(objetos, JsonRequestBehavior.AllowGet);
}

E depois cria um Controller em separado para estes novos métodos usando JSON:
public MeuControllerApi : ApiController
{
    public IHttpActionResult DevolveView()
    {
        ...
        return Ok(objetos);
    }
}

Isso é apenas uma sugestão. O ideal é fazer um tutorial mais denso para compreender como essa migração funciona.
Comment: Cigano, agradeço pelas respostas dos meus questionamentos. Com relação aos seus exemplos ficou muito claro como devo servir a view, o meu problema é exatamente em como apresentar uma View utilizando Razor e obtendo o retorno em Json? Sei que JQuery é capaz de me ajudar, mas até onde pude entender o retorno "data" não preenche diretamente os inputs da View. Falo muito em View com Razor , pois atualmente é o que mais conheço dentro do cenário .Net MVC. Com relação ao seu curso, o mesmo é apresentado em video ou somente em livro? Acho que uso pouco do poder do Razor e o seu livro pode me ajudar!
Comment: Sobre sua primeira pergunta, você precisa usar um *framework* mais robusto que o jQuery para conseguir. Minhas sugestões são Aurelia, React e Angular 2, nesta ordem.
Comment: Sobre meu curso, as aulas são feitas por *hangouts* e gravadas em vídeo por mim. O aluno fica com uma cópia para assistir quando quiser. Há o livro que serve como material de apoio ao conteúdo apresentado em *hangout*. O curso ajuda sim bastante no uso do Razor.
Comment: Olá Cigano, pelo visto para conseguir oque desejo não tem outra saída a não ser partir para um Framework MVVM, mas estes frameworks não faz com que eu deixe de utilizar uma view com Razor? Outra coisa, considerando a ordem apresentada na sua ultima resposta, devo iniciar com o Aurélia? mais uma vez muito obrigado pela força!!!
Comment: Cigano, com relação ao seu curso, consigo todas as informações no link http://www.codingcraft.com.br - Preço, prazo de pagamento entre outros?
Comment: "Olá Cigano, pelo visto para conseguir oque desejo não tem outra saída a não ser partir para um Framework MVVM, mas estes frameworks não faz com que eu deixe de utilizar uma view com Razor?", exatamente. Você passa a não ter geração de HTML pelo servidor. Tudo o que o servidor gera é JSON e o JavaScript do browser interpreta esse JSON para gerar um resultado dinâmico em tela.
Comment: "Outra coisa, considerando a ordem apresentada na sua ultima resposta, devo iniciar com o Aurélia?" Sim.
Comment: Sobre o curso, vamos continuar o contato por e-mail, Facebook ou Twitter. Veja meu perfil com todas as possibilidades de contato que tenho. De qualquer forma, sim, o preço e o prazo de pagamento são os mesmos do link.

Asp.Net Razor com Json


Why do curlers have a stopwatch?

Question: Watching curling, I often see the sweeper seem to start a stopwatch before starting to sweep.
I doesn't seem to make sense that you need a stopwatch in curling. There's no difference whether the stone gets there in 10 or 15 seconds.
What is the use of the stopwatch?
Answer: I think you are seeing them stop, not start the stopwatch.  They are timing how long it takes from the back line to the first hog line.  This time can be compared to previous throws to see if the rock will be heavy or light.
If the time is long (rock is underthrown), they can get on the brooms immediately and try to stretch it.
Answer: Curling teams receive a specific allotment of thinking time (term used in rules) to complete the delivery of their stones.
World Curling Federation handles the timing of games in section C6. Each team is given 38 minutes for its ten ends, or  30 minutes for its eight ends, with alternative times for wheelchair or mixed doubles, and additional time for extra ends.
A team's clock runs from the instant all stones have stopped moving or left play during their opponent's previous stone, any violations have been corrected, and the opposing team have moved off the playing area or house. It stops when their own current stone passes the tee line.
Since each team uses eight stones, a ten-end game allows 28.5 seconds per stone. Teams may desire more thinking time left towards the last stone of an end or the last end of a game, so tracking is important, especially as a team must forfeit if their ends are not completed in their time.
Comment: Hmm. It could be that yes; but in the olympics there's a huge clock behind them telling them how much thinking time they have left. Old habits maybe?
Comment: There are teams in every sport that run their own clocks despite perfect timing displayed in several places around the venue. Sometimes the official clock counts the wrong direction, sometimes they have it for a specific system of player workload management. I see no reason these would be any exception.
Comment: The only timing that counts is the official. The players sweeping time only the speed of the stone as @BowlOfRed described. There are of course various reasons the official timing might not be accurate and has to be corrected, but this is a different story. The timing the OP has asked for is solely for determining how far the stone will travel.

Why do curlers have a stopwatch?


How to update a field in Drupal 7 without saving whole node

Question: I wanted to update a field that is not seen by the user, but I would turn off and on (boolean) quite a lot (and for thousands of nodes). I initially used field_attach, but this had the unhappy effect of removing a file that was also attached to the node (this is a drupal bug).
It took a lot of searching, but I found the solution combining a couple of other peoples snippets. I put it below so hopefully may save someone some time.
For the record: Apparently it is bad practice to edit fields directly like this, however, I really needed to for this use case and I have yet to find any issues. You have been warned!
Comment: See my answer here https://drupal.stackexchange.com/a/99846/6309
Answer: function common_update_db($entity_id, $field_name, $value, $clear_cache) {
  foreach (array('data', 'revision') as $table) {
    $result = db_update('field_'.$table.'_'.$field_name)
        ->fields(array(
            $field_name.'_value' => $value,
        ))
        ->condition('entity_id',$entity_id,'=')
        ->execute();
  }
  if ($clear_cache) {
    cache_clear_all("field:node:" . $entity_id, 'cache_field');
  }
}

This will update the field and the revision field. If you send clear_cache = TRUE, it will also clear that nodes cache. This only works for *_value fields and nodes, but it's easy to modify.
Examples:
common_update_db(1234, field_run_cron, 1, TRUE);

on node 1234, set field_run_cron value to 1 and clear the cache for immediate visible effect to the user.
common_update_db(1234, field_run_cron, 0, FALSE);

on node 1234, set field_run_cron value to 0, don't clear cache as the user doesn't see this field anyway.
Comment: Thank you - this solution worked for me. I know you're not *supposed* to update a node's field in this way, but I haven't noticed any negative effects yet and node_save() is just not an option when dealing with > 1000 nodes.


Como pegar os pontos de um círculo através de um ângulo em um plano cartesiano?

Question: Imagine um circulo com raio de 5 no plano cartesiano.
Por analogia eu já sei os ângulos seguintes:
0° (ou 360°): (x =  5, y =  0)
90°         : (x =  0, y =  5)
180°        : (x = -5, y =  0)
270°        : (x =  0, y = -5)

Assumindo que o centro é x=0 e y=0, é claro.
Eu gostaria de uma equação onde é possível descobrir o x e y apenas através de um ângulo qualquer.
Comment: Problemas envolvendo matemática são interessantes, mas eles precisam estar envolvidos no escopo de alguma programação. No seu caso, me parece apenas uma questão de matemática comum.
Comment: É realmente uma questão matemática, mas será utilizada em um software com canvas 3D.
Comment: Então seria necessário mostrar na pergunta o código envolvido bem como a linguagem utilizada.
Comment: Minha pergunta é somente relacionada à matemática. Eu não consegui encontrar essa equação no google. Consegui apenas encontrar coisas relacionadas diretamente ao arco da circunferencia o que não é util para mim. Posso passar o link do projeto, mas minha dúvida é completamente matemática.
Comment: Eu recomendaria ajustar a pergunta para que ela tenha uma cara de programação e não de matemática. Assim vc tem chances de obter uma resposta. Da forma que está ela provavelmente será fechada por estar fora do escopo do site.
Comment: A comunidade de programadores já foi muito mais amigável. Eu postei essa pergunta, como você diz "com cara de programação" [aqui](https://stackoverflow.com/questions/49833044/given-an-angle-how-can-i-get-x-and-y-position) e fui reprovado como se eu tivesse feito uma pergunta absurda, agora estou novamente sendo sensurado.

É assim tão difícil informar uma fórmula matemática para alguém que não sabe? =(

(sad)
Comment: É que o site trata de assuntos relacionados a programação, e não de matemática. Talvez exista algum site da rede Stack que trate de matemática. Dá uma pesquisada.
Comment: Tem esse aqui olha: https://math.stackexchange.com/
Comment: Isso de fato me ajuda! Vou postar essa mesma questão lá. Mesmo assim vou deixar esta aqui aberta, por enquanto. Quando tiver uma solução eu posto para responder aqui. Não é possível que eu seja o único que não sabe fazer isso. Obrigado, por enquanto.
Comment: Se conseguir lá posta aqui o link pra gente saber. Boa sorte!
Comment: O pessoal não fecha as coisas por maldade. Simplesmente cada rede da StackExchange tem escopos diferentes e por isso tratam problemas/perguntas diferentes. Logo tem de colocar a sua pergunta na rede certa sob pena de ser fechada abruptamente.
Comment: A pergunta da qual me referi esta no escopo certo. Em um escopo de programação com linguagem voltada a programação.
Comment: Diretamente da época dos computadores de 8-bit, considerando o centro do círculo como centro em (0,0), raio igual a 5 e ângulo em radianos -- X=0, Y=0, Raio=5 -- `X'=X+Raio×Seno(Angulo)` e `Y'=Y-Raio×Cosseno(Angulo)`
Comment: Só uma correção para ficar na sequência certa...é `X'=X+Raio×Cosseno(Angulo)` e `Y'=Y'+Raio*Seno(A)`
Comment: Obrigado Giovanni. Acredito que seja essa fórmula mesmo que estava procurando. Só mais uma coisa, no X' o apóstrofo significa algo matematicamente falando?
Answer: Depois de muito pesquisar aprendi como isso deve ser feito e também que muitas pessoas também tem essa mesma dúvida. Acredite ou não, apesar de ser algo simples e pura matemática de ensino fundamental é um conteúdo pouco comentado na internet, pelo menos foi a impressão que eu tive. Talvez as pessoas imaginam que seja algo tão simples que pressupõem que todo mundo já sabe assim como ninguém imagina que alguém possa não saber multiplicar... Enfim...
De qualquer forma a resposta é tal como o Giovanni Nunes mencionou. Segue código:
https://jsfiddle.net/s67Lmx1a/39/
var x = Math.cos(angulo * Math.PI / 180) * raio;
var y = Math.sin(angulo * Math.PI / 180) * raio;

Ps.: Multiplica-se o angulo por PI e divide por 180 para se obter os radianos desse angulo. Essa era a parte que faltava para meu código funcionar.
Comment: Para aquele aventureiro que vier a ler esta resposta, tenha sempre no coração a seguinte frase: exceto se especificado o contrário, a biblioteca matemática que você está usando trabalhará com **radianos**, dificilmente trabalhará com graus.


How to know the menu ID

Question: Like a function to debug a page or something. Want to add a link via links.yml but can't get the menu 'parent' name
Answer: You can use hook_menu_local_tasks() or hook_menu_local_task(). It is primary Tabs.
function mymodule_menu_local_tasks_alter(&$data, $router_item, $root_path) {
  foreach ($data['tabs'] as $key1 => $tabs) {
    foreach ($tabs['output'] as $key2 => $item) {
      // Conditionally change the link title.
      if ($item['#link']['path'] == 'some/path/here') {
        $data['tabs'][$key1]['output'][$key2]['#link']['title'] = 'New Title';
      }
    }
  }
}

Answer: What you're wanting is the route name, not menu parent name (it's changed since D7). You can retrieve a route name a couple of different ways:

Use Url::getRouteName() to look up your current route:
$path = \Drupal::service('path.current')->getPath();
$url = \Drupal\Core\Url::fromUri( 'internal:' . $path );
$url->getRouteName()
Use the Webprofiler module to look up the current route as you're viewing it.
Look up URL patterns in the router DB table.

To see how the core node module does it for the tasks in your screenshot look at core/modules/node/node.links.task.yml
For further information on adding local tasks to routes, read Providing module-defined local tasks.

How to know the menu ID


How to get DRBD to automatically start after reboot, mount volume, start service, and configure primary/secondary

Question: I have a great working version of DRBD across two Debian Stretch servers which I created by following this awesome guide:
https://www.howtoforge.com/setting-up-network-raid1-with-drbd-on-debian-squeeze-p2/
But after each reboot I have to redo a number of things to get it into a working state again.
Here is what I see when it's working, before reboot:
root@server1:~# cat /proc/drbd
version: 8.4.7 (api:1/proto:86-101)
srcversion: AC50E9301653907249B740E
 0: cs:Connected ro:Primary/Secondary ds:UpToDate/UpToDate C r-----
    ns:8 nr:0 dw:4 dr:1209 al:1 bm:0 lo:0 pe:0 ua:0 ap:0 ep:1 wo:f oos:0
On server 2:
root@server2:~# cat /proc/drbd
version: 8.4.7 (api:1/proto:86-101)
srcversion: AC50E9301653907249B740E
 0: cs:Connected ro:Secondary/Primary ds:UpToDate/UpToDate C r-----
    ns:0 nr:8 dw:8 dr:0 al:0 bm:0 lo:0 pe:0 ua:0 ap:0 ep:1 wo:f oos:0
On server 1:
root@server1:~# mount
...
/dev/drbd0 on /var/www type ext3 (rw,relatime,data=ordered)
And here is what I see after reboot. All is working but mounting, service start, and primary/secondary configurations is lost. I've tried to add drbd to the start by doing this:
update-rc.d drbd defaults
on both servers this doesn't seem to work. DRBD simply doesn't start but manually doing /etc/init.d/drdb start works fine on both servers.
Also I'm unsure if I can just add the DRBD volumes to fstab because surely it won't work if the DRBD service isn't even started? I've read about using _netdev in fstab but various combinations of fstab entries didn't work out.

Finally I also have to set the primary and secondary status of DRBD every time I restart and then remount the volume manually.
So this is how I am getting it working after reboot:
On server 1:
root@server1:/etc# /etc/init.d/drbd status
● drbd.service - LSB: Control DRBD resources.
   Loaded: loaded (/etc/init.d/drbd; generated; vendor preset: enabled)
   Active: inactive (dead)
     Docs: man:systemd-sysv-generator(8)
root@server1:/etc# /etc/init.d/drbd start
[ ok ] Starting drbd (via systemctl): drbd.service.
root@jmtest1:/etc# cat /proc/drbd
version: 8.4.7 (api:1/proto:86-101)
srcversion: AC50E9301653907249B740E
 0: cs:Connected ro:Secondary/Secondary ds:UpToDate/UpToDate C r-----
    ns:0 nr:0 dw:0 dr:0 al:0 bm:0 lo:0 pe:0 ua:0 ap:0 ep:1 wo:f oos:0
root@server1:/etc# drbdadm primary r0
root@server1:/etc# cat /proc/drbd
version: 8.4.7 (api:1/proto:86-101)
srcversion: AC50E9301653907249B740E
 0: cs:Connected ro:Primary/Secondary ds:UpToDate/UpToDate C r-----
    ns:0 nr:0 dw:0 dr:0 al:0 bm:0 lo:0 pe:0 ua:0 ap:0 ep:1 wo:f oos:0
On server 2:
root@server2:~# /etc/init.d/drbd status
● drbd.service - LSB: Control DRBD resources.
   Loaded: loaded (/etc/init.d/drbd; generated; vendor preset: enabled)
   Active: inactive (dead)
     Docs: man:systemd-sysv-generator(8)
root@server2:~# /etc/init.d/drbd start
[ ok ] Starting drbd (via systemctl): drbd.service.
root@server2:~# cat /proc/drbd
version: 8.4.7 (api:1/proto:86-101)
srcversion: AC50E9301653907249B740E
 0: cs:Connected ro:Secondary/Secondary ds:UpToDate/UpToDate C r-----
    ns:0 nr:0 dw:0 dr:0 al:0 bm:0 lo:0 pe:0 ua:0 ap:0 ep:1 wo:f oos:0
root@server2:~# drbdadm secondary r0
root@server2:~# cat /proc/drbd
version: 8.4.7 (api:1/proto:86-101)
srcversion: AC50E9301653907249B740E
 0: cs:Connected ro:Secondary/Primary ds:UpToDate/UpToDate C r-----
    ns:0 nr:0 dw:0 dr:0 al:0 bm:0 lo:0 pe:0 ua:0 ap:0 ep:1 wo:f oos:0
Some fstab entries that I tried:
/dev/drbd0 /var/www    ext3    _netdev     0   2
UUID=042cc2e395b2b32    /var/www    ext3    none,noauto 0   0
Not sure if you're supposed to use the UUID or just /dev/drbd0
I have these questions as to why it's not starting:

What FSTAB entries are supposed to be there?
Why does update-rc.d drbd defaults not work?
Why do I have to reset primary and secondary on both servers after each restart?
Answer: You should definitely consider using a product which is made for dealing with such problems.
I described in this post [ Nagios/Icinga: Don't show CRITICAL for DRBD partitions on standby node ] how I manage to do exactly what you expect using opensvc, and it works fine for years.

no need for fstab entries as mounts are described in the opensvc service configuration file, which is automatically synchronized between opensvc cluster nodes
no need to setup update-rc.d drbd defaults because opensvc stack is modprobing the drbd module when it sees that you have drbd resources in some services, and then brings up drbd in primary/secondary states
to reach primary/secondary at boot, just setup the nodes parameter in the DEFAULT section of the opensvc service configuration file.
If you want server1 as primary and server2 as secondary, just set nodes=server1 server2 using the command svcmgr -s mydrbdsvc set --kw DEFAULT.nodes="server1 server2"
if you only want the service to be started at boot on server1, set the orchestrate=start parameter using the command svcmgr -s mydrbdsvc set --kw DEFAULT.orchestrate=start
if you only want the service to be orchestrated in high availability mode (meaning automatic failover between nodes), set the orchestrate=ha parameter using the command svcmgr -s mydrbdsvc set --kw DEFAULT.orchestrate=ha
to relocate the service from one node to the other, you can use svcmgr -s mydrbdsvc switch command
Answer: There's a lot to unpack here, but I will start by saying: That DRBD version is old! You should upgrade it to either 8.4.11 (as of this writing, December 2018), or move to the 9 branch. But the questions you're asking can be solved with the version you're using.
Let's take a look at your three consice questions you posed at the bottom of your post:

What FSTAB entries are supposed to be there?

None, ideally. DRBD devices must first be promoted before they can be used. The fstab is not the best option even for DRBD-9 block devices that can autopromote, as in most cases it will trip up the boot process of things aren't all fine. But it can technically work with many caveats.

Why does update-rc.d drbd defaults not work?

Don't do it that way. Debian uses systemd, and DRBD has a systemd unit file. You should be using that UNLESS you're using a cluster manager, which I highly recommend. So in the absence of the Pacemaker cluster resource manager, you should be issuing things like # systemctl enable drbd to make it start at boot. Or # systemctl start drbd to start the service after it's stopped. The most common commands are start, stop, restart, enable and disable.

Why do I have to reset primary and secondary on both servers after each restart?

Because DRBD has no concept of leader elections. An external system must promote a DRBD resource to Primary, and there can only be one primary at a time. There are a lot of ways to do this.
You can "manually" promote a resource with # drbdadm primary <resource> and then mount things up from there -- but that's what you want to avoid. DRBD can "autopromote" in version 9, which will automatically promote a resource upon attempting to open its block device for access (like with a filesystem mount or a volume group activation) -- but the version you're running can't do that (upgrade? This might be enough for you). OR you could use a finite state leader election system to control promotion actions and ensure the state of both DRBD and the application stack it supports. That's Pacemaker.
You want Pacemaker, I promise. Pacemaker is not overly difficult, but it is extremely large. You won't have to learn much of it in order to accomplish what you want. You can spend a lot of time and energy making a "perfect" cluster that will resist any failure under the sun, and that effort would be rewarded. It's a good system.
A combination of Corosync/Pacemaker, DRBD-9.x or DRBD-8.4.x latest, and whatever you have on top of that should accomplish what you want automatically. There are lots of docs out there which detail how to do this. Here's one that's up to date:
linbit users-guide-9.0
I would recommend reading that entire guide if you have the time. DRBD has undergone some serious evolution in the past few years.
Comment: From what the OP wrote, I assume that he's using the stock Debian Kernel. While this drbd might be old, it's already in the distro kernel, it's possible bugs are known and documented, and saves admins from fiddling with manually patched, self-compiled kernels in production environments. Speaking for me, I care more about using my time efficiently for my job instead of half-duplicating the work of the Debian Kernel Maintainers. :-)
Answer: Extending the Answer of @Spooler: See Chapter 5.8.3 of the drbd8 Manual for the become-primary-on directive. While the mentioned chapter is about dual primary mode, become-primary-on is also valid for active-passive setups.


Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock

Question: I am trying to connect to a docker image, for that, i tried those commands:
export CR_PAT=<your token access>
echo $CR_PAT | docker login ghcr.io --password-stdin -u <your username>

I used as username my Github username and as result, i got:
Got permission denied while trying to connect to the Docker daemon socket at
unix:///var/run/docker.sock: Post "http://%2Fvar%2Frun%2Fdocker.sock/v1.24/auth":
dial unix /var/run/docker.sock: connect: permission denied

so to fix it, i tried to give permissions for all users using the following command:
sudo chmod 777 /var/run/docker.sock

and when i retype
    echo $CR_PAT | docker login ghcr.io --password-stdin -u <your username>

the terminal didn't return any answer!! it's blocked ..
any help please??
Thanks.
Answer: The problem was fixed by restarting the computer.
Comment: I have encountered the same issue and restarting did not solve the problem.
Comment: @JerodG I think you have to pay attention to your personal access token rights. create another token and retype commands !


param-grid passing parameters to an underlying function. lost in kw_args

Question: I am lost here. Hope some one can shed some light.
I have built a pipeline (sklearn pipe, actually to be precise an imbalanced-learn pipeline)
The first step of the pipe is a FunctionSampler (imbalanced-learn 0.4.0dev available on Git-hub only) which is an API wrapper for a custom function defined below on step #3. I wish to be able to pass a range of parameters to the function underlying - this is my problem here.
Then I build a grid search with a range for max_samples, but when I fit I get the error.
I am new to python - apologies if I there is an obvious answer I am not seeing.
Thanks a lot!
1 define custom function
In [90]: def outlier_rejection(X, y, max_samples):
        ...:     model = IsolationForest(max_samples=max_samples, contamination=0.4, random_state=rng)
        ...:     model.fit(X)
        ...:     y_pred = model.predict(X)
        ...:     return X[y_pred ==1], y[y_pred == 1]
        ...:

2 build pipeline
  pipe = make_pipeline(FunctionSampler(func=outlier_rejection, kw_args={'max_samples':1}), LogisticRegression(random_state=rng))

3 show the pipe I need to pass max_samples in kw_args
Pipeline(memory=None,
             steps=[('functionsampler', FunctionSampler(accept_sparse=True,
                func=<function outlier_rejection at 0x000001173B3E9EA0>,
                kw_args={'max_samples': 1})), ('logisticregression', LogisticRegression(C=1.0, class_weight=None, dual=False, fit_intercept=True,
                  intercept_scaling=1, max...ect at 0x0000011737DCA1B0>,
                  solver='liblinear', tol=0.0001, verbose=0, warm_start=False))])

4 build a grid search
cv = GridSearchCV(pipe, param_grid={'logisticregression__C': [1., 10.], 'functionsampler__max_samples': [1, 10, 100]})

5 fit cv and get the following error
ValueError: Invalid parameter max_samples for estimator FunctionSampler(accept_sparse=True,
        func=<function outlier_rejection at 0x000001173B3E9EA0>,
        kw_args={'max_samples': 1}). Check the list of available parameters with `estimator.get_params().keys()`.

Answer: The first issue here is that you're trying to pass a max_samples argument to FunctionSampler(), but FunctionSampler() does not have a max_samples as a named argument.
Rather, max_samples belongs as an entry in the kw_args argument to FunctionSampler().
That suggests that you should instead pass in something like
'functionsampler__kw_args': {'max_samples': [1, 10, 100]}

to the GridSearchCV param_grid argument (note: I'm not sure why it's called params in your code, the argument is either positional or named param_grid in the docs).
But...you can't pass a dict as a value in the param_grid argument.  Doing so throws an error:

ValueError: Parameter values for parameter (functionsampler__kw_args) need to be a sequence(but not a string) or np.ndarray.

The best solution I can think of is to wrap FunctionSampler() in a class that accepts separate key and values arguments from param_grid (eg functionsamplerwrapper__key), and then puts them together as the kw_args dict that FunctionSampler() expects.  Something like this:
from imblearn import FunctionSampler
from imblearn.pipeline import make_pipeline
from sklearn.ensemble import IsolationForest
from sklearn.model_selection import GridSearchCV
from sklearn.linear_model import LogisticRegression

class FunctionSamplerWrapper(object):
    def unwrap(self, key, values):
        return FunctionSampler(func=outlier_rejection, kw_args={key[0]: values})

pipe = make_pipeline(FunctionSamplerWrapper().unwrap(key = ['max_samples'],
                                                     values = [1]),
                     LogisticRegression(random_state=rng))

cv = GridSearchCV(pipe,
                  [{'logisticregression__C': [1., 10.],
                   'functionsamplerwrapper__key': ['max_samples'],
                   'functionsamplerwrapper__values': [1, 10, 100]}])

Note - I only checked to see if this runs without error (it does), but I haven't actually tested it out on data to ensure correct functionality.
Hope this helps.
Comment: Also I just want to mention that while playing I managed to make this code run: cv = GridSearchCV(pipe, param_grid={'logisticregression__C': [1., 10.], 'functionsampler__kw_args': [{'max_samples':x} for x in [10,100]]}) but I need to test it fully
Comment: super! thank you very much indeed. Re: "params" and "param_grid" is due to the fact that i was experimenting with a variation of GridSearchCV called EvolutionaryAlgorithmSearchVC (sklearn-deap)
Comment: You're welcome!  Re different variations, it might be helpful to update your original post to note which functions and classes are non-standard.  I also discovered that your `make_pipeline` is actually from `imblearn`, not `sklearn` (the `sklearn` version throws an error with this code).  For others coming to learn from your post in the future, this might be cause for confusion.
Answer: The FunctionSamplerWrapper solution by @andrew_reece isn't working for me. Instead, the workaround in the comments by @luide does the job. Only instead of
'functionsampler__kw_args': [{'max_samples':x} for x in [10,100]]
I'd prefer to do
'functionsampler__kw_args': [{'max_samples': 10}, {'max_samples': 100}]
because I think it's easier to understand.
Note that I haven't placed the values inside lists (e.g. {'max_samples': [10]}), because doing so generates an error about non-matching value lengths.
There's a relevant discussion about Scikit-learn's FunctionTransformer here:
How can I make the FunctionTransformer along with GridSearchCV into a pipeline?
To sum up, that's how I would do it:
'functionsampler__kw_args': [{'max_samples': 10}, {'max_samples': 100}]


How to change the default logo size in the OpenChurch theme?

Question: I'm trying to upload an image for the logo with a slightly higher resolution than the default logo, but I don't find any way to change the default logo size in the OpenChurch theme. I don't need the text beside the logo there, but I need a bigger logo.
Any suggestions?
Answer: In your Admin toolbar, click on appearance, then click on settings.

Scroll down to LOGO IMAGE SETTINGS and uncheck Use the default logo supplied by the theme and upload your own logo.
Comment: thank you for the detailed instructions with screenshots. If I upload my logo there which is bigger in dimensions(200x150), it is scaled back to smaller(60x45) resolution. Anyway to keep the resolution intact? I checked the css file with inspect element at /profiles/openchurch/themes/openchurch_theme/css/openchurch-style.css but get where to change the resolution since they have not added height and width there.
Comment: @yogi then try adding `.site-branding__logo img{ height: 200; width: 150px; }` to your css file and clear/flush the cache to see changes.


Interval of convergence geometric series

Question: Suppose $\sum_{k=0}^{\infty} {a_k}{x^k}$ is a power series and $$\lim_{k\rightarrow\infty}|a_k|^\dfrac{1}{k}{=L>0}$$ converges.
In part a) I used properties of exponential and logarithms to find that
$\quad k^{1/k}\leq (k+1)^{1/k}\leq (2k)^{1/k} \quad$ for    every $k\in \mathbb{N}$
part b) asked to used the squeeze lemma to prove that $$\lim_{k\rightarrow\infty}(k+1)^{1/k}={1}$$
part c) asked to prove R=1/L This was done using the root test.
Now I'm stuck on part d) which asks to
Prove that
$\sum_{k=0}^{\infty} \dfrac{a_k}{k+1}{r^{(k+1)}}$
convergences for $r\in $ (-R,R).
I'm not sure how to proceed. Any help would be greatly appreciated. Thank you,
Answer: \begin{align*}
\dfrac{|a_{k}|^{1/k}|r|^{(k+1)/k}}{(k+1)^{1/k}}=\dfrac{|a_{k}|^{1/k}|r|^{1/k}r}{(k+1)^{1/k}}\rightarrow\dfrac{L\cdot 1\cdot |r|}{1}=L\cdot|r|<1,
\end{align*}
if $|r|<R$.


VSCode - cannot enter input into console while debugging C++

Question: I know this was asked many times before, but none of the solutions have worked for me.
I am trying to debug a single C++ file on Visual Studio Code on Windows. Running and debugging works fine. However, when I try to debug a program that asks for user input (for example using cin or scanf()), the process starts and just hangs. The program is waiting for me to input something, however the integrated terminal does not let me type anything in.
One possibility is to run debug in an external terminal, but the problem with the external terminal is that it closes immediately when the program finishes, so I cannot see the result.
Is there an option in launch.json or maybe an extension that would help solve my issue?
Here's my launch.json file:
"name": "g++.exe - Générer et déboguer le fichier actif",
"type": "cppdbg",
"request": "launch",
"program": "${fileDirname}\\${fileBasenameNoExtension}.exe",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"miDebuggerPath": "C:\\MinGW\\bin\\gdb.exe",
"setupCommands": [
  {
    "description": "Activer l'impression en mode Pretty pour gdb",
    "text": "-enable-pretty-printing",
    "ignoreFailures": true
  }
],
"preLaunchTask": "C/C++: g++.exe build active file"

Comment: You can always add a break point in the end or add a sleep function to see the results. And there should be an option in VC to launch console that doesn't close immediately after finishing. At least VS has such option.
Comment: Use the debug terminal
Comment: I do not want to fight with the tool by adding breakpoints or sleep in the end every time I debug. I would like there to be a solution that would make it work out of the box, like it works on my VSCode for Linux or Visual Studio IDE.
Answer: Reinstalling MinGW seems to have solved the issue for me. I used the installer from it's SourceForge page.
I do not know what original the issue was, but now it is possible to type into the terminal when in debug mode. I suspect the issue was with my gdb installation.


Odd e even não funcionam

Question: Estou fazendo um theme no tumblr e queria alterar a cor das labels do chat, pra que em cada linha elas alternassem as cores. Acontece que todas elas ficam com a cor definida na odd
.label:nth-child(odd){color: #012E5E; font-style: italic;}
.label:nth-child(even){color: #D8A307; font-style: italic;}

Esse é o bloco do chat
{block:Chat}
    {block:Lines}
        {block:Label}{Label}{/block:Label} {Line}

    {/block:Lines}
{/block:Chat}

E fica assim
Answer: Não funciona pq cada linha sempre é odd no seu caso, pq cada label é filha única de uma Lines
Para ajustar isso vc tem que atingir a Lines, pois elas sim são irmãs umas das outras. Então seu código deveria ficar como isso:
.Lines:nth-child(odd) .label{color: #012E5E; font-style: italic;}
.Lines:nth-child(even) .label{color: #D8A307; font-style: italic;}

Snippet

.Lines:nth-child(odd) .label{color: #012E5E; font-style: italic;}
.Lines:nth-child(even) .label{color: #D8A307; font-style: italic;}

{Label}{/block:Label} {Line}

{Label}{/block:Label} {Line}

{Label}{/block:Label} {Line}

{Label}{/block:Label} {Line}

Comment: @lua entendi... se o seu framework funciona de forma diferente vc pode inspecionar o código já renderizado no Browser, usando a DevTools do browser para ver quis elementos ele gera, se são `` ou `` ou  `` e adaptar seu CSS, mas o seu problema é que vc tem que usar o Odd e Even o nível acima, nos elemenetos irmãos e não nos filhos dos irmão como expliquei na resposta. Inclusive reeditei o código, da uma olhada novamente pra ver se resolve
Comment: @lua que bom que resolver, se vc acha que o problema foi resolvido considere marcar a Resposta como Aceita **✓**. Seobre o problema com o `` estar quebrado a sua regra do CSS da uma olhada nessa resposta que com certeza vai te ajudar a entender o que aconteceu de fato para não ter funcionado: https://pt.stackoverflow.com/questions/290866/qual-a-diferen%C3%A7a-entre-o-nth-child-e-o-nth-of-type
Comment: Então, o problema é que as linhas não estão dentro de uma div, então pra manipular dessa forma não traria nenhum tipo de efeito.
Comment: Fiz um teste aqui, tirando o  que coloquei depois do {Line} e ele funcionou, agora vou só rearranjar as linhas dentro de div para que fiquem umas embaixo das outras. Obrigada pela ajuda!

Odd e even não funcionam


How can we create a search form to display a specific node

Question: I need to create a result publishing system in drupal.
there must be a search page to enter the student register number.
when the user enter the register number it should take it to a single specific node.
here the register number is a nodeid
so when a user enter the node id and hit show button, it should display that specific node.
which method is best.
i think with views we can do this.
but how
thanks
Answer: Make an exposed filter (with autocomplete) of the register number in your view (showing all these desired nodes), enable it's exposed filter block (Advanced > Exposed form in block : Yes)
Now place this block where ever you want, hit apply, you should be taken to the views page, only showing one result. (Make sure the full rendered node entity is shown)


Pass Query String to User Control from Parent Page

Question: i have create a user control search.ascx with query string values and i m accessing this page from Parent page(Rcomm.aspx) and now this Page is open from another page(view.apsx) on button click using hyperlink navigateurl. my question is that how can i pass my user control query string from view.aspx
Comment: not sure I understand your question, if you mean how to pass values from page to user control, possible duplicate of [Pass values from page to user control](http://stackoverflow.com/questions/8117490/pass-values-from-page-to-user-control)
Answer: A user control has access to the page's URL the same as any normal ASP.NET page does; thus, in order to retrieve the QueryString from the user control, the normal syntax will work:
Request.QueryString('key')

However, I consider this poor style, because I think of user controls as a modular item you can embed in ANY page: thus tying it directly to a particular querystring value seems to go against that. However you may have valid reasons for this.
I'm not sure I understand the second part of your question:

how i make hyperlink navigate URL with query string for open my Rcomm.aspx

Could you please clarify?
ADDITIONAL: OK it seems to me like you have a link in your user control, and want to use a querystring value from the user control's parent page (Rcomm.aspx) to use in the link to a third page. Correct me if I am wrong.
In this case, you would read the querystring from the user control, then append to another URL using NavigateURL:
URL: Rcomm.aspx?field=value

(in code behind:)

Dim qs as string

qs = Request.QueryString('field')

MyHyperlink.NavigateURL = "newpage.aspx?field2=" & qs

Or something similar. Yes?
Comment: thanks Katstevens, my question is simple is that how i pass query string value of my user control from another page in navigaturl how i can send value because my embed page is open from another page with hyperlink navigaturl


How to pass the id of a record from a listview

Question: public class searchEvent extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener,
    SearchView.OnQueryTextListener {
private SessionManager session;
ProgressDialog pDialog;
List<DataModel> listData = new ArrayList<DataModel>();
Adapter adapter;
SwipeRefreshLayout swipe;
ListView list_view;

public static final String url_data = "http://10.0.2.2/TriniRec/eventList.php?email=";
public static final String url_cari = "http://10.0.2.2/TriniRec/search.php?email=";

private static final String TAG = searchEvent.class.getSimpleName();

public static final String TAG_ID = "eventID";
public static final String TAG_NAMA = "name";
public static final String TAG_RESULTS = "results";
public static final String TAG_MESSAGE = "message";
public static final String TAG_VALUE = "value";

String tag_json_obj = "json_obj_req";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_search_event);
    // session manager
    session = new SessionManager(getApplicationContext());

    swipe = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh);
    list_view = (ListView) findViewById(R.id.list_view);

    adapter = new Adapter(searchEvent.this, listData);
    list_view.setAdapter(adapter);

    swipe.setOnRefreshListener(this);

    swipe.post(new Runnable() {
                   @Override
                   public void run() {
                       swipe.setRefreshing(true);
                       callData();
                   }
               }
    );
    //Adding ListView Item click Listener.
   list_view.setOnItemClickListener(new AdapterView.OnItemClickListener()
    {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            Intent intent = new Intent(searchEvent.this,ShowSingleRecordActivity.class);

            // Sending ListView clicked value using intent.
            intent.putExtra("ListViewValue",listData.get(position).toString());

            startActivity(intent);

            //Finishing current activity after open next activity.
            finish();

        }
    });
}

private void callData() {
    listData.clear();
    adapter.notifyDataSetChanged();
    swipe.setRefreshing(true);
    String email = session.getEmail();
    // Creating volley request obj
    JsonArrayRequest jArr = new JsonArrayRequest(url_data + email, new Response.Listener<JSONArray>() {

        @Override
        public void onResponse(JSONArray response) {
            Log.e(TAG, response.toString());

            // Parsing json
            for (int i = 0; i < response.length(); i++) {
                try {

                    JSONObject obj = response.getJSONObject(i);

                    DataModel item = new DataModel();

                    item.setEventID(obj.getString(TAG_ID));
                    item.setName(obj.getString(TAG_NAMA));

                    listData.add(item);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            // notifying list adapter about data changes
            // so that it renders the list view with updated data
            adapter.notifyDataSetChanged();
            swipe.setRefreshing(false);
        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.e(TAG, "Error: " + error.getMessage());
            Toast.makeText(searchEvent.this, error.getMessage(), Toast.LENGTH_LONG).show();
            swipe.setRefreshing(false);
        }
    });

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(jArr);
}

@Override
public void onRefresh() {
    callData();
}

@Override
public boolean onQueryTextSubmit(String query) {
    cariData(query);
    return false;
}

@Override
public boolean onQueryTextChange(String newText) {
    return false;
}

Here i am displaying a list of events from mysql database, i want to be able for the user to click on a list record and take them to the next activity with all the details of the record, for that i need to pass the record id.
I tried passing it the array position through the intent but i dont get the expected results, i think i am passing the wrong value can someone tell me what i have to pass here. I am new to java and android studio so sorry for the lack of detail.
Comment: It'd help to elaborate what is meant by "don't get expected results".
Answer:  listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
             // get postion from arraylist
                modelclass u = arrayList.get(position);
                Intent in = new Intent(currentacticity.this, nextactivity.class);
                in.putExtra("send", u);
                startActivity(in);
                   }
        });

Comment: try above code passing object based on postion of item
Comment: This ends up passing a null value
Answer: What you should do there is:
DataModel model = (DataModel) listData.get(position);
intent.putExtra("ListViewValue", model);
startActivity(intent);

your DataModel should implements Serializable
this should fix your problem.
Comment: We don't know if `DataModel` is parcelable.
Comment: Plz check my changes


How do I use Leibniz's rule to show find the derivative of $\int_{0}^{x} f(t)x\sin(xt)\, dt$?

Question: How do I use Leibniz's rule to show find the derivative of $$\int_{0}^{x} f(t)x\sin(xt)\, dt$$ where $f(t)$ is continuous on the interval $[0,b]$ and $b>0$, $0 \le x \le b$. The rule is given as $$\dfrac{d}{dx} \bigg(\int_{a(x)}^{b(x)} g(x,t)\, dt\bigg) = g(x,b(x))\cdot \dfrac{d}{dx}b(x)-g(x,a(x))\cdot \dfrac{d}{dx}a(x) + \int_{a(x)}^{b(x)} \dfrac{\partial}{\partial x} g(x,t)\,dt$$
Also, I'm not really sure what $g(x,a(x))$ or $g(x,b(x))$ equates to if I let $g(x,t) = f(t)x \sin(xt)$. Do I just plug in $a(x)$ or $b(x)$ in place of $t$ in $g(x,t)$?
Answer: In your case, you have
$$a(x) = 0 \implies \frac{d}{dx}a(x) = 0 \tag{1}\label{eq1A}$$
$$b(x) = x \implies \frac{d}{dx}b(x) = 1 \tag{2}\label{eq2A}$$
Also, as you stated, you have
$$g(x,t) = f(t)x\sin(xt) \tag{3}\label{eq3A}$$
You thus have that
$$g(x,a(x)) = g(x,0) = f(0)x\sin(0) = 0 \tag{4}\label{eq4A}$$
$$g(x,b(x)) = g(x,x) = f(x)x\sin(x^2) \tag{5}\label{eq5A}$$
$$\begin{equation}\begin{aligned}
\frac{\partial}{\partial x} g(x,t) & = f(t)\left(\sin(xt) + x\left(\frac{\partial\sin(xt)}{\partial(xt)}\right)\left(\frac{\partial{(xt)}}{\partial{x}}\right)\right)\\
& = f(t)(\sin(xt) + xt\cos(xt))
\end{aligned}\end{equation}\tag{6}\label{eq6A}$$
Now, you can just plug these values into the RHS of your stated rule.


Getting ValueError: DataFrame constructor not properly called while creating a dataframe from lists of list

Question: I am getting below error while converting Lists of list to dataframe:
raise ValueError('DataFrame constructor not properly called!')
ValueError: DataFrame constructor not properly called!
I have used numpy to split the list and now need to convert those lists of list to a dataframe:

    import numpy as np
    import pandas as pd

    def SplitList():
        l = np.array([6,2,5,1,3,6,9,7,6])
        n = 3

        list = l.reshape((len(l)//n), n).T
        print(list)

    df = pd.DataFrame(list)

Answer: First of all, don't use list as a variable name, it is a reserved keyword in Python.
Secondly, you need your function to return your reshaped array, so you need:
import numpy as np
import pandas as pd

def SplitList():
    l = np.array([6,2,5,1,3,6,9,7,6])
    n = 3

    a = l.reshape((len(l)//n), n).T
    return a

df = pd.DataFrame(SplitList())

print(df)

   0  1  2
0  6  1  9
1  2  3  7
2  5  6  6

Just a suggestion, but may be an idea to make your function more reusable. For example:
def split_list(arr, n):
    arr = np.array(arr)
    return arr.reshape(-1, n).T

split_list([6,2,5,1,3,6,9,7,6], 3)

[out]
[[6 1 9]
 [2 3 7]
 [5 6 6]]