text:
Q: Inclusion templatetag with counter What I want
Inclusion Templatetag which returns number of uses and don't break when using template inheritance. I tried to storage counter in context, but it does not work as I intended.
base.html
{% block body %}
  {% my_tag %}

  {% my_tag %}

{% endblock %}

page.html
{% extends 'base.html' %}
{% block body %}
    {{ block super }}
    {% my_tag %}

    {% my_tag %}

{% endblock %}

rendered result:
1
2
3
4

What I tried
@register.inclusion_tag('tagtemplate.html', takes_context=True)
def my_tag(context):
    counter = context.get('tag_counter', 1)
    ctx = {'tag_counter': counter}
    context['tag_counter'] = counter + 1
    return ctx

And result:
1
2
1
2

And what worked
Added middleware which added counter to request
class TagCounterMiddleware(object):
    def process_request(self, request):
        request.tag_counter = 1

and changed template tag
@register.inclusion_tag('tagtemplate.html', takes_context=True)
def my_tag(context):
    request = context.get['request']
    ctx = {'tag_counter': request.tag_counter}
    request.tag_counter += 1
    return ctx

Thanks to @SardorbekImomaliev for his suggestion! :)

A: I suggest putting your counter in request. Something like this.
# This code wasn't checked
@register.inclusion_tag('tagtemplate.html', takes_context=True)
def my_tag(context):
    request = context.get('request')
    counter = getattr(request, 'tag_counter', 0)
    request.tag_counter = counter + 1
    context['request'] = request
    return context


text:
Q: Save entire desktop state? I'd love to have a utility that would save and restore my current desktop state, much like sessions in Firefox.  At best, it would freeze every application's state, open window positions, etc. and provide a scriptable interface to restore them at any time, just as you'd left them.
More realistically, I could make a list of what applications were open, hide/minimize them, hide them from the dock, etc., so that restoring them (if they were still open) would appear to resume them - and so that it would be hard to accidentally close them.
Most minimally, I could add a new desktop surface to Leopard Spaces for each saved session, and move everything there, using Spaces itself as a sort of stack.
The use case is:

*

*I start working on something - say, this very question - and so I open up stackoverflow in Firefox, I launch XCode and ScriptDebugger, I write a few lines of code, and realize I'm stuck till I find an answer

*I add a "Keep working on SessionSaver" calendar event to iCal, or a task to OmniFocus

*I save my current session

*I attach an AppleScript to the iCal event or OmniFocus task that will reopen the session I saved in step 3

I see something in Carbon about archiving window hierarchies, but I'd want this to work in 64-bit Cocoa in Snow Leopard.  (I'm currently using 10.5.6 on a Mac Pro.)
FinderWindowManager does something like this for Finder windows.

A: If you want to freeze the applications' states, is it what suspend/hibernate does?
Edit: Just realized what you want to archive. I'm using Linux, I would start a new X session if I want something like this.

A: You could do something like this with virtual machines, though obviously there would be a performance penalty and I'm not sure whether you can run Leopard itself under a virtual machine.  (You just suspend the VM duplicate it and then restart it).
Certainly doing this natively for the OS would require a huge amount of storage as you have to duplicate the memory and the entire hard drive (as changes to the hard drive could be incompatible with the saved state).
I imagine that at somepoint in the future something like this could be done using ZFS.

A: I've seen a few attempts at this lately...
Relaunch
Worksets

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is IPTW (inverse probability of treatment weighting) legal? When using IPTW, one can easily get weights 10 or even 20 for the observations.
For instance, in logistic regression, weight 10 for an observation means that we have not one, but 10 observations identical to this one. Thus, if we are allowed to assign weights > 1 to observations, then we can take, e.g., a sample of 100 observations, assign weight 10 to each one of them, and thus obtain a sample of 1000 observations, with totally lesser p-values etc.. But that will be evidently illegal.
Why assigning weights > 1 is legal in IPTW? Is IPTW with weights >1 legal?

A: That is not how it works. The inference based on logistic regression is not correct when you incorporate weighting. You need to estimate the variance of the IPTW estimator, which happens to be inversely related to the propensity score. So large weights also lead to large variance estimates and thus larger p-values.
(Also, with IPTW, all weights are larger than one since it is the inverse of a probability).
Here is a ultra mini-lesson on IPW estimators. Suppose you observe the data structure $(X,A,Y)$ where $X$ is a vector of covariates, $A$ is a binary treatment, and $Y$ is some outcome. Let $\pi_0(x):= P(A=1|X=x)$ be the propensity score. Suppose we are interested in estimating the treatment-specific mean parameter $Psi := E_XE[Y|A=1,X]$. Consider the identity
$$E_XE[Y|A=1,X] = E_X \left[\frac{E[Y|A,X]1(A=1)}{\pi_0(X)}\right] =  E_X \left[\frac{Y1(A=1)}{\pi_0(X)}\right],$$
which follows from a conditioning argument. This suggests the following IPW estimator of $\Psi$:
$$\hat \Psi_n := \frac{1}{n} \sum_{i=1}^n \frac{Y_i1(A_i=1)}{\pi_0(X_i)}$$
where we unrealistically assume that $\pi_0$ is known. Since $\hat \Psi_n$ is just an average of a random variable, inference is easy. We have
$$\sqrt{n}(\hat \Psi_n - \Psi) \rightarrow_d  N\left(0, \text{Var}_0\{Y1(A=1)/\pi_0(X)\} \right).$$
Now, note that the variance depends on the weight $w_0=\frac{1}{\pi_0(X)}$, so a larger weight gives a larger variance.
You are free to replace $\pi_0$ with a logistic regression estimate of $\pi_n$, but this is usually not a $\sqrt{n}$-consistent or asymptotically normal estimator without very strong conditions.
Note, $E[Y|A=1]$ and $E_XE[Y|A=1,X]$ are two very different parameters.


text:
Q: Concept - Creating client side validation from PHP object I am making my own MVC framework and I was thinking of a way to do "automatic" client side validation controller.
Among other functionalities, my forms, elements and validators are objects that work together somewhat like this (inside the form object):
$this->addElement('text', 'myInput');
$this->elements['myInput']->addValidators(array
    'length' => array('min' => 5, 'max' => 10),
    'number' => array('decimals' => 0)
));

In the example above, I created a text input named 'myInput' whose value, according to the validators I added:

*

*Must be >= than 5 characters

*Must be <= than 10 characters

*Must be a number

*Must have no decimals (int only)

When I get the form submission and call a validation function, all works well on the server side. However, what bothered me was having to redo validation on the client side manually. I dislike having to duplicate the same functionality so I came up with a way to create my client side validation from the PHP form object that is already there.
It boils down to having JS validator functions that have the same functionality as the PHP validators and calling a getClientValidatiors() function on elements to create the appropriate

I'm looking for a thumbs up or suggestions on how this could work with another technique. If you have any thoughts, I'd like to hear them!

A: Consider writing the validation specification in such a way that you can automatically validate in JavaScript and PHP.
$input_schema = array(
    "foo" => array(
        "type" => "number",
        "decimals" => 0,
        "length" => array(
            "min" => 5,
            "max' => 10
        )
    )
);

Then in JS you can do:
var input_schema = <?php echo json_encode($input_schema);?>;
function validate_input(form_values) {
    for (var key in input_schema) {
        validate_property(input_schema[key], form_values[key]);
    }
}

function validate_property(schema_property, value) {
    if (schema_property.type === "number") {
        validate_number(schema_property, value); // etc
    }
}

And you can make a similar implementation in PHP.


text:
Q: How to auto-fit a wpf window to a ListBox content? Why does this WPF window does not auto-sets its width and height, depending of the Grid or listbox size (so depending of the number of items into the listbox)?:
<controls:MetroWindow x:Class="....."
                 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                      xmlns:controls="clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
                        Width="Auto" Height="Auto" MaxHeight="500" MaxWidth="500">

<Grid  Background="Gray" Width="Auto" Height="Auto" >
    <ListBox   Width="Auto" Height="Auto" FontSize="12" FontWeight="SemiBold" ItemsSource="{Binding ListError}"  >
        <ListBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding}" />
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
 </Grid>
</controls:MetroWindow>

In this case, it renders 500*500 ( = my MaxWidth and MaxHeight values).
If I remove the MaxWidth and MaxHeight values, it till does not auto-fit to the listbox size.
Thx in advance.

A: Remove the Height and Width properties, and add the following :
SizeToContent="WidthAndHeight"


text:
Q: Why is Rails putting a period(dot) before the query string in URL's, instead of a question mark? Rails is generating account activation URL's with a period, instead of a question mark. I see this happening consistently in both the mailer preview and the rails log. Example link:
http://localhost:3000/account_activations/Cm4OyFOwosBcGZ67qg49nQ/edit.example@railstutorial.org
From routes.rb:
resources :account_activations, only: [:edit]

From users_controller.rb:
  def create
    @user = User.new(user_params)
    if @user.save
      UserMailer.account_activation(@user).deliver_now
      flash[:info] = "Please check your email to activate your account."
      redirect_to root_url
    else
      render 'new'
    end
  end

From account_activation.html.erb:
<%= link_to "Activate", edit_account_activation_url(@user.activation_token, @user.email) %>

From user.rb (method to create and assign the digest):
def create_activation_digest
  self.activation_token = User.new_token
  self.activation_digest = User.digest(activation_token)
end

From user_mailer_preview.rb:
  def account_activation
    user = User.first
    user.activation_token = User.new_token
    UserMailer.account_activation(user)
  end

A: The url_route only takes one param: id. What you want to do is this:
edit_account_activation_url(@user.activation_token, email: @user.email)
This will give you params[:id] and params[:email] in your controller to use.

A: The reason is that every resourceful url_helper actually expects n or n+1 arguments (where n is a number of named params in the route), with the last argument being format of the route:
user_path(@user, :json)  #=>  /users/1.json

(Actually the signature is just url_helper(*args), wrong arity exception is thrown from inside of the helper)
If you want to add extra get parameters, you need to pass an extra hash as already stated by nzfinab:
user_path(@user, hello: :there) #=> /users/1?hello=there


text:
Q: Determine orthogonal basis I have to determine an orthogonal basis for the symmetric bilinear form $S(x,y)=x^TMy$ on $\mathbb{F}_3^3$. The Matrix is:
$$M =\begin{bmatrix}0& 1 &2 \\\ 1& 1& 0 \\\ 2& 0 &2\\ \end{bmatrix}$$
I have tried to calculate first the eigenvalues and eigenvectors, but I have calculated just one eigenvalue that's $0$, but I need more eigenvalues.
I hope someone can help me?

A: Trying a "Gram-Schmidt" approach without calculating $\det M-\lambda\mathbb{1}$:
Consider $S(e_2,e_2) = 1$, so take $v_1=e_2$ as the first vector of the new base. Unluckily $S(e_1,e_1)=0$, so we can't take $e_1$ as the first vector of the new base (just to be sure...).
Then consider $v_2 = e_1 - S(e_1,v_1) v_1 = e_1 - e_2$. Then $S(v_1,v_2) = S(e_2 ,e_1 - e_2) = S(e_1,e_2) - S(e_2,e_2) = 0$ and $S(v_2,v_2)=-1$: here the second vector of the basis!
Similarly, consider $v_3 = e_3 - S(v_1,e_3)v_1 - S(v_2,e_3)v_2 = e_3 + 2(e_1-e_2)$. Then $S(v_1,v_3) = S(v_2,v_3)=0$ and $S(v_3,v_3) = S(e_3 - 2(e_1-e_2),e_3 - 2(e_1-e_2)) = 0$.

If you want to calculate the characteristic polynomial: $|\det (M-\lambda)| = \lambda^3$, so $\lambda=0$... then you should check the kernels of $(M-\lambda)^k$ for $k=1, \ldots, 3$ and study the generalized eigenspaces. How do you want to proceed from there?


text:
Q: Is there an easy way to edit a json file with python There are some similar questions to this lying around but I couldn't find anything that does what I'm looking for.
The code I'm using is as follows (python 2.75): (EDIT, updated to include suggestions for clarity:
def write_json(entry):
  current_players = []
  with open("Dota2data.txt","r+") as outfile:
     data = json.load(outfile)
     for member in entry.players:
        current_players.append(member['account_id'])
     data["matches"].append({"match":entry.match_id, "winner":entry.radiant_win, "players":current_players})
     json.dump(data, outfile)
     outfile.close()
  pass

I'm basically trying to add a new match instance within the 'matches' key each time this function is running (it is called when a new match is loaded).
However, as I'm sure you've noticed this will just replace the text file with the most recent result each time.
I know that I can use appending to add a new match to each line, but because I'm stubborn I want to add the data within the 'matches' field. Is this possible?
Thanks!
Edit: I just want to add, tonight is my first time playing around with this and I'm pretty new to python too.
That answer was a great help, I've now got some momentum to finish this. Thanks for your help! For reference: final code is as follows.
def write_json(entry):
   current_players = []
   with open("Dota2data.txt","r+") as infile:
      data = json.load(infile)
      for member in entry.players:
         current_players.append(member['account_id'])
      data["matches"].append({"match":entry.match_id, "winner":entry.radiant_win, "players":current_players})
      infile.close()
   with open("Dota2data.txt","r+") as outfile:
      json.dump(data, outfile)
      outfile.close()
   pass

A: EDIT: Change your quotes to "" instead of '' for json.loads. Or, you can use ast.literal_eval() instead.
EDIT2: Let me clarify, JSON uses double quotes for syntax, while python can use either. If you're calling json.loads, use double quotes for your JSON. If you want to use single quotes, use ast.literal_eval. Make sure you import ast.

A: EDIT: before of anything , load the file.
with open("Dota2data.txt","r+") as outfile:

Sure, first lets load the json file into an object.
data = json.load(outfile)

Then, add a new property inside 'matches' as a dictionary.
data['matches'].append({'match':entry.match_id, 'winner':entry.radiant_win, 'players':current_players})

Finally, output the file.
json.dump(data, outfile)

FULL CODE:
def write_json(entry):
    with open("Dota2data.txt","r") as infile:
        for member in entry.players:
            current_players = current_players.append(member['account_id'])
        data = json.load(infile)
        infile.close
        data['matches'].append({'match':entry.match_id, 'winner':entry.radiant_win, 'players':current_players})
        with open("Dota2data.txt","w") as outfile:
            json.dump(data, outfile)
            outfile.close()

A: def update_file(path, entry):
    with open(path) as infile:
        data = json.load(infile)

    current_players = [member['account_id'] for member in entry.players]
    data["matches"].append({
        "match": entry.match_id,
        "winner": entry.radiant_win,
        "players": current_players
    })

    with open(path, "w") as outfile:
        json.dump(data, outfile)


text:
Q: Wordpress sorting by either post meta key or post_date I'm having a little trouble coming up with the correct SQL for a Wordpress query.
What I have are some posts that contain a custom field called 'date'. I'd like to fetch ALL posts (both those containing this custom field plus those that don't) and sort them by date AND post_date. date will take precedence over post_date, i.e., if there's not a date specified, it'll use the post_date value instead.
What I have so far:
        $query = "
            SELECT wposts.*
            FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta
            WHERE wposts.ID = wpostmeta.post_id
            AND wpostmeta.meta_key = 'date'
            AND wposts.post_type = 'post'
            ORDER BY wpostmeta.meta_value, posts.post_date ASC
        ";

Thx


text:
Q: Script that outputs all DLLs used by exe In cmd the line
tasklist /m /fi "imagename eq xxxxx.exe" > output.txt

will output the DLLs used by all processes to one file.
How can I separate the output to multiple txt files, each file contains the name of the process the the DLL used?

A: This should get you what you want:
Get-Process |
    ForEach-Object {
        $procName = $_.Name
        Get-Process -InputObject $_ -Module -ErrorAction SilentlyContinue |
            Export-Csv ".\$procName.csv" -NoTypeInformation
    }


text:
Q: JAVA Regex for password validation issue i have a regexp for password validation ( Regexp Java for password validation
with extra special characters)
String pattern ="^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=!\\*_?|~(){}/<>:\"\',\\[\\]`;\\\\\\\\-])(?=\\S+$).{8,}$";

The issue with this is,
if i say
 "Xyz.123".matches(pattern);

This returns false
However, if i say
  "Xyz.123$".matches(pattern);

This returns true
'.' is not a valid special characters in my case. But if my password has a valid special character along with '.' it returns true

A: You have \\S+, which means "any non-space character."  . satisfies that.  You also need the $ to satisfy the third pseudo-condition (lookahead).  . is not in that, but $ is.
EDIT: If you do not want any periods at all, change the last pseudo-condition to (?=[^\\s.]+$)


text:
Q: How to make webpage think it is on screen? How can social media web apps determine if your page is on screen vs minimized?
Here's an example:
Whatsapp Web tells people that you're online if your page is open and on screen. It also does not load chats if it is minimized.
How do I make it think that it is on screen. I would like some Javascript code that I can inject into my UIWebView (iOS) so that it keeps loading chats even when the UIWebView is on the background.
Or some other solution to the problem.
What happens right now is that when I open a chat, it loads the last message and has a loading icon on top until I actually open the app. Only once I open the app, it loads the rest of the messages.
EDIT: From one of the answers, I think I should be running a code similar to this:
document.focus();

Still does not load the rest of the chat unless on screen.

A: setInterval( checkFocus, 200 );

function checkFocus() {
  document.hasFocus() ?  console.log('focus'): console.log('blur')
}

or you can do
window.addEventListener('focus', () => console.log('focus'));
 window.addEventListener('blur', () => console.log('blur'));


text:
Q: How to use Selenium WebDriver to Download APK Files I am trying to download an .apk file using SeleniumWebDriver on FireFox.
I have set the profile to auto-save, but when I click the .apk file download link, it opens the download confirmation dialogue.
How should I proceed moving forward?
Here is my code:

FirefoxProfile fprofile = new FirefoxProfile();
fprofile.setPreference("browser.download.folderList", 2);
fprofile.setPreference( "browser.download.manager.showWhenStarting", false );
fprofile.setPreference("browser.download.dir", "D:\\WebDriverdownloads");
fprofile.setPreference("browser.helperApps.alwaysAsk.force", false);
fprofile.setPreference("browser.helperApps.neverAsk.saveToDisk",
"application/vnd.android.package-archive;"); //MIME Type for APK files
driver = new FirefoxDriver(fprofile);

A: As far as I know there is no easy way to download files with Selenium because browsers use native dialogs. Check this link.
AutoIT was helpful for me, hope it helps you too.

A: In my code, I just have following preferences and it works fine. Looks like you do have these options already.
   "browser.download.folderList": 2,
   "browser.download.dir": "/Users/nilesh",
   "browser.helperApps.neverAsk.saveToDisk": "text/csv"

If you search online, people will be posting bunch of solutions using AutoIT and Robot class. I strongly recommend you avoid that. AutoIT to my knowledge is windows only. My experience with Robot didn't give consistent results. So both solutions are flimsy and brittle.
Also if you care about supporting multiple browsers, you would have to deal with this problem on per browser basis and NOT just firefox. I recommend you reading this blog which describes how to download files in Selenium and why you shouldn't. Author of the blog provides a solution in Java on querying for the file using a HTTP Get request. That's the best way to deal with this problem if you want to support multiple browsers.


text:
Q: "Repentant" vs "penitent" Are these words interchangeable or there is some different perception of "feeling sorry" that underlies the concept? Are they both equally often used in religion? I found more derivatives from the second one. If they aren't, what are the spheres of usage for the each?

A: While, according to the OED, penitent (first found in English in 1341) and repentant (from 1230) have separate roots, they have similar meanings, and are partially defined in terms of each other.
The OED has for the pair:

Penitent:  A. adj.  1.a. That repents with sincere desire to amend the
  sin or wrongdoing;    repentant, contrite.
B. noun  1. A person who repents; a repentant sinner.
Repentant: A. adj. 1. Experiencing repentance; feeling contrition or
  regret for past sins or actions; penitent.
  B. n. 1. A person who
  repents, a penitent.

In both cases, the majority of citations given imply a religious context.
The definitions in Merriam-Webster are even more circular:

Penitent (adj.):  feeling or expressing humble or regretful pain or sorrow
  for sins or offenses :  repentant
Repentant (adj.):  1 :  experiencing repentance :  penitent
              2 :  expressive of repentance

From the definitions found in these two dictionaries, it's difficult to draw any distinction between the terms.  Both are predominantly found in a religious context, but neither one is, from the definitions given, necessarily more religious than the other.

A: James Fernald, English Synonyms and Antonyms (1914) bundles repentance and penitence with attrition, compunction, contriteness, contrition, regret, remorse, self-condemnation, and sorrow, and then offers this succinct distinction between the two:

Repentance is sorrow for sin with self-condemnation, and complete turning from the sin. Penitence is transient, and may involve no change of character or conduct.

The 1947 edition of Fernald's book, now titled Funk & Wagnalls Standard Handbook of Synonyms, Antonyms, and Prepositions, rearranges the order of the sentences in the larger block of text, but leaves the wording of the remarks about repentance and penitence unchanged.
Meanwhile, Webster's Dictionary of Synonyms (1942) offers this commentary on penitence and repentance, which it places in a group with contrition, attrition, compunction, and remorse:

Penitence, repentance, contrition, attrition, compunction, and remorse agree in denoting sorrow or regret for sin or wrongdoing. Penitence implies little more than such sorrow or regret; as, the outward signs of penitence; his penitence is only skin-deep; he showed his penitence in many ways. Repentance is richer in its implications, for it also implies a change of heart, an awareness of one's shortcomings morally or or spiritually, or of the evil of one's actions or life as a whole. "I came not to call the righteous, but sinners to repentance" (Luke v. 32) "God of his mercy give/ You patience to endure, and true repentance" (Shak[espeare]).

Merriam-Webster's Dictionary of Synonyms (1984) updates the examples of repentance and penitence, but not the language of the distinction that its predecessor drew 42 years earlier.
I find the insistence by both of these resources on the relative superficiality of penitence surprising. Perhaps in the first half of the twentieth century, there was a general sense that penitence was mere lip service and repentance was heartfelt—but if so, I think that distinction has very nearly vanished in current usage.
With regard to the adjectives penitent and repentant, I acknowledge that penitent seems to me rather more likely to appear in connection with conduct such as enduring physical chastisement as the price of forgiveness, whereas repentant doesn't seem especially concerned with the scourging of one's sins by some third party. But in general today, I don't detect a difference in sincerity between a person who is penitent and one who is repentant.


text:
Q: Is there any benefit to this switch / pattern matching idea? I've been looking at F# recently, and while I'm not likely to leap the fence any time soon, it definitely highlights some areas where C# (or library support) could make life easier.
In particular, I'm thinking about the pattern matching capability of F#, which allows a very rich syntax - much more expressive than the current switch/conditional C# equivalents. I won't try to give a direct example (my F# isn't up to it), but in short it allows:

*

*match by type (with full-coverage checking for discriminated unions) [note this also infers the type for the bound variable, giving member access etc]

*match by predicate

*combinations of the above (and possibly some other scenarios I'm not aware of)

While it would be lovely for C# to eventually borrow [ahem] some of this richness, in the interim I've been looking at what can be done at runtime - for example, it is fairly easy to knock together some objects to allow:
var getRentPrice = new Switch<Vehicle, int>()
        .Case<Motorcycle>(bike => 100 + bike.Cylinders * 10) // "bike" here is typed as Motorcycle
        .Case<Bicycle>(30) // returns a constant
        .Case<Car>(car => car.EngineType == EngineType.Diesel, car => 220 + car.Doors * 20)
        .Case<Car>(car => car.EngineType == EngineType.Gasoline, car => 200 + car.Doors * 20)
        .ElseThrow(); // or could use a Default(...) terminator

where getRentPrice is a Func<Vehicle,int>.
[note - maybe Switch/Case here is the wrong terms... but it shows the idea]
To me, this is a lot clearer than the equivalent using repeated if/else, or a composite ternary conditional (which gets very messy for non-trivial expressions - brackets galore). It also avoids a lot of casting, and allows for simple extension (either directly or via extension methods) to more-specific matches, for example an InRange(...) match comparable to the VB Select...Case "x To y" usage.
I'm just trying to gauge if people think there is much benefit from constructs like the above (in the absence of language support)?
Note additionally that I've been playing with 3 variants of the above:

*

*a Func<TSource,TValue> version for evaluation - comparable to composite ternary conditional statements

*an Action<TSource> version - comparable to if/else if/else if/else if/else

*an Expression<Func<TSource,TValue>> version - as the first, but usable by arbitrary LINQ providers

Additionally, using the Expression-based version enables Expression-tree re-writing, essentially inlining all the branches into a single composite conditional Expression, rather than using repeated invocation. I haven't checked recently, but in some early Entity Framework builds I seem to recall this being necessary, as it didn't like InvocationExpression very much. It also allows more efficient usage with LINQ-to-Objects, since it avoids repeated delegate invocations - tests show a match like the above (using the Expression form) performing at the same speed [marginally quicker, in fact] compared to the equivalent C# composite conditional statement. For completeness, the Func<...> based-version took 4 times as long as the C# conditional statement, but is still very quick and is unlikely to be a major bottleneck in most use-cases.
I welcome any thoughts / input / critique / etc on the above (or on the possibilities of richer C# language support... here's hoping ;-p).

A: The purpose of pattern matching (as described here) is to deconstruct values according to their type specification. However, the concept of a class (or type) in C# doesn't agree with you.
There's nothing wrong with multi-paradigm language design, on the contrary, it's very nice to have lambdas in C#, and Haskell can do imperative stuff to e.g. IO. But it's not a very elegant solution, not in Haskell fashion.
But since sequential procedural programming languages can be understood in terms of lambda calculus, and C# happens to fit well within the parameters of a sequential procedural language, it's a good fit. But, taking something from the pure functional context of, say, Haskell, and then putting that feature into a language which is not pure, well, doing just that will not guarantee a better outcome.
My point is what makes pattern matching tick is tied to the language design and data model. Having said that, I don't believe pattern matching to be an useful feature of C# because it does not solve typical C# problems, nor does it fit well within the imperative programming paradigm.

A: In my humble opinion, the object oriented way of doing such things is the Visitor pattern. Your visitor member methods simply act as case constructs and you let the language itself handle the appropriate dispatch without having to "peek" at types.

A: Although it's not very 'C-sharpey' to switch on type, I know that construct would be pretty helpful in general use - I have at least one personal project that could use it (although its managable ATM). Is there much of a compile performance problem, with the expression tree re-writing?

A: After trying to do such "functional" things in C# (and even attempting a book on it), I've come to the conclusion that no, with a few exceptions, such things don't help too much.
The main reason is that languages such as F# get a lot of their power from truly supporting these features. Not "you can do it", but "it's simple, it's clear, it's expected".
For instance, in pattern matching, you get the compiler telling you if there's an incomplete match or when another match will never be hit. This is less useful with open ended types, but when matching a discriminated union or tuples, it's very nifty. In F#, you expect people to pattern match, and it instantly makes sense.
The "problem" is that once you start using some functional concepts, it's natural to want to continue. However, leveraging tuples, functions, partial method application and currying, pattern matching, nested functions, generics, monad support, etc. in C# gets very ugly, very quickly. It's fun, and some very smart people have done some very cool things in C#, but actually using it feels heavy.
What I have ended up using often (across-projects) in C#:

*

*Sequence functions, via extension methods for IEnumerable. Things like ForEach or Process ("Apply"? -- do an action on a sequence item as it's enumerated) fit in because C# syntax supports it well.

*Abstracting common statement patterns. Complicated try/catch/finally blocks or other involved (often heavily generic) code blocks. Extending LINQ-to-SQL fits in here too.

*Tuples, to some extent.

** But do note: The lack of automatic generalization and type inference really hinder the use of even these features. **
All this said, as someone else mentioned, on a small team, for a specific purpose, yes, perhaps they can help if you're stuck with C#. But in my experience, they usually felt like more hassle than they were worth - YMMV.
Some other links:

*

*Mono.Rocks playground has many similar things (as well as non-functional-programming-but-useful additions).

*Luca Bolognese's functional C# library

*Matthew Podwysocki's functional C# on MSDN

A: One thing to be careful of: the C# compiler is pretty good at optimising switch statements. Not just for short circuiting - you get completely different IL depending on how many cases you have and so on.
Your specific example does do something I'd find very useful - there is no syntax equivalent to case by type, as (for instance) typeof(Motorcycle) is not a constant.
This gets more interesting in dynamic application - your logic here could be easily data-driven, giving 'rule-engine' style execution.

A: Arguably the reason that C# doesn't make it simple to switch on type is because it is primarily an object-oriented language, and the 'correct' way to do this in object-oriented terms would be to define a GetRentPrice method on Vehicle and override it in derived classes.
That said, I've spent a bit of time playing with multi-paradigm and functional languages like F# and Haskell which have this type of capability, and I've come across a number of places where it would be useful before (e.g. when you are not writing the types you need to switch on so you cannot implement a virtual method on them) and it's something I'd welcome into the language along with discriminated unions.
[Edit: Removed part about performance as Marc indicated it could be short-circuited]
Another potential problem is a usability one - it's clear from the final call what happens if the match fails to meet any conditions, but what is the behaviour if it matches two or more conditions? Should it throw an exception? Should it return the first or the last match?
A way I tend to use to solve this kind of problem is to use a dictionary field with the type as the key and the lambda as the value, which is pretty terse to construct using object initializer syntax; however, this only accounts for the concrete type and doesn't allow additional predicates so may not be suitable for more complex cases. [Side note - if you look at the output of the C# compiler it frequently converts switch statements to dictionary-based jump tables, so there doesn't appear to be a good reason it couldn't support switching on types]

A: I don't think these sorts of libraries (which act like language extensions) are likely to gain wide acceptance, but they are fun to play with, and can be really useful for small teams working in specific domains where this is useful.  For instance, if you are writing tons of 'business rules/logic' that does arbitrary type tests like this and whatnot, I can see how it would be handy.
I've no clue if this is ever likely to be a C# language feature (seems doubtful, but who can see the future?).
For reference, the corresponding F# is approximately:
let getRentPrice (v : Vehicle) =
    match v with
    | :? Motorcycle as bike -> 100 + bike.Cylinders * 10
    | :? Bicycle -> 30
    | :? Car as car when car.EngineType = Diesel -> 220 + car.Doors * 20
    | :? Car as car when car.EngineType = Gasoline -> 200 + car.Doors * 20
    | _ -> failwith "blah"

assuming you'd defined a class hierarchy along the lines of
type Vehicle() = class end

type Motorcycle(cyl : int) =
    inherit Vehicle()
    member this.Cylinders = cyl

type Bicycle() = inherit Vehicle()

type EngineType = Diesel | Gasoline

type Car(engType : EngineType, doors : int) =
    inherit Vehicle()
    member this.EngineType = engType
    member this.Doors = doors

A: In C# 7, you can do:
switch(shape)
{
    case Circle c:
        WriteLine($"circle with radius {c.Radius}");
        break;
    case Rectangle s when (s.Length == s.Height):
        WriteLine($"{s.Length} x {s.Height} square");
        break;
    case Rectangle r:
        WriteLine($"{r.Length} x {r.Height} rectangle");
        break;
    default:
        WriteLine("<unknown shape>");
        break;
    case null:
        throw new ArgumentNullException(nameof(shape));
}

A: Yes I think pattern matching syntactic constructs are useful. I for one would like to see syntactic support in C# for it.
Here is my implementation of a class that provides (nearly) the same syntax as you describe
public class PatternMatcher<Output>
{
    List<Tuple<Predicate<Object>, Func<Object, Output>>> cases = new List<Tuple<Predicate<object>,Func<object,Output>>>();

    public PatternMatcher() { }

    public PatternMatcher<Output> Case(Predicate<Object> condition, Func<Object, Output> function)
    {
        cases.Add(new Tuple<Predicate<Object>, Func<Object, Output>>(condition, function));
        return this;
    }

    public PatternMatcher<Output> Case<T>(Predicate<T> condition, Func<T, Output> function)
    {
        return Case(
            o => o is T && condition((T)o),
            o => function((T)o));
    }

    public PatternMatcher<Output> Case<T>(Func<T, Output> function)
    {
        return Case(
            o => o is T,
            o => function((T)o));
    }

    public PatternMatcher<Output> Case<T>(Predicate<T> condition, Output o)
    {
        return Case(condition, x => o);
    }

    public PatternMatcher<Output> Case<T>(Output o)
    {
        return Case<T>(x => o);
    }

    public PatternMatcher<Output> Default(Func<Object, Output> function)
    {
        return Case(o => true, function);
    }

    public PatternMatcher<Output> Default(Output o)
    {
        return Default(x => o);
    }

    public Output Match(Object o)
    {
        foreach (var tuple in cases)
            if (tuple.Item1(o))
                return tuple.Item2(o);
        throw new Exception("Failed to match");
    }
}

Here is some test code:
    public enum EngineType
    {
        Diesel,
        Gasoline
    }

    public class Bicycle
    {
        public int Cylinders;
    }

    public class Car
    {
        public EngineType EngineType;
        public int Doors;
    }

    public class MotorCycle
    {
        public int Cylinders;
    }

    public void Run()
    {
        var getRentPrice = new PatternMatcher<int>()
            .Case<MotorCycle>(bike => 100 + bike.Cylinders * 10)
            .Case<Bicycle>(30)
            .Case<Car>(car => car.EngineType == EngineType.Diesel, car => 220 + car.Doors * 20)
            .Case<Car>(car => car.EngineType == EngineType.Gasoline, car => 200 + car.Doors * 20)
            .Default(0);

        var vehicles = new object[] {
            new Car { EngineType = EngineType.Diesel, Doors = 2 },
            new Car { EngineType = EngineType.Diesel, Doors = 4 },
            new Car { EngineType = EngineType.Gasoline, Doors = 3 },
            new Car { EngineType = EngineType.Gasoline, Doors = 5 },
            new Bicycle(),
            new MotorCycle { Cylinders = 2 },
            new MotorCycle { Cylinders = 3 },
        };

        foreach (var v in vehicles)
        {
            Console.WriteLine("Vehicle of type {0} costs {1} to rent", v.GetType(), getRentPrice.Match(v));
        }
    }

A: You can achieve what you are after by using a library I wrote, called OneOf
The major advantage over switch (and if and exceptions as control flow) is that it is compile-time safe - there is no default handler or fall through
   OneOf<Motorcycle, Bicycle, Car> vehicle = ... //assign from one of those types
   var getRentPrice = vehicle
        .Match(
            bike => 100 + bike.Cylinders * 10, // "bike" here is typed as Motorcycle
            bike => 30, // returns a constant
            car => car.EngineType.Match(
                diesel => 220 + car.Doors * 20
                petrol => 200 + car.Doors * 20
            )
        );

It's on Nuget and targets net451 and netstandard1.6


text:
Q: Save data in DPS for synchronisation I want to build an app with DPS which will embed a HTML/JS module.
This module will display a form with several questions. After the user completes it, I would like to :
1- Send his choices to a database (with some ajax I guess)
OR
2- Store data in the app for further synchronisation
I did not find how to save data offline (like some kind of database), does someone have any idea ?
Thank you.

A: Well I finally found this post from turutosiya. It pretty much answered my questions, time to develop it now.


text:
Q: Data got corrupted and unable to open a excel file after i export to excel in angular Able to to export an excel file in angular using exceljs and filesaver. But when i open a file nothing was displayed . I am using excel 2013. Since i want to format the data and make the alignment during export im using exceljs.
Performed npm install and imported like this for exceljs and filesaver below
    import * as Excel from "exceljs/dist/exceljs.min.js";
    import * as ExcelProper from "exceljs";
    import * as fs from 'file-saver';

    generateExcel() {

        //Excel Title, Header, Data
        const title = 'Car Sell Report';
        const header = ["Year", "Month", "Make", "Model", "Quantity", "Pct"]
        const data = [
          [2007, 1, "Volkswagen ", "Volkswagen Passat", 1267, 10],
          [2007, 1, "Toyota ", "Toyota Rav4", 819, 6.5],
          [2007, 1, "Toyota ", "Toyota Avensis", 787, 6.2],
          [2007, 1, "Volkswagen ", "Volkswagen Golf", 720, 5.7],
          [2007, 1, "Toyota ", "Toyota Corolla", 691, 5.4],
          [2007, 1, "Peugeot ", "Peugeot 307", 481, 3.8],
          [2008, 1, "Toyota ", "Toyota Prius", 217, 2.2],
          [2008, 1, "Skoda ", "Skoda Octavia", 216, 2.2],
          [2008, 1, "Peugeot ", "Peugeot 308", 135, 1.4],
          [2008, 2, "Ford ", "Ford Mondeo", 624, 5.9],
          [2008, 2, "Volkswagen ", "Volkswagen Passat", 551, 5.2],
          [2008, 2, "Volkswagen ", "Volkswagen Golf", 488, 4.6],
          [2008, 2, "Volvo ", "Volvo V70", 392, 3.7],
          [2008, 2, "Toyota ", "Toyota Auris", 342, 3.2],
          [2008, 2, "Volkswagen ", "Volkswagen Tiguan", 340, 3.2],
          [2008, 2, "Toyota ", "Toyota Avensis", 315, 3],
          [2008, 2, "Nissan ", "Nissan Qashqai", 272, 2.6],
          [2008, 2, "Nissan ", "Nissan X-Trail", 271, 2.6],
          [2008, 2, "Mitsubishi ", "Mitsubishi Outlander", 257, 2.4],
          [2008, 2, "Toyota ", "Toyota Rav4", 250, 2.4],
          [2008, 2, "Ford ", "Ford Focus", 235, 2.2],
          [2008, 2, "Skoda ", "Skoda Octavia", 225, 2.1],
          [2008, 2, "Toyota ", "Toyota Yaris", 222, 2.1],
          [2008, 2, "Honda ", "Honda CR-V", 219, 2.1],
          [2008, 2, "Audi ", "Audi A4", 200, 1.9],
          [2008, 2, "BMW ", "BMW 3-serie", 184, 1.7],
          [2008, 2, "Toyota ", "Toyota Prius", 165, 1.6],
          [2008, 2, "Peugeot ", "Peugeot 207", 144, 1.4]
        ];
        //Create workbook and worksheet
        let workbook: ExcelProper.Workbook = new Excel.Workbook();
        let worksheet = workbook.addWorksheet('Car Data');
        //Add Row and formatting
        let titleRow = worksheet.addRow([title]);
        titleRow.font = { name: 'Comic Sans MS', family: 4, size: 16, underline: 'double', bold: true }
        worksheet.addRow([]);
        // let subTitleRow = worksheet.addRow(['Date : ' + this.datePipe.transform(new Date(), 'medium')])

        worksheet.mergeCells('A1:D2');
        //Blank Row
        worksheet.addRow([]);
        //Add Header Row
        let headerRow = worksheet.addRow(header);

        // Cell Style : Fill and Border
        headerRow.eachCell((cell, number) => {
          cell.fill = {
            type: 'pattern',
            pattern: 'solid',
            fgColor: { argb: 'FFFFFF00' },
            bgColor: { argb: 'FF0000FF' }
          }
          cell.border = { top: { style: 'thin' }, left: { style: 'thin' }, bottom: { style: 'thin' }, right: { style: 'thin' } }
        })
        // worksheet.addRows(data);
        // Add Data and Conditional Formatting
        data.forEach(d => {
          let row = worksheet.addRow(d);
          let qty = row.getCell(5);
          let color = 'FF99FF99';
          if (+qty.value < 500) {
            color = 'FF9999'
          }
          qty.fill = {
            type: 'pattern',
            pattern: 'solid',
            fgColor: { argb: color }
          }
        }
        );

    worksheet.getColumn(3).width = 30;
        worksheet.getColumn(4).width = 30;
        worksheet.addRow([]);
        //Footer Row
        let footerRow = worksheet.addRow(['This is system generated excel sheet.']);
        footerRow.getCell(1).fill = {
          type: 'pattern',
          pattern: 'solid',
          fgColor: { argb: 'FFCCFFE5' }
        };
        footerRow.getCell(1).border = { top: { style: 'thin' }, left: { style: 'thin' }, bottom: { style: 'thin' }, right: { style: 'thin' } }
        //Merge Cells
        worksheet.mergeCells(`A${footerRow.number}:F${footerRow.number}`);
        //Generate Excel File with given name
        workbook.xlsx.writeBuffer().then((data: any) => {
          let blob = new Blob([data], { type:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
          fs.saveAs(blob, 'CarData.xlsx');
        })

  }


text:
Q: VueJS: How to determinate the "from" route, when route in URL is directly entered in browser? I have a Vue application and a few routes (let's refer to them as "homepage", "first_route" and "second_route"). Before loading the component for the "first_route" route, I want to check from where the user comes from.
There are two options:

*

*there is a menu in the app and when user clicks in the menu, he will try to access to the corresponding clicked route (imagine this as a simple menu with items like "Dashboard", "About Us", "Contact" pages, just in my case will be "First Route Page", "Second Route Page" and I will also have the route "/" in this menu, which is the "HomePage" of my application);

*while user is on a certain route, he can refresh the browser, which will load his current route again OR while he is on a different site (google for example) he can try to directly open the route like "www.mypage.com/first_route"

In general, the idea is:

*

*if the user comes from the current application (internal - if he clicks in it)

*if the user comes from some external site or if he refresh the page

I'm posting my code below and I'm having issue in forming the if condition in the block below:
    export default new Router({
        mode: 'history',
        routes: [
            {
                path: "/",
                component: HomePage
            },
            {
                path: "/first_route",
                component: FirstRoutePage,
                beforeEnter (to, from, next) {
                    if (check where the route comes from)
                        // do something if the route comes from page refresh
                        // or if user directly entered "/first_route" from external site
                    } else {
                        // do something else if the route comes as a result of
                        // a user click from another route (internal, from the menu)
                    }
                }
            },
            {
                path: "/second_route",
                component: SecondRoutePage
            }
]

What I tried is to check:
beforeEnter (to, from, next) {
    if (to.path == from.path)
        // do something if the route comes from page refresh
        // or if user directly entered "/first_route" from external site
    } else {
        // do something else if the route comes as a result of
        // a user click from another route (internal, from the menu)
    }
}

But this covers only the case when user refreshes the browser. The case when user enters directly the full URL into the browser is not covered with this solution.
The main problem is: when user enters directly the full URL into the browser, the value which is recognized for the from route for from.path is "/". If we are in the "HomePage" (which route is "/" and if user clicks on the menu and chooses the "/first_route" page) then we will have the same condition to be true.
In the both cases the from and to routes are identical. And this is the contradictory thing: in the first case we are coming from the external site and in the second case we are coming from the "/" route (HomePage) but in the both cases the same condition (from.path == "/" && to.path == "/first_route") is true, so I can not determinate which of the main two scenarios (from above) was hit.

A: you could try do this in your created() method.
if (this.$route.params.id)
        // do something if the route comes from page refresh
        // or if user directly entered "/first_route" from external site
    } else {
        // do something else if the route comes as a result of
        // a user click from another route (internal, from the menu)
    }

and in your router just set the id.
{
      path: '/example/:id/',
      name: 'example',
      component: () => import(/* webpackChunkName: "about" */ './components/example.vue')
    }


text:
Q: Javascript to Get Month/Year WITHOUT Alert Popup Found this code that generates a future date just like I need. But it only show it via a pop up. How can I get it to display automatically on my webpage, versus a popup.
<script>
var days = 300;
var date = new Date();
date.setDate(date.getDate() + days);
alert ( date.getMonth()+1 + "/" + date.getFullYear() ) ;

</script>

A: Try this

var days = 300;
var date = new Date();
date.setDate(date.getDate() + days);
document.getElementById('test').innerHTML = date.getMonth()+1 + "/" + date.getFullYear();
<div id="test">
</div>


text:
Q: How to catch enter keypress on textarea but not shift+enter? I'm doing it for texarea. A function should be called when the user press Enter, but nothing should be done when Shift + Enter be pressed.
I try to simulate here a feature that many IM communicators have: sending a message on Enter but also adding multiple lines using Shift + Enter.

A: Test for the enter keycode (13) and if shift key was pressed.
...onkeyup = function(e) {
    if (e.keyCode == 13)
    {
//      if (e.shiftKey === true)
        if (e.shiftKey)  // thruthy
        {
            // new line
        }
        else
        {
            // run your function
        }
        return false;
    }
}

Edit: Accept all truthy values of e.shiftKey

A: element.onkeydown = function(o) {
  o = o || event;
  if (o.shiftKey && o.keyCode == 13) {
    /* shift + enter pressed */
  }
}

A: I believe you need a keydown event as well to check for the SHIFT key, http://www.quirksmode.org/js/keys.html

A: Look at the shiftKey property of the event object which will tell you if shift was held while the key was pressed.


text:
Q: Probability - independence questions 1) Given that two events $A$ and $B$ are independent if $\text{Pr}(A∩B)=\text{Pr}(A)\text{Pr}(B)$, prove that if $\text{Pr}(B)>0$ then $A$ and $B$ are independent if and only if $\text{Pr}(A|B)=\text{Pr}(A)$.
My thinking is that if $\text{Pr}(A|B) = \text{Pr}(A∩B)/\text{Pr}(B) = \text{Pr}(A)$, then $\text{Pr}(B)$ must be $1$ and $\text{Pr}(A∩B)$ has to be $\text{Pr}(A)$. But I'm not sure what to do after that.
2) Let $A$ and $B$ be independent events. Show $\overline{A}$ and $\overline{B}$ are also independent, where $\overline{A}=Ω \setminus A$.

A: 1) $\textbf{Proof}$. Assume $\text{Pr}(B)>0$. Assume that the events $A$ and $B$ are independent. Then
$$
\text{Pr}(A|B) = \dfrac{\text{Pr}(A\cap B)}{\text{Pr}(B)} = \dfrac{\text{Pr}(A)\text{Pr}(B)}{\text{Pr}(B)} = \text{Pr}(A).
$$
On the other hand, if $\text{Pr}(A|B)=\text{Pr}(A)$, then
$$
\text{Pr}(A|B) = \dfrac{\text{Pr}(A \cap B)}{\text{Pr}(B)}=\text{Pr}(A).
$$
Since $\text{Pr}(A\cap B)=\text{Pr}(A)\text{Pr}(B)$, we conclude that $A$ and $B$ are independent.
2) $\textbf{Proof}$. Assume $A$ and $B$ are independent events. Let $\overline{A}=\Omega\setminus A$.
Then we have
$$
\begin{aligned}
\text{Pr}(\overline{A}\cap \overline{B}) &= \text{Pr}((\Omega\setminus A) \cap (\Omega\setminus B)) \\
&= \text{Pr}(\Omega\setminus (A\cup B)) \\
&= \text{Pr}(\Omega) - \text{Pr}(A\cup B) \\
&= 1 - (\text{Pr}(A)+\text{Pr}(B)-\text{Pr}(A\cap B)) \\
&= 1 - (\text{Pr}(A)+\text{Pr}(B)-\text{Pr}(A) \text{Pr}(B)) \\
&= 1 - (\text{Pr}(A)+\text{Pr}(B))+\text{Pr}(A) \text{Pr}(B). \\
\end{aligned}
$$
On the other hand,
$$
\begin{aligned}
\text{Pr}(\overline{A})\text{Pr}(\overline{B}) &=
(1-\text{Pr}(A))(1-\text{Pr}(B)) \\
&= 1-(\text{Pr}(A)+\text{Pr}(B)) +\text{Pr}(A)\text{Pr}(B). \\
\end{aligned}
$$
Since $\text{Pr}(\overline{A}\cap \overline{B})=\text{Pr}(\overline{A})\text{Pr}(\overline{B})$, events $\overline{A}$ and $\overline{B}$ are also independent.

A: HINT
Use $P(A \cup B) = P(A) + P(B) -P(A \cap B)$


text:
Q: Define a function as argument and passing a number in Racket I'm trying to define a function as an argument and then passing a number to that function. It should look like this:
> (function-3 sqrt)

1.7320508075688772

I was thinking of just defining function-3 to equal to 3 but it seems like it doesn't work... this is what I have so far:
(define function-3
   (λ (x)
     (3)))

I don't know if I'm thinking on the right path...but it would be great if someone can just point me in the right direction. Thanks

A: You're close—you just want to apply the argument of function-3 to the number 3, like this:
(define function-3
  (λ (x)
    (x 3)))

More idiomatically, using the shorthand function syntax, it would probably be written like this:
(define (function-3 f)
  (f 3))

(The name f is often used instead of x when the value is a function.)

But why?
Functions in Racket (as in its parent language, Scheme) are just ordinary values. Behind all the parentheses, the syntax for function application is actually extremely simple. Here's an example scheme expression:
                 (f a b c)
                  ^ ^^^^^
                  |   |
function expression   argument expressions

Note that each of these two roles is an expression. Obviously, the arguments can be expressions, not just variables, since you can do things like this:
> (+ 1 (* 2 3))
7

Notably, though, the function itself can be an expression, too. You can have a form that produces a function, and that expression can be used in a function invocation:
> ((λ (x) (* x 2)) 3)
6

So when you call (function-3 sqrt), the sqrt function itself gets passed into the function and bound to the first argument of the function implementation. Therefore, all you need to do is put that argument in function expression position, and it will be invoked like any other function.

A: You're so close!
(define function-3
  (lambda (x)
    (x 3)))


text:
Q: How can I replace commas per newlines, but only if they are not between brackets? I was wondering if you could help me with a replacement script im trying here...
I've got something like this:
aaaaaa,aaaaa,aaaaa,aaaa,aaaaa,aaa,aaa,aaa,aaaa,aaa
aaaa,aaaaa,aaaaa,aaaaaaa,aaa[1,2], aaaaaaaa[5,6], aaaa,aaaaaaa

and want to order the file to get something like:
aaaaaa,
aaa,
aaaaa,
aaaaa[1,2],
aaaaaaaa[5,6],
aaaaa,
aaaaaaaa,
aaaa

I've tried replacing , with line-breaks, but it separates the [n,n] blocks, too.
Also tried replacing ,[^0-9] with line-breaks, but I loose the first char after the comma.
I've been trying sed, but I'm not sure how this would look like.
I've added a sample of the file:
x0.fieldB [1,2] ,x5.fieldC ,x0.fieldX ,x0.fieldA
(x0.fieldE [1,5] = x2.fieldZ) ) AND (x0.fieldG [1,2] = x3.fieldT ) )

and should get something like this:
x0.fieldB [1,2] ,
x5.fieldC ,
x0.fieldX ,
x0.fieldA (x0.fieldE [1,5] = x2.fieldZ) ) AND (x0.fieldG [1,2] = x3.fieldT ) )

A: In order to not lose that digit, you need to capture it with (escaped) parenthesis, and then substitute it with \1 as follows:
sed 's/\([^0-9]\),/\1\n/g' yourfile

A: Quick and dirty fix: Replace , and <]>, with enters.

A: Here is one solution that works in your case:
sed -e 's;\([A-Za-z \t]\),;\1,\n;g' -e 's;],;],\n;g'

What it does is replaces comma after any character in ranges A-Z or a-z, or a whitespace. And then replaces all ], occurrences. Seems to do exactly what you want. I am not a regexp or sed expert and most likely this can be written much better, so don't blame me :-)


text:
Q: Pandas - Groupby and Standardize I have tried to tackle this for quite some time, but haven't been able to get a pythonic way around it by using the built-in groupby and transform methods from pandas.
The goal is to group the data by columns ex_date and id, then within the groups identified, standardize the column called ref_value_1 against the value found in the row where df['calc_date'] == df['ex_date']
Here's a sample input:
df = pd.DataFrame({'calc_date': ['1/1/2021', '2/1/2021', '3/1/2021', '1/1/2021', '2/1/2021', '3/1/2021', '1/1/2021', '2/1/2021', '3/1/2021', '1/1/2021', '2/1/2021', '3/1/2021'], 'ex_date': ['2/1/2021', '2/1/2021', '2/1/2021', '2/1/2021', '2/1/2021', '2/1/2021', '2/1/2021', '2/1/2021', '2/1/2021', '2/1/2021', '2/1/2021', '2/1/2021'], 'id': [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4], 'ref_value_1': [1.5, 3.0, 4.5, 5.0, 10.0, 15.0, 15.0, 40.0, 60.0, 75.0, 100.0, 120.0], 'bins': [1, 1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3]})

which looks like:

calc_date
ex_date
id
ref_value_1
bins

1/1/2021
2/1/2021
1
1.5
1

2/1/2021
2/1/2021
1
3
1

3/1/2021
2/1/2021
1
4.5
1

1/1/2021
2/1/2021
2
5
1

2/1/2021
2/1/2021
2
10
1

3/1/2021
2/1/2021
2
15
1

1/1/2021
2/1/2021
3
15
2

2/1/2021
2/1/2021
3
40
2

3/1/2021
2/1/2021
3
60
2

1/1/2021
2/1/2021
4
75
3

2/1/2021
2/1/2021
4
100
3

3/1/2021
2/1/2021
4
120
3

And expected output:

calc_date
ex_date
id
ref_value_1
bins
standardized_val

1/1/2021
2/1/2021
1
1.5
1
0.5

2/1/2021
2/1/2021
1
3
1
1

3/1/2021
2/1/2021
1
4.5
1
1.5

1/1/2021
2/1/2021
2
5
1
0.5

2/1/2021
2/1/2021
2
10
1
1

3/1/2021
2/1/2021
2
15
1
1.5

1/1/2021
2/1/2021
3
15
2
0.375

2/1/2021
2/1/2021
3
40
2
1

3/1/2021
2/1/2021
3
60
2
1.5

1/1/2021
2/1/2021
4
75
3
0.75

2/1/2021
2/1/2021
4
100
3
1

3/1/2021
2/1/2021
4
120
3
1.2

A: You can mask the non matching values and fill per group using groupby+transform to get the reference. Then simply divide your data with the reference.
ref = df['ref_value_1'].where(df['calc_date'].eq(df['ex_date'])).groupby(df['id']).transform('first')

df['standardized_val'] = df['ref_value_1'].div(ref)

Output:
   calc_date   ex_date  id  ref_value_1  bins  standardized_val
0   1/1/2021  2/1/2021   1          1.5     1             0.500
1   2/1/2021  2/1/2021   1          3.0     1             1.000
2   3/1/2021  2/1/2021   1          4.5     1             1.500
3   1/1/2021  2/1/2021   2          5.0     1             0.500
4   2/1/2021  2/1/2021   2         10.0     1             1.000
5   3/1/2021  2/1/2021   2         15.0     1             1.500
6   1/1/2021  2/1/2021   3         15.0     2             0.375
7   2/1/2021  2/1/2021   3         40.0     2             1.000
8   3/1/2021  2/1/2021   3         60.0     2             1.500
9   1/1/2021  2/1/2021   4         75.0     3             0.750
10  2/1/2021  2/1/2021   4        100.0     3             1.000
11  3/1/2021  2/1/2021   4        120.0     3             1.200


text:
Q: Why is this question about googling closed as off topic? The question: Tips for using Google when looking for C stuff, rather than C++?
The FAQ says the following:

We feel the best Stack Overflow questions have a bit of source code in
  them, but if your question generally covers …

*

*software tools commonly used by programmers

I definitely consider Google to be a software tool commonly used by programmers. The question I asked also is a real problem I have with this tool, and looking to solve. So why was it closed?

A: Google is a tool that programmers use, but it's hardly exclusive to programmers. There are a seemingly infinite number of verbs that can come after "As a [foo] programmer, how do I .." .. and we're simply not equipped to handle that. Consider the following:

Well, darn it, you let the person wondering how to use Google as a programmer ask their question, why can't I ask the same about Excel?

Sooner or later, you'll get someone asking about boating as a programmer. That, actually happened. Programmers could conceivably use anything to get our jobs done, heck we use rubber ducks. We have to draw a line, so we ask that the tool you're asking about be rather exclusively used by programmers. That is what is meant by tools that programmers use.
If you've got a question about an editor, a compiler, a debugger .. we're here to help provided that the problem relates to programming. Tips on how to narrow down Google searches (essentially, what you're asking) are of a far broader interest than a very programming specific community.

A: "How to Google something?" is not really a programming question. Even if you end up Google-ing programming related content. So as such I would say it's off topic.
The whole "software tool commonly used by programmers" angle doesn't really work either. I'm sure most of us commonly use a browser. Or some IM program. That doesn't mean questions about those fall under this header. Questions about IDEs, compilers, etc. would fall under this header.
All in all, I would say it's off-topic indeed.


text:
Q: ES6 de-structuring - what does this do? I'm trying to understand this ES6 de-structuring. Can someone explain what this line of code will compile to?
const { loading, route: { pageName = 'default' } = {} } = this.props;

A: let props = {

    loading: 'Loading value goes here',
    route : {
        pageName: 'pagename value goes here'
    }
}

without de-structuring
const loading = props.loading;
const route = props.route.pageName || 'default';

with de-structuring
const { loading, route: { pageName = 'default' } = {} } = props;

we define distinct variables left-hand side of the assignment to define what values to unpack from the sourced variable.
loading and pageName are variables
props is sourced variable
we have just unpack the props object properties  by give the properties name to left-hand assignment.
we can also unpack nested object as you can see route is nested object in props
so in  de-structuring we will unpack the object properties
here we give pageName default value if it is undefined
For more info check

A: From props you are getting 2 parameters loading & pageName. If pageName has no value (undefined) it will get the default string value "default".
you need to write "route" too to check nested key (pageName) if there is no route key in this.props you provide default value (empty object)

A: const { loading, route: { pageName = 'default' } = {} } = this.props;

I would write it as below for you to grasp easily :
const
    {
      loading,
      route: {
               pageName = 'default'
             }
    }

this.props is like so :
    {
      loading,
      route: {
               pageName
             }
    }

Now this would just map the properties exactly no matter how deep. So whatever is in this.props.loading will go into loading counterpart in const. Whatever is in the this.props.route.pageName will go into route.pageName in the const. If pageName is empty or undefined in the props then 'default' value will be there. It is just like the default value is provided for an argument of a function if nothing is provided for that in the function call.

A: In simplest form it will compile to
const loading = this.props.loading ;
let pageName ;
let route ;
if(this.props.route){
  route = this.props.route ;
  if(this.props.route. pageName){
     pageName = this.props.route. pageName ;
  } else {
    pageName = 'default' ;
  }
} else{
 route = {};
}


text:
Q: Kubernetes system:serviceaccount:default denied access So does anyone know exactly what I need to put in my ServiceAccount yaml in order not to be denied access to my ServiceAccount when i try to list things via the REST API:
curl https://$KUBERNETES_SERVICE_HOST:$KUBERNETES_PORT_443_TCP_PORT/api/v1/namespaces/default/persistentvolumeclaims -X GET -k -H "Authorization: Bearer $(cat /var/run/secrets/kubernetes.io/serviceaccount/token)"
User "system:serviceaccount:default:my-service-service-account" cannot list persistentvolumeclaims in the namespace "default".
My RBAC serviceAccount is setup as follows in the YAML:
apiVersion: v1
kind: ServiceAccount
metadata:
  name: {{ .Values.service.name }}-service-account
  labels:
    app: {{ .Values.service.name }}
automountServiceAccountToken: true
---
kind: Role
apiVersion: rbac.authorization.k8s.io/v1beta1
metadata:
  namespace: default
  name: {{ .Values.service.name }}-role
  labels:
    app: {{ .Values.service.name }}
rules:
- apiGroups: [""] # "" indicates the core API group
  resources: ["pods"]
  verbs: ["get", "watch", "list","delete"]
- apiGroups: [""] # "" indicates the core API group
  resources: ["persistentvolumeclaims"]
  verbs: ["get", "watch", "list","delete"]
---
apiVersion: rbac.authorization.k8s.io/v1beta1
kind: RoleBinding
metadata:
  name: {{ .Values.service.name }}-role-binding
  labels:
    app: {{ .Values.service.name }}
subjects:
  - kind: ServiceAccount
    # Reference to upper's `metadata.name`
    name: {{ .Values.service.name }}-service-account
    # Reference to upper's `metadata.namespace`
    namespace: default
roleRef:
  kind: Role
  name: {{ .Values.service.name }}-role
  apiGroup: rbac.authorization.k8s.io

A: The role you've shown only allows get/list/watch/delete permissions on pods in the default namespace
If you want list permissions on persistent volume claims, you need to include that verb and resource in your role as well


text:
Q: WSO2 Share same user between two tenants I have a user in tenant1 and i want the same user with same password in tenant2 also. How to achieve this in WSO2.
I did some workaround by creating same username and password in multiple tenants but this would break if any one of the tenant's password changed
Basically how to share same user between multiple tenants in WSO2 Identity Server? I am using wso2is 5.1.0

A: You can add the same userstore for both tenants as secondary userstores.
https://docs.wso2.com/display/IS530/Configuring+Secondary+User+Stores


text:
Q: background-attachment: fixed for  with object-fit cover? Is there a trick or workaround to make image with object-fit:cover and absolute positioning in parent to behave like background-attachment: fixed in css?
I want this:

    <img src="" style="object-fit: cover; position: absolute; width: 100%; height: 100%;"

to have same functionality as this:

A: position:fixed combined with a clip-path trick can do it

section {
  height: 100px;
  margin: 30px 5px;
  clip-path: inset(0);
}

body {
  min-height: 300vh;
}


text:
Q: Click function doesn't work after ajax call in dynamic element (Backbone) I've create dynamic popup in my Backbone.view by clicking button:
var Section = Backbone.View.extend({
className: 'sqs-frontend-overlay-editor-widget-section',
events:{
    'click .sqs--section--control__edit':           'Section_control'
},

initialize: function(){

},

render: function(){
    this.$el.append(_.template(_section).apply(this.options));
    return this.$el;
},

Section_control: function(){
    var me = this;
    require(['View/Popup/Section_control'], function(_Section_control){
        var sec     = new _Section_control({popup: popup, sec: me.options.section});
        var popup   = new Popup({content: sec.render()});
    });
}
});
return Section;

in the created dynamic popup i have button with trigger:
    events:{
        'click .module-invert-mode':    'invert'
    },

    invert: function(e){
            console.log('hello');

            if(this.options.sec.hasClass('.module-invert')) {
                console.log('yse');
            }

            this.options.sec.toggleClass('module-invert');
            this.options.sec.trigger('invertChange');

    },

and button invertChange trigger:
    el.on("invertChange", function(e){
        var section = el.parents('section');
        var index   = section.index();
        var model   = collection.at(index);
        model.set(Helper.sectionToObj(section),{doReload: true})
    });

take a look at the {doReload: true} function that i call in invertChange:
    change: function(model, options){
        me = this;

        if( model._changing && options.doReload ) {
            $.ajax({
                url: 'wp-admin/admin-ajax.php',
                type: 'post',
                data: {
                    action: 'getShortcode',
                    shortcode: model.attributes.shortcode
                },
                success: function (data) {
                    //var section = $(data);
                    me.$el.find('section:eq(' + model.collection.indexOf(model) + ')').replaceWith(data);
                    me.add( model, model.collection );
                    //me.collection.add({shortcode: model.attributes.shortcode}, {at: section.index()});
                }
            });
        }
    },

the problem is when I create dynamic popup and click on the button with invertChange trigger, ajax works only once, when I click on button in popup again, ajax doesn't works ( next ajax request works only if close and create dynamic popup again). How I can call ajax without constantly closing and opening my dynamic popup?

A: The problem that you have code which overrides child views
me.$el.find('section:eq(' + model.collection.indexOf(model) + ')').replaceWith(data);

And this listener is not able to handle event
el.on("invertChange", function(e){

because your code
this.options.sec.trigger('invertChange');

doesn't trigger event on correct view, it has lost the reference to this view after replaceWith()
As a solution you need parse your data object and apply each changes locally to elements
something like this
$(data).find("* [attr]").each(function(i, el) {
    var $el = $(el),
        attr = $el.attr("attr"),
        $parent = me.$el.find('section:eq(' + model.collection.indexOf(model) + ')');
    if ($el.is("div, span")) {
        $parent.find('[attr=' + attr + ']').html($el.html());
    } else if ($el.is("img")) {
        $parent.find('[attr=' + attr + ']').attr("src", $el.attr("src"));
    } else if ($el.is("a")) {
        $parent.find('[attr=' + attr + ']').attr("href", $el.attr("href"));
    } else if (attr == "image_back_one") {
        $parent.find('[attr=' + attr + ']').attr("style", $el.attr("style"));
    } else {
        console.log($el);
    }
});


text:
Q: Access WebRole data from .aspx page I am working on TCP/IP in Windows Azure and am successfully able to develop a TCP client to send and web-role to receive the TCP data.
I want to display this received data in a .aspx page. How should I access the webrole data from .aspx page?
Regards,
Anil

A: Having read the long comment stream, I think I get the essence of this scenario and question. It appears that there's some tcp-listener code being launched from within webrole.cs, not within the asp.net app code.
Here's the thing: A Web Role is Windows Server 2008 with IIS, along with some Windows Azure code for handling bootstrap and shutdown tasks. The webrole.cs file you speak of is the bootstrap/shutdown code entry point, with methods such as OnStart(), Run(), OnStop(), and Stopping(). This code is run in a separate AppDomain than your web app.
If you're launching a ServiceHost (or some other port listener) from webrole.cs, that's fine, but you'd need to then store content somewhere temporarily after it's uploaded, then make it available for your web app later. You could choose durable storage such as SQL Azure or Azure Storage (blobs or tables), or volatile storage (e.g. a local disk). You could then use some type of communication scheme to notify your web app that it has new data display, possibly by placing a message on an Azure queue, or having your web app just query a table for data each time a user requests it.


text:
Q: Detecting newlines in textbox content and creating an array I got a mediocre problem with my php script showing me the finger whenever I try to split the contents of a textbox from another page by its newline characters. The reasons could be multiple as I'm not that familiar with php (normally C#).
Maybe I messed up with the newline detection. Mabye that textbox produces something else than "\n" for breaks.
The plan is to detect special characters and if they're not contained, then add something and save to a file. If there are several lines, create an array by splitting at newline, add something to all the parts and save each one of them in a file.
Code for the textbox:
<form method='post' action='../inc/convert.php'>

            Enter sequence here:
            <textarea id="seq" class="reset" name="textbox_input" cols="80" rows="5" style="width: 489px; height: 135px;"></textarea>

        <input type="submit" name="textbox_text" align="middle" />

    </form>

Code for the php script:
<?php
$textbox_content = $_POST['textbox_input'];
//$post = print_r($_POST, true);
//file_put_contents("../files/meh.txt", $post);

if (strpos($textbox_content,'<') !== false)
{
    echo "unallowed syntax!";
}
else
{
$appearance = substr_count( $textbox_content , '\n');

switch(true) #if sequence doesn't have a multifasta format
{
    case ($appearance == 0):

        if (strpos($textbox_content,'>') !== true) #if just one sequence without fasta format
        {
            $santas = ">Organism.1 Indentifier.1 / 0-0 ";
            $helper = $santas . $textbox_content;
            $file = "../files/file1.mfa";
            file_put_contents($file, $helper);

        }
        else
        {
            $parts = preg_split('/[\n\r]+/', $textbox_content); #if multiple sequences without fasta
            $max = sizeof($parts);
            $runner = 1;
            for($i = 0; $i < $max; $i++)
            {
                $santas = ">Organism." . (string)$runner . "Indentifier."+(string)$runner . "/ 0-0 ";
                $helper = $santas . $textbox_content;
                $file = "../files/file" . (string)$runner . ".mfa";
                $content = serialize($parts[$i]);
                file_put_contents($file, $content);
                $runner++;
            }
        }
        break;

    case ($appearance == 1): #if just one sequence with fasta format

        $file = "../files/newjob.mfa";
        file_put_contents($file, $textbox_content);
        break;

    case ($appearance >= 2): #if several sequences with fasta format

        $parts = explode("\n" , $textbox_content); #if multiple sequences without fasta format
        $max = sizeof($parts);
        $runner = 1;
        for($i = 0; $i < $max; $i++)
        {
            $file = "../files/fastafile" . (string)$runner . ".mfa";
            file_put_contents($file, $parts[$i]);
            $runner++;
        }

        break;
}

}
?>
It just creates one file, with the little extra in front and then the whole textbox content instead of several files.
As you can see, I also tried to figure out what the textbox content looks like and it came out like this:
Array
(
   [textbox_input] => >abc
   >abc
   >abc
   [textbox_text] => Senden
)

A: <?php
$array = explode("\n", $_POST['textbox_input']);

"\n" is the new line representation (only works in double quotes!). The explode function searches for occurences of the delimitter (1st param) in the input string (2nd param) and splits on those delimmiters into an array.
That should server your needs.


text:
Q: How to debug "pthread_cond_wait: Resource busy"? I wrote a script that performs API calls using the python mulithreading library. It speeds up the processing by huge margins because the bottleneck is the network, not anything on my host (enter someone stating python doesn't do true multithreading here).
The issue is that sometimes when I run the script I receive this error, with my script eventually hanging/sleeping:
pthread_cond_wait: Resource busy

I have no idea how to figure out why this is happening. How do I get more context to debug the issue? Do I need to put print statements in a bunch of random places and hope to catch whatever issue is causing this? Is there a better way to debug?
If it helps, this is how I implemented the multithreading:
for i in range(threads): # make the threads
        t = threading.Thread(target=queue_worker, args=[apikey, q, retries, hit_threshold]) # The threads will use the "queue_worker" function with these parameters
        t.daemon = True
        t.start() # start the thread!
# Data is put onto the queue and queue_worker does the API work here...
...
q.join() # Clean up and close the threads when the threads are all idle (no more data on the queue)

EDIT:
queue_worker, api and main code is basically this:
def queue_worker(apikey, q, retries, hit_threshold)
   api_data = q.get()
   for x in range(retries)
      try:
         response = do_api(api_data, apikey)
      except Exception as error:
         time.sleep(5)
         continue
   else:
      error_count = error_count + 1
      q.task_done()
      continue
   #... data parsing code here...
   #... printing parsed data to screen here if a particular value returned is greater than "hit_threshold"...
   q.task_done()

def do_api(api_data, apikey)
   params = { 'apikey': apikey, 'resource': api_data }
   response = requests.get('https://MYURL.com/api', params=params, timeout=10)
   return response

if __name__ == '__main__':
   threads = 50
   q = Queue.Queue(threads)
   for i in range(threads): # make the threads
      t = threading.Thread(target=queue_worker, args=[apikey, q, retries, hit_threshold]) # The threads will use the "queue_worker" function with these parameters
      t.daemon = True
      t.start() # start the thread!
   # Data is put onto the queue and queue_worker does the API work here...
   ...
   q.join() # Clean up and close the threads when the threads are all idle (no more data on the queue)

A:
Comment: Any tips on debugging?

*

*Doublecheck your code using own Locks, Condition or other threading Functions for nested usage.

*Use own Locks for accessing shared Variables.

*
Read Python Threads and the Global Interpreter Lock
  and try this "work around".
  There are other ways to accelerate the GIL manipulation or avoid it:

*

*call ''time.sleep()'' - set ''sys.setcheckinterval()'' - run Python in optimized mode - dump process-intensive tasks into C-extensions - use the subprocess module to execute commands

Likely, you are facing Python GIL!
what-is-a-global-interpreter-lock-gil
One of the other threads has the lock.
There is inconsistent use of locking.


text:
Q: Creating an SQL query from a dictionary I have a function to update an entry in a database (MySQL) and it needs to be as dynamic as possible.
The function allows the user of the API to pass an id of a record and then kwargs to handle the values to change (there is no limit on how many values can be passed).
So lets say I get this dictionary from kwargs
{'hello':'world', 'foo':'bar'}

Is there a way I can use this in an update statement.
UPDATE myTable
SET key_n = val_n, key_n+1 = val_n+1, ...
WHERE id = the_id_passed_to_the_function

Thanks in advance.

A: Try this:
def UpdateQuery(data,where):
    if isinstance(data, dict) and where:
        vals = ','.join(["%s=?" %(k) for k,v in data.iteritems()])
        query = "update myTable set %s where id=?" % (vals)
        res = cr.execute(query,where)

A: How about:
foo = kwargs['bar']
id = 1
if foo:
    k = foo.keys()
    q = '''UPDATE myTable'''
    q += ','.join('SET {0}=%s'.format(i) for i in k)
    q += 'WHERE id = %s'
    cur.execute(q,tuple(foo[i] for i in k)+(id,))

Some points to note:

*

*Since dictionaries are unordered, we are fetching a list of the keys first.

*Instead of putting the values directly in the query; you should pass them in. Again, we step through the same list of keys so that the values match the column names.

*Finally, we add the id to the set of ordered arguments to the query.


text:
Q: Scala case class prohibits call-by-name parameters? Scenario:
I want to implement an infinite list:
abstract class MyList[+T]
case object MyNil extends MyList[Nothing]
case class MyNode[T](h:T,t: => MyList[T]) extends MyList[T]

//error: `val' parameters may not be call-by-name

Problem:
The error is that call-by-name is not allowed.
I've heard that it is because val or var constructor parameter is not allowed for call-by-name. For example:
class A(val x: =>Int)
//error: `val' parameters may not be call-by-name

But in contrast the normal constructor parameter is still val, despite private.  For example:
class A(x: =>Int)
// pass

So the Question :

*

*Is the problem really about val or var ?

*

*If that, since the point for call-by-name is to defer computation. Why could not val or var computation(or initialization) be deferred?

*How to get around the case class limitation to implement an infinite list?

A: I have also not found why exactly by-name parameters are prohibited in case classes. I guess explanation should be quite elaborate and complex.
But Runar Bjarnason in his book "Functional Programming in Scala" provides a good approach to handle this obstacle. He uses the concept of a "thunk" together with memoizing.
Here is an example of Stream implementation:
sealed trait Stream[+A]
case object Empty extends Stream[Nothing]
case class Cons[+A](h: () => A, t: () => Stream[A]) extends Stream[A]
object Stream {
 def cons[A](hd: => A, tl: => Stream[A]): Stream[A] = {
  lazy val head = hd
  lazy val tail = tl
  Cons(() => head, () => tail)
 }
 def empty[A]: Stream[A] = Empty
 def apply[A](as: A*): Stream[A] =
  if (as.isEmpty) empty else cons(as.head, apply(as.tail: _*))
 }
}

As you see, instead of a regular by-name parameter for the case class data constructor they use what they call a "thunk", a function of zero-arguments () => T. Then to make this transparent for the user they declare a smart constructor in the companion object which allows you to provide a by-name parameters and make them memoized.

A: There is no contradiction: class A(x: => Int) is equivalent to class A(private[this] val x: => Int) and not class A(private val x: => Int). private[this] marks a value instance-private, while a private-modifier without further specification allows accessing the value from any instance of that class.
Unfortunately, defining a case class A(private[this] val x: => Int) is not allowed either. I assume it is because case-classes need access to the constructor values of other instances, because they implement the equals method.
Nevertheless, you could implement the features that a case class would provide manually:
abstract class MyList[+T]

class MyNode[T](val h: T, t: => MyList[T]) extends MyList[T]{

  def getT = t // we need to be able to access t

  /* EDIT: Actually, this will also lead to an infinite recursion
  override def equals(other: Any): Boolean = other match{
    case MyNode(i, y) if (getT == y) && (h == i) => true
    case _ => false
  }*/

  override def hashCode = h.hashCode

  override def toString = "MyNode[" + h + "]"

}

object MyNode {
  def apply[T](h: T, t: => MyList[T]) = new MyNode(h, t)
  def unapply[T](n: MyNode[T]) = Some(n.h -> n.getT)
}

To check this code, you could try:
def main(args: Array[String]): Unit = {
  lazy val first: MyNode[String] = MyNode("hello", second)
  lazy val second: MyNode[String] = MyNode("world", first)
  println(first)
  println(second)
  first match {
    case MyNode("hello", s) => println("the second node is " + s)
    case _ => println("false")
  }
}

Unfortunately, I do not know for sure why call-by-name val and var members are prohibited. However, there is at least one danger to it: Think about how case-classes implement toString; The toString-method of every constructor value is called. This could (and in this example would) lead to the values calling themselves infinitely. You can check this by adding t.toString to MyNode's toString-method.
Edit: After reading Chris Martin's comment: The implementation of equals will also pose a problem that is probably more severe than the implementation of toString (which is mostly used for debugging) and hashCode (which will only lead to higher collision rates if you can't take the parameter into account). You have to think carefully about how you would implement equals to be meaningfull.

A: This is actually similar approach to the Stream solution but simplified to what is actually required:
case class A(x: () => Int) {
  lazy val xx = x()
}

So you can use your case class as:
def heavyOperation: Int = ???
val myA = A(heavyOperation)
val myOtherA = A(() => 10)
val useA = myA.xx + myOtherA.xx

Like this the actual heavy operation will be performed only when you use xx, i.e., only on the last line.

A: I like using an implicit function to make a thunk work like a call by name.
e.g. in this example:
case class Timed[R](protected val block: () => R) {
    override def toString() = s"Elapsed time: $elapsedTime"

    val t0 = System.nanoTime()
    val result = block() // execute thunk
    val t1 = System.nanoTime()
    val elapsedTime = t1 - t0
  }

  implicit def blockToThunk[R](bl: => R) = () => bl //helps to call Timed without the thunk syntax

this let's you call Timed({Thread.sleep(1000); println("hello")}) for example with call by name syntax


text:
Q: jquery time picker, criar função para "min time" Tenho dois input com jQuery que carrega um intervalo de horários de 30 em 30 minutos.
O primeiro é o horário de entrada, o segundo é o de saída.
$(function() {
  $('.timepicker').timepicker({
    interval: 30,
    minTime: '7',
    maxTime: '18',
    dynamic: false,
    dropdown: true,
    scrollbar: true
    });
  });

Queria saber como cria uma função dentro do código do jQuery ("minTime:") para que seja impossível colocar horário de saída antes do horário de entrada.
Site feito em PHP.

A: Pela documentação você pode usar o método change pra modificar outro input quando o atual for modificado, usando a notação de option. Veja um exemplo:

$(function() {

  $('.timepicker-saida').timepicker({
    interval: 30,
    minTime: '7',
    maxTime: '18',
    dynamic: false,
    dropdown: true,
    scrollbar: true
  });

  $('.timepicker-entrada').timepicker({
    interval: 30,
    minTime: '7',
    maxTime: '18',
    dynamic: false,
    dropdown: true,
    scrollbar: true,
    change: function(time) {
      var element = $(this), text;
      var timepicker = element.timepicker();

      $('.timepicker-saida').timepicker(
      'option',
      'minTime',
      timepicker.format(time)
      );

    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/timepicker/1.3.5/jquery.timepicker.min.js"></script>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/timepicker/1.3.5/jquery.timepicker.min.css">

<input type="text" class="timepicker-entrada" />
<input type="text" class="timepicker-saida" />

A: Eu faria da seguinte forma. A partir do código que você já tem, e com a suposição de que os inputs têm por id entrada e saida:
var entrada = $("#entrada"), saida = $("#saida");
var validarIntervalo = function () {
    if (entrada.timepicker("getTime") < saida.timepicker("getTime")) {
        // A hora de entrada está menor que a hora de saída.
        // Você pode disparar um erro ou realizar outra ação aqui
    }
}

$(function() {
    $('.timepicker').timepicker({
        interval: 30,
        minTime: '7',
        maxTime: '18',
        dynamic: false,
        dropdown: true,
        scrollbar: true
    }).on("change", validarIntervalo); // Associa a função criada acima ao evento change.
});


text:
Q: send get parameters using action attribute of form and even send the form elements I want to sent parameters using action and even the value of input name=edit parameters but only
ajaxify/modify.php?edit=something
is sent instead of
ajaxify/modify.php?f=update&id=5&edit=something

Is there any solution for this or I am doing some blunder. Please help me.
<form id="update" action="ajaxify/modify.php?f=update&id=5">
    <input type="text" name="edit" value="something"/>
    <input type="submit" value="update"/>
</form>

A: Use hidden input. This will work for get/post methods. Example:
<form id="update" action="ajaxify/modify.php">
     <input type="hidden" name="id" value="5"/>
    <input type="hidden" name="f" value="update"/>
    <input type="text" name="edit" value="something"/>
    <input type="submit" value="update"/>
</form>

A: Set the method attribute of the form element to get to make it do a get instead of a post.
<form id="update" action="ajaxify/modify.php?f=update&id=5" method="get">


text:
Q: Changing multiple states on button's click In my react app i have a list of cars returned from an axios call, each car has an attribute inside it called refundable and it's boolean either true or false, and i have a button and a disabled input, i want when i click on this button if the refundable is true to enable the input and if it's false to hide the input and show a sentence that this car is not refundable, the code i made checks if refundable is true or not and it enables the input, but if it was false it shows the false sentence for all of the cars in the list, here is what I'm doing:
Initial state:
state={cars: [],isInputDisabled: [], isVisible: true }

Function on button's click:
changeDisableState = (id, i) => {
    const car = this.state.cars.find(x => x.id === id);
    let isInputDisabled = this.state.isInputDisabled;
    isInputDisabled[i] = !isInputDisabled[i];
    if (car.refundable == true) {
      this.setState({ isInputDisabled });
    } else {
      this.setState({ isVisible: false });
    }
  };

Rendering cars:
renderCars() {
  const cars = this.state.cars;
  return cars.map((car, i) => (

    <Button onClick={() => this.changeDisableState(car.id, i)}>Check</Button>
   {this.state.isVisible ?
    <input
    disabled={!this.state.isInputDisabled[i]}/> :
Can't be refundable
}

  ));
}

A: It seems like you're missing something in your code:
changeDisableState = (id, i) => {
    const car = this.state.cars.find(x => x.id === id);
    let isInputDisabled = this.state.isInputDisabled;
    if (car.refundable == true) {
      this.setState({ isInputDisabled[i] : !isInputDisabled[i] });
    } else {
      this.setState({ isVisible: false });
    }
  };

also
this line
 disabled={!this.state.isInputDisabled[i]}/>

is not clear. It reads as "make my input disabled if my state value for isInputDisable is false" - shouldn't it be inveresed?

A: You should have isVisible state for each car object.
{car.isVisible ? <input ... /> :
Can't be refundable
}

A: You need to create another state variable for recently clicked id. And then only render sentence for active id
changeDisableState = (id, i) => {
    const car = this.state.cars.find(x => x.id === id);
    let isInputDisabled = this.state.isInputDisabled;
    isInputDisabled[i] = !isInputDisabled[i];
    if (car.refundable == true) {
      this.setState({ isInputDisabled,activeid:id });
    } else {
      this.setState({ isVisible: false, activeid:id });
    }
  };

renderCars() {
  const cars = this.state.cars;
  return cars.map((car, i) => (

    <Button onClick={() => this.changeDisableState(car.id, i)}>Check</Button>
   {this.state.isVisible ?
    <input
    disabled={!this.state.isInputDisabled[i]}/> : this.state.activeid === car.id &&
Can't be refundable
}

  ));
}


text:
Q: When call volume is high in asterisk, its get killed without any error message I am using Asterisk 1.6.2.24 for call handling. I am using 6 port ( 180 channels) to handle the calls. When call volume is around 140 to 150 my asterisk gets killed without any error message even when we enabled the full log in asterisk logger.conf file. 16GB RAM is available in the asterisk running machine. In out of 16GB, 5GB free space also available when asterisk gets killed.
Please let us know what could be the reason?

A: Simple solution: upgrade your asterisk to latest stable.
More complex - find what exactly result core dump
http://www.voip-info.org/wiki/view/Asterisk+debugging

A: this could be an issue with asterisk itself and you can check in the below link for fix...
https://issues.asterisk.org/jira/browse/ASTERISK-16892