text:
Q: Pandas update column conditionally if another column exists I have a dataframe with a column whose value depends on the existence of another column, so I tried to use np.where to condition the value like this:
the_dataframe["dependant_value"] = np.where(
    "independant_value_" + the_dataframe["suffix"].str.lower()
    in the_dataframe.columns,
    the_dataframe["another_column"]
    * the_dataframe[
        "independent_value_" + the_dataframe["suffix"].str.lower()
    ],
    0,
)

But I'm getting this error:
 File "C:\the_file.py", line 271, in the_method
    "independent_value_" + the_dataframe["suffix"].str.lower()
  File "C:\the_file.py", line 4572, in __contains__
    hash(key)
TypeError: unhashable type: 'Series'

I suppose there must be a propper way to make the logic evaluation of the condition, but I haven't found it.

A: There is no syntax like Series in Series/Index
$ s = pd.Series([1, 2])
$ s in s

Traceback (most recent call last):
  File "~/sourcecode/test/so/73460893.py", line 44, in <module>
    s in s
  File "~/.local/lib/python3.10/site-packages/pandas/core/generic.py", line 1994, in __contains__
    return key in self._info_axis
  File "~/.local/lib/python3.10/site-packages/pandas/core/indexes/range.py", line 365, in __contains__
    hash(key)
TypeError: unhashable type: 'Series'

You might want Series.isin
    ("independant_value_" + the_dataframe["suffix"].str.lower()).isin(the_dataframe.columns),


text:
Q: How to autostart `ypbind` on Ubuntu 14.04 It seems I need to use sysv-rc-conf to manage service startup/shutdown, but no scripts were added to /etc/init.d/ when I installed NIS. I would expect to either have /etc/init.d/nis or /etc/init.d/ypbind.
I installed NIS via apt-get as so:
sudo apt-get install nis

How do I configure ypbind to start automatically when Ubuntu 14.04 boots?

A: Looking at the /var/log/upstart/ypbind.log file, I saw ypbind was failing to bind to the server at boot and just quitting. There was actually no problem with auto-starting ypbind.
I determined this was due to DNS not being available at early boot, so I added a couple entries to my /etc/hosts file for the two NIS servers and voila!
Cheers!
--ap

redpajama_set_name: RedPajamaStackExchange


text:
Q: Store past results of a function I have a function that takes in two arrays, does some calculation, and then returns a new array. The function is called maybe 60,000 times (or 500k, depending), where up to 25% of the times it is called, it is redoing a previous calculation.
prev_calc = {}
def arrayMagic(ar1,ar2):
    ar1_t = tuple(ar1)
    ar2_t = tuple(ar2)

    if (ar1_t,ar2_t) in prev_calc:
        return prev_calc[(ar1_t,ar2_t)]
    #some somewhat, but not too expensive function
    res = magicCalc(ar1,ar2)

    prev_calc[(ar1_t,ar2_t)] = res

    return res

ar1 and ar2 are arrays of 3 floats each; for example: [1.1,1.2,2.2]
res is also an array of 3 floats.
The problem is that the tuple conversion and dictionary lookup happen to be very close to the time the magicCalc() function takes. Since this is the major bottleneck in my code, optimizing this would solve alot. The function is passed the two arrays, so I can't have them as an array already.
Is there a fast way to store past results of a function and return them?

A: This seems pretty quick...
d = dict()
l1 = [1.1,21.1,31.1,41.1,51.1]
l2 = [12.1,21.1,31.1,41.1,51.1]

def do(a1):
    cacheKey = str(a1)
    if cacheKey in d:
        print("Read from cache")
        return d[cacheKey]
    else:
        print("calc and cache result")
        d[cacheKey] = sum(a1)
        return d[cacheKey]

print(do(l1))
print(do(l2))
print(do(l1))


text:
Q: How can I automate and run post installation commands in Azure Virtual Machines? I need to deploy Azure hosts and configure them according to a pre-defined script once they are loaded.
Is there any example, guidance,or tutorial on how to modify an Azure VM once the instance is deployed... programmatically (via powershell, c# or any other means)?
So far, I've gone through the command-line deployment commands, and don't see a way that I could upload or otherwise launch a post deployment installation command.

A: I'm not entirely sure where you've gotten stuck or what specifically you're trying to accomplish, but I'll give it a shot anyway...
Remote Desktop
Just for kicks, let's start with remoting in to the VM. I've spun up a VM using the Azure portal. The portal asks for a username and password to be specified. Obviously, the simplest way to remote in would be using the 'Connect' button after selecting an instance of your VM:

From there you could input your credentials, log in to the VM, and open up PowerShell.
That's a bad way of taking care of it, but it is the most straightforward.
PowerShell Remoting
Starting a remote PowerShell session could be a little quicker and involve less GUI. For a quick one-liner, try this:
Enter-PSSession -ConnectionUri (Get-AzureWinRMUri) -SessionOption (New-PSSessionOption -SkipCACheck) -Credential (Get-Credential)

You'll be prompted for the service name (in my case, rtannerf) and credentials. I opted to ignore the self-signed certificate rather than importing it.
You can also use Invoke-Command:
 Invoke-Command –ConnectionUri $uri –Credential $cred –ScriptBlock { "do u liek mah hat!?" | Out-File C:\hello.txt }

More on this here. You could expand upon this and use PowerShell to both deploy your VMs and run scripts against them once deployment is finished. Might want to take a look at the Azure Management cmdlet reference page.
This approach seems a little clunky to me, but if you need to kick off just a few VMs it might work out fine for you.
Deploying via Images
If you need a heavier touch than is appropriate for Invoke-Command, you may want to look in to deploying images. Short version is you'll prepare an image the way you would just about any other Windows image, upload it to a storage account in Azure, and use the management console to add the VHD to your images. There's a short guide here.
It sounds to me like this will be the way you want to approach your problem. You could use startup scripts and whatnot to get the machine in to the state you want, but it's probably better to cut to the chase and simply deploy an image that's configured exactly how you need it.

A: When deploying a VM, you can specify custom data: Up to 64K of data that's injected into the VM during provisioning (API details here). You specify data in a base-64 encoded format in the <CustomData> element. This data will then appear in your VM, in:

*

*%SYSTEMDRIVE%\AzureData\CustomData.bin (Windows)

*/var/lib/waagent/CustomData (Linux)

This is currently only available via the REST API directly, but will soon also be available via the cross-platform CLI. You can see the pull request for this feature here.

A: Alternative way, use IaaS Management Studio, it generates the command line so you can connect via powershell in one click. (and generate the command lines for it)
Commercial, but maybe the free trial is enough for you.


text:
Q: C# - Json converter Example I have following code (C# - Console App)
static async Task MainAsync(string[] args)
{
    Account account = new Account { Name = "Test", Code = (AccountCode)"Code" };
    Console.WriteLine(JsonConvert.SerializeObject(account));
}

public class Account
{
    public string Name { get; set; }

    public AccountCode Code { get; set; }
}

public struct AccountCode
{
    public AccountCode(string value)
        : this()
    {
        if (string.IsNullOrEmpty(value))
        {
            throw new ArgumentException("AccountCode cannot be null or empty.");
        }

        Value = value.ToUpperInvariant();
    }

    public string Value { get; set; }

    public static explicit operator AccountCode(string value)
    {
        return new AccountCode(value);
    }

    public static explicit operator AccountCode? (string value)
    {
        if (string.IsNullOrEmpty(value))
        {
            return null;
        }
        else
        {
            return new AccountCode(value);
        }
    }

    public static explicit operator string(AccountCode code)
    {
        return code.Value;
    }

    public override bool Equals(object obj)
    {
        return obj is AccountCode && this == (AccountCode)obj;
    }

    public override int GetHashCode()
    {
        return Value.GetHashCode();
    }

    public static bool operator ==(AccountCode x, AccountCode y)
    {
        return string.Equals(x.Value, y.Value, StringComparison.InvariantCultureIgnoreCase);
    }

    public static bool operator !=(AccountCode x, AccountCode y)
    {
        return !string.Equals(x.Value, y.Value, StringComparison.InvariantCultureIgnoreCase);
    }

    public override string ToString()
    {
        return Value;
    }

The output is:
{"Name": "Test", "Code": { "Value": "CODE" }
My expectation is:
{"Name": "Test", "Code": "CODE" }
Note: AccountCode is a struct but I would like to serialize/deserialize as a normal string. How should I do?

A: Code in Account class is an object of AccountCode that's why while serializing it, JsonConverter is putting it into curly braces. You have to either change the Code property into string or manipulate the serialized json


text:
Q: Caches to be used in Magento Using OpCache and Magento Default Cache is enough to reduce resource utilisation for repeated requests on the same content?
Do I need to add any other type of Cache? If yes what?

A: It's actually possible to have a <0.5s TTFB with all Magento caches OFF.
Caches don't make sites faster, they reduce resource utilisation for repeated requests on the same content, don't confuse the two.

I have a powerful server so I don't think its a problem with that

Define powerful.
Having lots of RAM or lots of cores won't improve performance. The revision of the CPU, it's clock speed, the L2 cache size, bus speed, memory controller, motherboard chipset, RAM latency and bus speed all have a MASSIVE impact on performance.

All the settings for Mysql and Php and Apache are done

All the settings are done? There are no one size fits all configuration settings, if you have merely copied and pasted configuration files from the internet, then it's extremely likely your server is completely misconfigured.

I don't mean to be harsh but there seems to be a common misconception that developers are qualified to be system administrator's. Being able to use a package manager to install applications, or even compiling from source doesn't make you any more of a system administrator than a store owner is a developer,  because they can drop modules in via Magento connect.
Configuring a server properly comes from testing the server specifically for your needs, refining the configuration and repeating tests. Most importantly having a full and detailed understanding of exactly what the effects of what you are changing are. So that you have a fast, reliable, predictable server that you can diagnose and rectify when things go wrong.
It sounds like you would benefit from being with a proper Magento host that specialises in high performance environments, that way you can focus your attention on your store, not learning how to manage a server.


text:
Q: AnimationFactory FlipTransition - Animation listener? I'm making use of this project (https://code.google.com/p/android-3d-flip-view-transition/) to do card flipping in my Android app.
Below is the code that I use to flip the card,
AnimationFactory.flipTransition((ViewAnimator) v,FlipDirection.LEFT_RIGHT);

How do I know if the animation is completed or not? I tried the below code to attach a listener for animation complete, but it throws a NullPointerException.
((ViewAnimator) v).getAnimation().setAnimationListener(new AnimationListener() {

 @Override
 public void onAnimationStart(Animation animation) {
    // TODO Auto-generated method stub
 }

 @Override
 public void onAnimationRepeat(Animation animation) {}

 @Override
 public void onAnimationEnd(Animation animation) {//do something}

});

Any pointers?

A: you need create interface, and override method:
public static Animation[] flipAnimation

and set listener to inFlip or outFlip — then it will work.
Or you may define runnable when you flip view, with postDelayed — 500 ms (this time set on this project, animation time). — This option is not very nice, and not recommended.
EDIT:
Interface:
public interface FlipCompleteListener {

    public void flipOutComplete();

    public void flipInComplete();

}

On class AnimationFactory:
   private static FlipCompleteListener flipCompleteListener;

   public static void setFlipCompleteListener(FlipCompleteListener flipCompleteListener) {
        AnimationFactory.flipCompleteListener = flipCompleteListener;
    }

On method flipAnimation:
outFlip.setAnimationListener(new AnimationListener() {
        @Override
        public void onAnimationStart(Animation animation) {
        }

        @Override
        public void onAnimationEnd(Animation animation) {
             if(flipCompleteListener != null) {

             flipCompleteListener.flipOutComplete();

            }
        }

        @Override
        public void onAnimationRepeat(Animation animation) {
        }
    });

On your class, like on create:
... extends Activity implements FlipCompleteListener

 @Override
    public void onCreate(Bundle savedInstanceState) {
        AnimationFactory.setFlipCompleteListener(this);
    ...

And finally you got needed methods:
    @Override
    public void flipOutComplete() {
    }

    @Override
    public void flipInComplete() {
    }

This should work, but use static listeners — bad, need refactoring static method to object method. Project under MIT license, that allows you to do.


text:
Q: Understanding a proof in convergence in probability Theorem 8
I'm trying to understand this. In the last line, I understand that $P({\frac{1}{X_n} \geq 1 + \epsilon}$) goes to 0 when n goes to infinity. Since
$P({\frac{1}{X_n} \geq 1 + \epsilon}$) = $P({X_n} \leq \frac{1}{1 + \epsilon}$) = $P({X_n-1} \leq \frac{-\epsilon}{1 + \epsilon}$) , which goes to 0 since we are given $P(|X_n -1 | \geq \epsilon_0) \rightarrow 0$ for some $\epsilon_0 >0 $
But I don't understand $P({\frac{1}{X_n} \leq 0}$) and $P( 0 < \frac{1}{X_n} \leq 1 - \epsilon$) goes to zero. Need some help in this


text:
Q: Need help recreating a SOAP request in groovy-wslite I had issues getting the most basic of actions working, but finally figured it out.  You can see what I did here
With that working I'm moving onto the subsequent action and once again running into issues. Here is what the XML SOAP Request looks like which works (generated in PHP)
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="urn:ws.company.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ns2="ws.company.com">
    <SOAP-ENV:Header>
        <ns2:SessionHeader>
            <ns2:sessionId>theLoginSessionID</ns2:sessionId>
        </ns2:SessionHeader>
    </SOAP-ENV:Header>
    <SOAP-ENV:Body>
        <ns1:triggerCampaignMessage>
            <ns1:campaign>
                <ns1:folderName>theFolder</ns1:folderName>
                <ns1:objectName>theObject</ns1:objectName>
            </ns1:campaign>
            <ns1:recipientData>
                <ns1:recipient>
                    <ns1:listName>
                        <ns1:folderName>theFolder</ns1:folderName>
                        <ns1:objectName>theObject</ns1:objectName>
                    </ns1:listName>
                    <ns1:emailAddress>person@company.com</ns1:emailAddress>
                </ns1:recipient>
                <ns1:optionalData>
                    <ns1:name>order_number</ns1:name>
                    <ns1:value>231</ns1:value>
                </ns1:optionalData>
            </ns1:recipientData>
        </ns1:triggerCampaignMessage>
    </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

The code I am trying to use is this
@Grab(group='com.github.groovy-wslite', module='groovy-wslite', version='0.8.0')
import wslite.soap.*

def client = new SOAPClient('https://company/services/WebService')
def response = client.send(SOAPAction:'https://company/services/WebService/') {
    body {
        login('xmlns':'urn:ws.company.com') {[
            username("username"),
            password("password")
            ]}
    }
}
theSession = response.envelope
try {
    response = client.send(SOAPAction:'https://company/services/WebService/') {
        header {
            SessionHeader('xmlns':'urn:ws.company.com') {
                sessionId(theSession)
            }
        }
        body {
            triggerCampaignMessage('xmlns':'urn:ws.company.com') {[
                campaign {[
                    folderName("theFolder"),
                    objectName("theObject")
                ]},
                recipientData {[
                    recipient {[
                        listName {[
                            folderName("theFolder"),
                            objectName("theObject")
                        ]},
                        emailAddress("person@company.com")
                    ]},
                    optionalData {[
                        name("order_number"),
                        value("1234567890")
                    ]}
                ]}
            ]}
        }
    }
} catch (SOAPFaultException sfe) {
    println "fault string :" + sfe.message // faultcode/faultstring for 1.1 or Code/Reason for 1.2
    println "envelope :" + sfe.text    // prints SOAP Envelope
    println "status code :" + sfe.httpResponse.statusCode
    println sfe.fault.detail.text()
}

I'm pretty sure that the first send to the login is working since it's the code that works all on it's own and the error message I am receiving is
Unexpected subelement {urn:ws.company.com}emailAddress

So I'm guessing I'm okay up to that point, but can't figure it out.  Based on the XML that works can anyone help me get my groovy code to work?
EDIT
Here's the response envelope from the login call
<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
    <soapenv:Body>
        <loginResponse xmlns="urn:ws.company.com">
            <result>
                <sessionId>string here</sessionId>
            </result>
        </loginResponse>
    </soapenv:Body>
</soapenv:Envelope>

A: The problem may be with theSession = response.envelope which will set theSession to the entire SOAP response from the first call to login.  My guess is that you really need to grab a token value from an element within the login response message, for example:
theSession = response.loginResponse.result.sessionId.text()
If you can provide a sample of the result from the call to login I can try to provide a more exact answer.


text:
Q: javascript indexOf strange behavior I found a strange unexplainable behavior while writing a piece of test code for my javascript program.  I was comparing an output of res.body to check if it contains a string.
More precisely, I was checking if res.body contained a string 'channel'.
Even though the output did really contain that string, the test case was always failing.  I ran the program in debug mode, to examine why it is failing.  The results are puzzling, to say the least.
> res.body
'Error: invalid channnel'
> res.body.indexOf('channel')
-1
> res.body.indexOf('channe')
-1
> res.body.indexOf('chann')
15
>

if I try to check indexOf of 'channel' in res.body whose value was 'Error: invalid channel', I was supposed to get a positive value, but it gives -1.
so, I tried by reducing the no. of chars in the match, it still fails until I reduce the search string to contain just 'chann' i.e by omitting 'el'.
But this behavior doesn't happen, if I take a string litteral and do the same exercise.  For example, the below works perfectly.
> 'Error: invalid channel'.indexOf('channel')
15

I went ahead and checked the typeof res.body, and it shows as string, and not any object.
> typeof res.body
'string'
>

Did anyone face a similar problem ever? Or is there an explanation to this?
EDIT
It happens when I res.body as produced by mocha + chai framework.  The full code is below:
 58   it ("Should fail with 400, if invalid channel", function(done) {
 59     chai.request(app).post('/campaigns/js')
 60     .send(samples.type0.invalidChannel)
 61     .end(function(err, res) {
 62       console.log("response:", res.body);
 63       expect(res).to.have.status(400);
>64       debugger;
 65       expect(res.body).to.contain('channel');
 66       return done();
 67     });
 68   });

A: You're res.body has channel with 3 ns.

'Error: invalid channnel'

This means that chann matches, but channe won't because of the extra n.

A: In the first piece of code, "channnel"  has 3 n's. That's why it matched "chann"  but not "channe".


text:
Q: Calculate two values systematic from the same column in a precedure (mysql) I have 2 columns that I want to multiply "speed" and "distance" points for each set thay appeare
The table:
--- type --- | --- points ---
....speed....|.......25........
....junk.......|.........1........
..distance..|......120........
....speed....|.......19........
....junk.......|.........1........
..distance..|......102........
....speed....|.......15........
....junk.......|.........1........
..distance..|.......99........
...
speed(25) * distance(120) save value
speed(19) * distance(102) save value
speed(15) * distance(99) save value
And in the end get the SUM(value)
I want to do something like this:(I know its so wrong but anyway you know what I mean...)
SET value = (SELECT SUM(t.v)
             FROM(
                 ((SELECT (points) s FROM UserData WHERE type = 'speed')
                 *
                 (SELECT (points) d FROM UserData WHERE type = 'distance'))
                 v
             ) t);

A: As you said, "its so wrong", but assuming the data is reliably in the order you've shown, this might work ....
SET @i := 0;
SET @part := 0;
SET @running := 0;

SELECT IF(@i=0, @part := `points`, @part := @part * `points`) AS `current_partial`
   , IF(@i=1, @running := @running + @part , @running) AS `incremental_running`
   , @i := IF(@i=1,0,1) AS `stage`
FROM some_ridiculous_table
;

SELECT @running;


text:
Q: Using SQL keywords as names without brackets Which keywords are allowed to be used as names without brackets and which are not  ?
Why some SQL keywords are allowed to be used as names when others are not ?
Is there any pattern in determination of which I can use and which I can't without trying to compile and getting error ?
I have impression that older keywords are not allowed, but newer are allowed so that newer SQL versions are as compatible as possible with older.
In the following example rollup can be used as name without brackets, but group cannot.
if object_id('accident') is not null drop table accident
create table accident(
     state varchar(50)
    ,city varchar(50)
    ,zip varchar(50)
    ,person varchar(50)
    ,id int identity(1,1)
)

insert accident(state,city,zip,person)values
 ('NY','Manhattan',10001,'John')
,('NY','Manhattan',10001,'John')
,('NY','Manhattan',10001,'Barbara')

;with
    rollup as (
            select accident.*
                    ,lvl = grouping_id(accident.state,accident.city,accident.zip,accident.person,accident.id)
                    ,accidents=count(1)
                    ,people=0
                from accident
                group by rollup(accident.state,accident.city,accident.zip,accident.person,accident.id)
        )
        select * from rollup

;with
    [group] as (
            select accident.*
                    ,lvl = grouping_id(accident.state,accident.city,accident.zip,accident.person,accident.id)
                    ,accidents=count(1)
                    ,people=0
                from accident
                group by rollup(accident.state,accident.city,accident.zip,accident.person,accident.id)
        )
        select * from [group]

Attempt to use group as name without brackets
;with
    group as (
            select accident.*
                    ,lvl = grouping_id(accident.state,accident.city,accident.zip,accident.person,accident.id)
                    ,accidents=count(1)
                    ,people=0
                from accident
                group by rollup(accident.state,accident.city,accident.zip,accident.person,accident.id)
        )
        select * from group

gives error:

Msg 156, Level 15, State 1, Line 28
  Incorrect syntax near the keyword 'group'.
  Msg 156, Level 15, State 1, Line 36
  Incorrect syntax near the keyword 'group'.

A: There is a list of reserved keywords and you can find it in here. It's too long to paste it into this answer. All reserved keywords have to be escaped. From your example rollup is not a reserved keyword, whereas group is.
There are more kywords in ISO standards. Plase take a look at the following notes in the same link:

Additionally, the ISO standard defines a list of reserved keywords. Avoid using ISO reserved keywords for object names and identifiers. The ODBC reserved keyword list, shown in the following table, is the same as the ISO reserved keyword list.
The ISO standards reserved keywords list sometimes can be more restrictive than SQL Server and at other times less restrictive. For example, the ISO reserved keywords list contains INT. SQL Server does not have to distinguish this as a reserved keyword.
Transact-SQL reserved keywords can be used as identifiers or names of databases or database objects, such as tables, columns, views, and so on. Use either quoted identifiers or delimited identifiers. Using reserved keywords as the names of variables and stored procedure parameters is not restricted.


text:
Q: How can I replace an existing image on a winforms ImageList? How can I replace an existing image on a winforms ImageList?
I tried this:
this.CoolPics.Images [ 2 ] = // new image
this.ListViewControl.SmallImageList = this.CoolPics;

However the new image is not rescaled the way the others are, when I used the this.CoolPics.Images.Add method.
What am I doing wrong?

A: I know this is old but here is how I solved the problem.  It looks like the image list will not resize the image upon assignment (even though it does when using the Add() function).  So basically, you need to resize the image manually before assigning.
Image img; //used to load new image from disk
Bitmap bmp = new Bitmap(160, 120); //canvas where the new image will be drawn/resized
Graphics graph = Graphics.FromImage(bmp); //used to draw/resize the new image

img = new Bitmap(fileDialog.FileNames[0]); //load new image from disk

graph.DrawImage(img, new Rectangle(0, 0, 160, 120)); //resize new image to proper size

imgList.Images[index] = bmp; //assign the new resized image to the list (overwrites the old image)

A: after your code try
listView1.Refresh();

A: I have run into this before and if I remember right the assignment operator had this behavior but the Imagelist.Images.Add(myImage) did the right thing.
Try changing your code to do the .Add(myImage) and see if that doesn't look better.


text:
Q: use variable under ajax call globally in javascript I created a java script file that get the images from flickr. Now I want that data can be accessed globally.
$.getJSON('js/album.json', function(data) {
    var myArray = data.children;
    $.each(myArray, function(i, item) {
        $.each(item.children, function(j, childItem){
            var childName = childItem.name;
            getFlickrImage(childName, handleData, data);
        });
    });
    new_json = data;
});

I want the new_json variable access globally. I tried a lot, after so much search on google I posted here.

A: Answering your question, remember that any "global variable" is just a member of the window's object (when working on browsers).
So you just must use:
//...
window.new_json = data
//...

In order to access "new_json" anywhere on your code.
But remember, global variables are evil :) So I would put it inside another object at least.
As a personal advice, I think you should take a look to Jquery's Promises first, because you can't ensure elsewhere on your code that new_json is properly fulfilled. Or also think other design patterns (module pattern, maybe) in order to make your app cleaner.

A: Some pretty bad answers here so far.
In the asynchronous world of AJAX, you need to do things with callbacks. With AJAX, you never know when (or even if) the data that you've asked for will become available. It depends on things like the clients internet connectivity, latency, your server's speed, traffic etc.
So you have to do it like this:
function doSomeAjaxCall(myCallback) {

  $.getJSON('js/album.json', function(data) {
      var myArray = data.children;
      $.each(myArray, function(i, item) {
          $.each(item.children, function(j, childItem){
              var childName = childItem.name;
              getFlickrImage(childName, handleData, data);
          });
      });
      new_json = data;

      myCallback.apply(window);

  });

});

doSomeAjaxCall(function() {
  console.log(new_json); //see? it is available globally.
});

A: You can't. You have to make call synchronously.
See this related question for more information.


text:
Q: SURF + BOWImgDescriptorExtractor + BFMatcher giving type error I am using opencv-2.4.13 with python 2.7. I am trying to create training set for my SVM classifier. In using BOWImgDescriptorExtractor I am getting type error. Here is the code..
extract = cv2.DescriptorExtractor_create("SURF")
surf = cv2.SURF(400)
matcher = cv2.BFMatcher(cv2.NORM_L2)

BOW = cv2.BOWKMeansTrainer(100)

for ImageName in FileList:
    img = cv2.imread(ImageName,0)
    kp, des = surf.detectAndCompute(img1,None)
    BOW.add(des)
 dictionary = BOW.cluster()

bow_extract = cv2.BOWImgDescriptorExtractor( extract, matcher )
bow_extract.setVocabulary( dictionary )

ImageName = FileList[0]
img = cv2.imread(ImageName,0)
kp = surf.detect(img1)
inp = bow_extract.compute(img1,kp)

I am getting this error
Traceback (most recent call last):
  File "Pre_process.py", line 48, in <module>
    inp = bow_extract.compute(img1, surf.detect(img1))
cv2.error:/opencv-2.4.13/modules/core/src/stat.cpp:2481: error: (-215) type == src2.type() && src1.cols == src2.cols && (type == CV_32F || type == CV_8U) in function batchDistance


text:
Q: What is the difference between "to cook something" and "to make something"? When do you use "cook" and when do you use "make" while you are talking about preparing food? In other words: Which (type of) food are cooked which (type of) food are made?
According to dictionary :
Cook means: To prepare (food) for eating by applying heat.
Make means: to produce something, often using a particular substance or material.
So I can see that the main element in cooking is using the "heat", but there are some food that can be "made" using "heat" (in the oven or on the stove) and I have problem in using the correct verb while I'm talking about preparing such food.
For example; shall I say

*

*"to cook a cake" or " to make a cake"?

*"to cook a pizza" or "to make a pizza"?

*"to cook omelette" or " to make omelette"?

*"to cook stew" or "to make stew"?

*"to cook steak" or "to make steak"?

Are there any general rules for using these two verbs?

A: To supplement WBT's answer, I would also say that there are dialectal differences. My fiancée is American and I am Irish. I would say "I am going to cook an egg" (or, more likely, something more specific like "boil", "fry" or "scramble") whereas she tends to say "I am going to make eggs", which sounds to me like she is going to squat down on the kitchen floor and lay an egg like a hen (I sometimes make clucking sounds when she says this :). To me "make", as it relates to food, involves some kind of assembly of ingredients, whereas to her it really doesn't.

A: I think the problem with your examples is that "cook" and "make" are both very general-purpose words. Usually it is more idiomatic to use a more specific verb. You don't "cook a potato", you boil, bake, fry, or roast it (and the four different methods of cooking it produce very different results). Similarly you don't "cook a steak", you fry, grill, or braise it.
You can use "cook" or "make" in situations where you would typically be using several different methods to prepare the food, and the details are not significant or interesting. For example you can "cook dinner", "make dinner," or "make a salad".
You could also you the generic verb "prepare", which seems to be appropriate for every possible method of turning a collection of ingredients into "food".

A: "Cook" focuses more narrowly on the act of applying heat and the transformation that the food undergoes because of the heat.  Commenters on the question have properly noted that the more specific "bake" should be used instead of "cook" when the heat is applied in an oven (especially when the transformation is more than just increasing the temperature of the food).
"Make" is more general and covers other aspects of food preparation that do not necessarily involve the application of heat.
For example, you "make" a salad but you don't "cook" a salad, because there's no heat (usually).   You might cook chicken as part of making a salad.
You "bake" a cake by putting it in the oven, and it is implied by context that you took other steps as well (such as mixing the ingredients, greasing the pan, frosting it, etc.) but if you "make" a cake those other steps are more explicitly stated and more emphasized.
In your examples, I would tend to use "make" more often unless "cooking" was about the only step in food preparation (e.g. "cook a steak" for some preparations).  I would also use "cook" or "bake" if the heat component was the focus of my narrative (e.g. "I went to cook the pasta and discovered that my stove didn't work" or "I feel hot and tired because I've been baking bread all day").
One also hears people talking about how "accurately measuring ingredients tends to be more important in baking than in general cooking," because the ratios of one ingredient to another are important for the chemical reactions that take place while baking.
If you use "cook/bake" interchangeably with "make" when referring to food preparation with heat, or if you always use "make" for food preparation, the meaning will be quite clear*, and you don't need to worry about using the wrong one.  The StackExchange Q&A site for chefs is even "cooking.stackexchange.com."  However, if you want to understand the subtle distinction a bit more, I hope the answer above has helped.

(*) with very few exceptions, such as if you're a known sushi lover talking about "making fish for dinner" with an intended meal partner who strongly prefers that the fish be cooked; this is someone who might seek clarification.

A: If 'cook' is making food using 'heat/fire', then 'making' in the reference of making food is when you don't use heat/fire.

She's cooking rice (fire/heat needed)

But...

She's making a vegetable sandwich for me (no fire/heat needed).

So, in your all examples, if heat/fire needed, use 'cook' or else 'make' should go fine, I think!
Note that it is not a strict rule.

She makes delicious dishes
Best oil for making french fries

is okay!
With these examples, I conclude that when 'heat/fire' is used, both the terms 'cook' and 'make' would go unnoticed. But when you don't require heat/fire, 'make' seems to be better choice.
Check -

I'm cooking a sandwich - does not sound right unless it is a grill sandwich or something else for what you require heat.

That's the reason, 'cooking' is not possible when it comes to 'juices/shakes'.

She's cooking making an orange juice.

A: I was just talking to a Japanese teacher of English about this.
You can use "make" generally.
Ex: I'm going to make a sandwich.
I'm going to make curry and rice.
I'm going to make an omelet.
I'm going to make some chicken tonight. However, with this sentence, you'd have to specify how are you going to prepare it;e.g., bake, fry, broil...
I'm going to make steaks tonight. Again, with this sentence, you'd specify how are you going to make the steaks.
Then again. It's a regional thing! Me, being from New York City, I rarely heard anyone say cook a sandwich when talking about making a grilled cheese sandwich. You don't cook grilled cheese sandwiches. You make them over a flame.

A: To cook is an specific act, about preparing food.
There are other scenarios which require the same logic, for example:

*

*to build/to develop software (not TO MAKE SOFTWARE)

TO MAKE is something generic, much more related with attitudes than physical things.
For example:

*

*to make it happen (present)

*I made it (past)

*make some noise! (present) - in this sentence, it is much more related with an attitude, without specifying PHYSICAL interaction


text:
Q: How to work with dates fast in pandas? I have dataframe with 200000 rows. Each record has a timestamp, and I need to group them by date. So I do:
In [67]: df['result_date'][0]
Out[67]: Timestamp('2017-09-01 09:12:00')

In [68]: %timeit df['result_day'] = df['result_date'].apply(lambda x: str(x.date()))
2.26 s ± 73.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [69]: df['result_day'][0]
Out[69]: '2017-09-01'

or
In [70]: %timeit df['result_day'] = df['result_date'].apply(lambda x: x.date())
2.05 s ± 213 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [71]: df['result_day'][0]
Out[71]: datetime.date(2017, 9, 1)

anyway, it takes ~2 seconds. Can I do it faster?
UPD:
In [75]: df.shape
Out[75]: (228217, 18)

In [77]: %timeit df['result_date'].dt.date
1.44 s ± 42.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

A: Using the example from jezrael. You almost never want to actually use .date; this creates python objects. .normalize() sets the time on dates to 00:00:00, effectively making them dates, but keeping them in a high performance format of datetime64[ns].
In [32]: rng = pd.date_range('2000-04-03', periods=200000, freq='2H')
    ...: df = pd.DataFrame({'result_date': rng})
    ...:

In [33]: %timeit df['result_date'].dt.date
482 ms ± 10.8 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [34]: %timeit df['result_date'].dt.normalize()
16.3 ms ± 234 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

Grouping
In [39]: %timeit df.groupby(df['result_date'].dt.date).size()
506 ms ± 11.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [40]: %timeit df.groupby(df['result_date'].dt.normalize()).size()
24.2 ms ± 1.92 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

Or idiomatically
In [38]: %timeit df.resample('D', on='result_date').size()
5.47 ms ± 110 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

A: Use dt.date, which working also with NaT very nice:
df['result_day'] = df['result_date'].dt.date

rng = pd.date_range('2000-04-03', periods=200000, freq='2H')
df = pd.DataFrame({'result_date': rng})

In [216]: %timeit df['result_date'].dt.date
1 loop, best of 3: 474 ms per loop

In [217]: %timeit df['result_date'].apply(lambda x: str(x.date()))
1 loop, best of 3: 740 ms per loop

In [218]: %timeit df['result_date'].apply(lambda x: x.date())
1 loop, best of 3: 559 ms per loop

EDIT:
I think floor is faster as normalize:
#home's notebook, so different times as above

In [3]: %timeit df['result_date'].dt.date
1 loop, best of 3: 854 ms per loop

In [4]: %timeit df['result_date'].dt.normalize()
10 loops, best of 3: 27.8 ms per loop

In [5]: %timeit df['result_date'].dt.floor('D')
100 loops, best of 3: 13.1 ms per loop

In [6]: %timeit df.groupby(df['result_date'].dt.date).size()
1 loop, best of 3: 883 ms per loop

In [7]: %timeit df.groupby(df['result_date'].dt.normalize()).size()
10 loops, best of 3: 40.2 ms per loop

In [8]: %timeit df.groupby(df['result_date'].dt.floor('D')).size()
10 loops, best of 3: 25.9 ms per loop

EDIT1:
numpy alternative is faster, but as pointed Jeff:

it's faster but you lose things like time zones and any higher level methods.

In [9]: %timeit df['result_date'].values.astype('datetime64[D]')
100 loops, best of 3: 2.39 ms per loop


text:
Q: How to find the right files to edit the css code in custom wordpress theme? I have a custom-made WordPress theme-based website. The problem is I'm not being able to change the dimensions/size of the images in my blog section. No matter what size I change, using the WordPress dashboard it stays in the same size. I have attached the image below.
Image preview
I tried using the inspect tool to see what is overriding the inline CSS I apply, I got to know that there is a max-width mentioned in a file that is causing this problem.
But I don't know how to locate this file and remove the code, so the image changes according to the specified size.
I have attached the image of the inspect tool results below
Inspect tool result
I tried searching for the file which the inspect tool mentions but the file it points to is the index (HTML) file of the blog post. But I couldn't find this Html file in my theme contents and moreover, all the files are in PHP in WordPress.
It would be truly helpful if someone can assist me in solving this problem.

A: I believe you can solve your problem by modifying the style.css file that is present in your theme.
You can find it in settings-> theme editor-> style.css
if you write some properties there using your tag class it should read your changes and if it doesn't work use !important next to the css property
I hope I was helpful


text:
Q: Can not find suitable configuration of distributed configuration store when initializing Patroni as sudo I followed the example described here https://www.opsdash.com/blog/postgres-getting-started-patroni.html and everything works as expected.
While testing, I tried sudo patroni  pg-2.yml. The output was:
2022-01-13 11:39:22,316 INFO: Failed to import patroni.dcs.consul
2022-01-13 11:39:22,316 INFO: Failed to import patroni.dcs.etcd
2022-01-13 11:39:22,317 INFO: Failed to import patroni.dcs.etcd3
2022-01-13 11:39:22,318 INFO: Failed to import patroni.dcs.exhibitor
2022-01-13 11:39:22,319 INFO: Failed to import patroni.dcs.raft
2022-01-13 11:39:22,319 INFO: Failed to import patroni.dcs.zookeeper
Traceback (most recent call last):
  File "/usr/local/bin/patroni", line 8, in <module>
    sys.exit(main())
  File "/usr/local/lib/python3.8/dist-packages/patroni/__init__.py", line 182, in main
    return patroni_main()
  File "/usr/local/lib/python3.8/dist-packages/patroni/__init__.py", line 140, in patroni_main
    abstract_main(Patroni, schema)
  File "/usr/local/lib/python3.8/dist-packages/patroni/daemon.py", line 98, in abstract_main
    controller = cls(config)
  File "/usr/local/lib/python3.8/dist-packages/patroni/__init__.py", line 30, in __init__
    self.dcs = get_dcs(self.config)
  File "/usr/local/lib/python3.8/dist-packages/patroni/dcs/__init__.py", line 110, in get_dcs
    raise PatroniFatalException("""Can not find suitable configuration of distributed configuration store
patroni.exceptions.PatroniFatalException: 'Can not find suitable configuration of distributed configuration store\nAvailable implementations: kubernetes'

Is there an explanation for that?


text:
Q: Replace jmx_exporter_config.xml in the Docker image built by Fabric8 maven plugin The default Docker image that is being built using mvn package fabric8:build contains /opt/agent_bond/jmx_exporter_config.xml that doesn't include (filters out) JMX beans that I'm interested in exporting to the Prometheus.
How can I replace that file with my own during the build with Fabric8 maven plugin?
I know I can construct the Docker image from scratch or redefine everything using Fabric8 plugin XML config, but that's too invasive in comparison to the default "Zero-config" approach.
Update:
So one way I found is to add custom jmx_exporter_config.yml file to the src/main/fabric8-includes and then add environment variable via Kubernetes deployment in src/main/fabric8/deployment.yml:
spec:
  template:
    spec:
      containers:
        -env:
          - name: AB_JMX_EXPORTER_CONFIG
            value: /deployments/jmx_exporter_config.yml

Unfortunately, the Docker image in this case would still not expose custom metrics by default.
I also cannot add exposed ports when using Spring Boot generator "zero-configuration" option.
Update 2
So the workaround for the ENV entry works ok and probably is sufficient for my use case.
The 4th port that I was trying to expose was the Spring Boot management port (default 8081). But it seams that it is not needed for the Kubernetes liveness probe checking, since Kubelet can access that port even if it is not exposed from the Docker image of the Spring Boot service.

A: The way you describe is currently the recommended way, but it should be probably easier to add such config files.
For the "zero-config" mode you can set this in the configuration (so not so zero ;-):
<configuration>
   <generator>
     <config>
       <spring-boot>
          <webPort>8080</webPort>
          <!-- dont expose jolokia -->
          <jolokiaPort>-1</jolokiaPort>
          <prometheusPort>9999</prometheusPort>
       </spring-boot>
     </config>
   </generator>
</configuration>

If you need additional ports you would have to provide it in your resource yaml fragment. See also https://maven.fabric8.io/#generator-java-exec for the options you can use here.


text:
Q: Deserializing nodes presenting as different types I am looping over a folder of JSON files, and I am trying to pull out some information from them; however, I am finding it greatly difficult to do so.
I have started to build my objects to deserialize.  I have a particular node I would normally deserialize as an object, but when it's empty, it presents as an empty array. Please see the definition field in the example JSON below:
{
  "name": "Example",
  "description": "Example JSON",
  "properties": {
    "foo": "bar",
    "foo1": "bar2",
    "foo3": "bar4"
  },
  "stages": {
    "This is a stage": {
      "stageInfo1": "blah",
      "stageInfo2": "blah",
      "integration": {
        "x": "x",
        "y": "y",
        "z": "z",
        "definition": []
      }
    },
    "Another Stage": {
      "stageInfo1": "blah",
      "stageInfo2": "blah",
      "integration": {
        "x": "x",
        "y": "y",
        "z": "z",
        "definition": {
          "5a4d7de4c6518": {
            "Editable": true,
            "ID": "5a4d7de4c6518",
            "Name": "My example"
          }
        }
      }
    }
  }
}

As the definition name can change (in this case it is 5a4d7de4c6518), I thought a dictionary would be best, but an error is thrown when an empty array is presented.
 [JsonProperty("definition")]
 public Dictionary<string, Definition> definition;

Error:

An unhandled exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll
Additional information: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'System.Collections.Generic.Dictionary`2[System.String,JsonProcessReader.Models.Stages+IntegrationDefinition]' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.

A: An empty array is incompatible with a dictionary structure, which gives rise to the error you are seeing.  Since it seems you cannot easily change the JSON, you will need to use a JsonConverter to handle this situation.  Here is a generic one that should work for you:
class TolerantObjectConverter<T> : JsonConverter where T: new()
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(T);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JToken token = JToken.Load(reader);
        object result = new T();
        if (token.Type == JTokenType.Object)
        {
            serializer.Populate(token.CreateReader(), result);
        }
        return result;
    }

    public override bool CanWrite
    {
        get { return false; }
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

This converter works by temporarily loading the relevant piece of JSON into a JToken and then checking whether it is actually an object before trying to convert it.  So if it is an array or some other token type that won't convert properly, it will return an empty T instance instead.
To use the converter, simply add a [JsonConverter] attribute to your dictionary property like this:
public class Integration
{
    ...
    [JsonConverter(typeof(TolerantObjectConverter<Dictionary<string, Definition>>))]
    public Dictionary<string, Definition> definition { get; set; }
}

Here is a working demo: https://dotnetfiddle.net/83dQoC


text:
Q: How can I map form values to database column names when I don't know which of the form names will be passed? I have an HTML form.
I have a MySQL table.
The form has name attributes such as "last_name," "first_name," "unique_id," etc.
The MySQL database table has the column name of "last," "first," "something_special_id," etc.
What I have done is create a new array and map it from form to table column names.  I then send back the new array, so I can then update my database.
The problem is I want to make it dynamic.
I have done this:
if (isset($myArray['last_name']))
{
    //Gets the current value of the form array sent in POST
    //and puts that value into the new array which is labeled
    //with the correct table column name;
    //e.g. $myArray['last_name']= "Smith";
    //now $mappedColumnNames['LAST'] is equal to "Smith";

    $mappedColumnNames['LAST'] = $myArray['last_name'];

}

if (isset($myArray['first_name']))
{
    $mappedColumnNames['FIRST'] = $myArray['first_name'];

}
if (isset($myArray['diploma']))
{
    $mappedColumnNames['DIPLOMA'] = $myArray['diploma_value_from_form'];

}
if (isset($myArray['secret_number']))
{
    $mappedColumnNames['SECRET'] = $myArray['secret_number_from_form'];

}
unset($myFormValues);

The $mappedColumnNames array is the database column names.  The $myArray array is the array of POST variables sent by the form.

*

*I do not know what they order will be each time the form is
submitted.

*I do not know which form elements will always be
submitted.

*I do not want to name of form attributes to be the column names of the database.

*I am not sure about changing my query in MySQL to use aliases.  For
example, using LAST as "last_name."

*I really didn't want to change the database schema, as I'd like this
to be "almost" database agnostic.

Is there a better way to do this than what I have done?
Here is my code to update my database:
$mappedColumnNames = parent::mapColumnNames($_student_search);

        //What I use now but it won't work because the form names are not the column names.
        foreach($_student_search as $key => $value)
        {
            //echo '
key: ' . $key . ', value: ' . $value . '
';
            $columns[] = $key . ' = ?';
            $new_value[$key] =  $value;
        }

        //I don't need the text input button, which occurs first
        array_shift($columns);
        array_shift($new_value);

        $sql = 'UPDATE students ';
        $sql .= ' SET ' . implode(' AND ', $columns);
        $sql .= ' WHERE student_id = ' . $new_value['student_id'];

        $this->adapter->prepare($sql);
        $this->adapter->execute($new_value);

EDIT:
I ended up taking the suggestions and did:
public function getFormNameMapping()
    {
        $realColumnNames = parent::getColumnNames('students');
        $realKeyNames  = parent::getColumnNames('students');
        return array_combine($realColumnNames, $realKeyNames);

    }

    protected function getColumnNames($myTable)
    {
        $sql = "DESCRIBE " . $myTable; //mysql only
        $this->adapter->prepare($sql);
        $this->adapter->execute();
        $results = $this->adapter->fetchAll(PDO::FETCH_COLUMN);
        return $results;
    }

And then:
        $student_model = $this->model->getStudentModel();
        $student = $student_model->findByStudentID($studentID);
        $mappedColumnNames = $student_model->getFormNameMapping();

    <input name="<?PHP echo $mappedColumnNames['FIRST']; ?>" type="text" class="text" value="<?PHP echo $student->FIRST ?>"/>

Thanks.

A: Probably a better approach to consider, but for the question:
$crossRef = array('FIRST'=>'first_name', 'LAST'=>'last_name'); //etc...

foreach($crossRef as $key => $val) {
    if(!empty($myArray[$val])) {
        $mappedColumnNames[$key] = $myArray[$val];
    }
}

I extract the column names from the DB and create the form using the column names. It would be DB agnostic because it dynamically creates the form based on the DB columns.


text:
Q: pgfplots: using a list generated with \foreach as symbolic coords I would like to create some bar charts using pgfplots. Each chart will have a similar format, but with some different labels and values. I am trying to make a command that will generate my chart from this input data. For example, I would like to be able to type \drawchart{Foo/10, Bar/20} and have this produce an appropriate bar chart. I'm having trouble taking this input "Foo/10, Bar/20" and converting it into a list "Foo,Bar" that symbolic coords can use. Here is a MWE, that doesn't work:
\documentclass{article}
\usepackage{tikz, pgfplots}
\pgfplotsset{compat=1.9}

\def\lab{Foo,Bar}
\let\labb\lab

\def\ylabelscmd{\foreach \label/\val in {Foo/1,Bar/2} {{\label},}}
\global\let\ylabels\ylabelscmd

\begin{document}
\ylabelscmd --- \ylabels
\begin{figure}[htb]
    \centering
    \begin{tikzpicture}
        \begin{axis}[
            xbar,
            %symbolic y coords/.expand once = {\lab}, % works
            %symbolic y coords/.expand once = {\labb}, % works
            %symbolic y coords/.expand once = {\ylabelscmd}, % error: ! Missing \endcsname inserted.
            symbolic y coords/.expand once = {\ylabels}, % error: ! Missing \endcsname inserted.
            ytick = data,
            ]
            \addplot+ coordinates { (1,Foo) (2,Bar) };
        \end{axis}
    \end{tikzpicture}
\end{figure}

\end{document}

For some reason, it works if the command in the symbolic coords is a hard-coded list, but if I generate it using \foreach it complains. As you can see in the code, I've tried to evaluate the command using \let and using that, but it seems to make no difference (at least with the expand once option).
Any ideas?

A: I guess all you want is to store the symbolic coordinate list in \ylabels. In order to achive that you can use \xdef as in my code below.

\documentclass{article}
\usepackage{pgffor,tikz, pgfplots}
\pgfplotsset{compat=1.9}

\def\lab{Foo,Bar}
\let\labb\lab

% use this to store the result of your for loop to \ylabelscmd
\def\ylabelscmd{}
\foreach \label/\val in {Foo/1,Bar/2}{\xdef\ylabelscmd{\ylabelscmd,\label}}

\global\let\ylabels=\ylabelscmd

\begin{document}
\ylabelscmd --- \ylabels

\begin{figure}[htb]
    \centering
    \begin{tikzpicture}
        \begin{axis}[
            xbar,
            %symbolic y coords/.expand once = {\lab}, % works
            %symbolic y coords/.expanded = {\labb}, % works
            %symbolic y coords/.expand once = {\ylabelscmd}, % error: ! Missing \endcsname inserted.
            symbolic y coords/.expand once={\ylabels}, % error: ! Missing \endcsname inserted.
            ytick = data,
            ]
            \addplot+ coordinates { (1,Foo) (2,Bar) };
        \end{axis}
    \end{tikzpicture}
\end{figure}

\end{document}


text:
Q: Node isn't working in console I'm watching some tutorials on youtube, how to make a real time chat with node.js from phpacademy channel.
Now I'm in the step where I should run my server.js file in console. I'm running it in console with command

node server.js

When I run it, nothing happens, just a whitespace. It should output a message like "info - socket.io started".
It works when I change the script to something like "console.log("worked");".
Click here for an image.
MongoDB is running perfectly and had no errors till now.
Any suggestions?

A: There are no errors because there are not any errors. Everything is working perfectly but you don't know that. That's why it is a good practice to log on which port is the server running.
For example add in the end of server.js:
console.log('Server running on port: 8080');

You could even move the port in a variable :
var port = process.env.PORT || 8080 ;

console.log('Server is running on port: ' + port);


text:
Q: Algolia Firebase Syncing - AlgoliaSearchNetworkError :( I followed the documentation here to a node.js client syncing Firebase with Algolia. Everything should be setup correctly, however when I try to run node, I get this error:
AlgoliaSearchNetworkError: getaddrinfo ENOTFOUND t29y6y0wwc t29y6y0wwc:443
    at ClientRequest.error (/Applications/MAMP/htdocs/bandly-algolia-firebase/node_modules/algoliasearch/src/server/builds/node.js:227:14)
    at ClientRequest.g (events.js:291:16)
    at emitOne (events.js:96:13)
    at ClientRequest.emit (events.js:188:7)
    at TLSSocket.socketErrorListener (_http_client.js:308:9)
    at emitOne (events.js:96:13)
    at TLSSocket.emit (events.js:188:7)
    at connectErrorNT (net.js:1015:8)
    at _combinedTickCallback (internal/process/next_tick.js:74:11)
    at process._tickCallback (internal/process/next_tick.js:98:9)

The actual code in question is here:
/**
 *  Adding or updating a record from Algolia
 */
function addOrUpdateIndexRecord(dataSnapshot) {
  // Get Firebase object
  var firebaseObject = dataSnapshot.val();
  // Specify Algolia's objectID using the Firebase object key
  firebaseObject.objectID = dataSnapshot.key;
  // Add or update object
  index.saveObject(firebaseObject, function(err, content) {
    if (err) {
      throw err;
    }
    console.log('Firebase object indexed in Algolia', firebaseObject.objectID);
  });
}

Is there something I'm missing here?
Thanks in advance!

A: So as embarassing as it is, I actually made a mistake in the .env file and was putting quotes around the values. DO NOT put quotes around the values for each property.
Everything works as expected now.


text:
Q: How can I mock Azure.Storage.Blobs.BlobContainerClient? I'm rather confused by the Azure.Storage.Blobs.BlobContainerClient class.  One of its constructors (without any parameters) has documentation that suggests the class was specifically designed for mocking:
// Summary:
//     Initializes a new instance of the Azure.Storage.Blobs.BlobContainerClient class
//     for mocking.
protected BlobContainerClient();

However, some of the class's methods require things to be returned that have no public constructor and therefore cannot be meaningfully mocked.  For example:
// Summary:
//     The Azure.Storage.Blobs.BlobContainerClient.GetBlobs(Azure.Storage.Blobs.Models.BlobTraits,Azure.Storage.Blobs.Models.BlobStates,System.String,System.Threading.CancellationToken)
//     operation returns an async sequence of blobs in this container. Enumerating the
//     blobs may make multiple requests to the service while fetching all the values.
//     Blobs are ordered lexicographically by name. For more information, see List Blobs.
//
// Parameters:
//   traits:
//     Specifies trait options for shaping the blobs.
//
//   states:
//     Specifies state options for filtering the blobs.
//
//   prefix:
//     Specifies a string that filters the results to return only blobs whose name begins
//     with the specified prefix.
//
//   cancellationToken:
//     Optional System.Threading.CancellationToken to propagate notifications that the
//     operation should be cancelled.
//
// Returns:
//     An Azure.Pageable`1 of Azure.Storage.Blobs.Models.BlobItem describing the blobs
//     in the container.
//
// Remarks:
//     A Azure.RequestFailedException will be thrown if a failure occurs.
public virtual Pageable<BlobItem> GetBlobs(BlobTraits traits = BlobTraits.None, BlobStates states = BlobStates.None, string prefix = null, CancellationToken cancellationToken = default);

Although Pageable<T> can be mocked because it has a protected constructor, the type that it's required to return (BlobItem) cannot; there's no public constructor.  The only thing a mock can do is return an empty list, which is not at all useful.  Am I missing something, or or this a significant oversight in one's ability to mock this class?


text:
Q: Possible asynchronous error using mongoose and express - db.once('open', function(){console.log('connection opened')}) not reached I have a simple express app with mongodb
I am trying to query the database based on parameters passed with a get request, however while console.log('==params==', params) is reached, console.log('connection opened') is not. I suspect it's an asynchronous problem but I can't fully see why as I'm not even passing any variables around
server.js
var express = require('express');
var db = require('./modules/db')
var logic = require('./modules/logic')

var app = express();
app.set('port', (process.env.PORT || 5000));

app.get('/phrase', function(req, res){
  logic(req.query);
  console.log('req.query', req.query)
})

db.js
var mongoose = require('mongoose');
mongoose.connect('...');
var db = mongoose.connection;
module.exports = db;

logic.js
var db = require('./db')

var logic = function(params){
  console.log('==params==', params)
  db.once('open', function(){
    console.log('connection opened')
  })
}

module.exports = logic;


text:
Q: Docker CMD not executing, program not running So I have a python project for which I have a Dockerfile, but the problem is for some magical reason when I build the docker image and then run it I don't see the result of the code I would see if I just ran it normally on pycharm or on the console, anyone knows why this happens? Its so odd.
FROM python:3.8-slim-buster
WORKDIR /app
COPY requirements.txt requirements.txt
COPY . /app
RUN pip3 install -r requirements.txt
CMD ["python3","main.py"]

The requirements.txt file is where I store all the packages that need to be installed in order to my program work.

A: You copy your application to wrong path.
Since you use WORKDIR you need to know (from the formal site):

The WORKDIR instruction sets the working directory for any RUN, CMD, ENTRYPOINT, COPY and ADD instructions that follow it in the Dockerfile

This means that your COPY . /app copy your application into /app/app, but when you write CMD ["python3","main.py"] this command will execute in /app. I believe the main.py file is not there, but in /app/app.
To fix it you need to change COPY . /app to COPY . .


text:
Q: ActiveMQ destinationPolicy and systemUsage Configuration Looking for some help around systemUsage and destinationPolicy configuration as I'm having some difficulty fully understanding the relationship between systemUsage, destinationPolicy, and flow control.
All our messages are persistent!  producerFlowControl is on.
So we give ActiveMQ say a maximum of 512MB heap space.
Our systemUsage is set as below:
<systemUsage>
    <systemUsage>
        <memoryUsage>
            <memoryUsage limit="200 mb"/>
        </memoryUsage>
        <storeUsage>
            <storeUsage limit="10 gb"/>
        </storeUsage>
        <tempUsage>
            <tempUsage limit="1000 mb"/>
        </tempUsage>
    </systemUsage>
</systemUsage>

Our destination policy as below:
<destinationPolicy>
    <policyMap>
      <policyEntries>
        <policyEntry topic=">" producerFlowControl="true" memoryLimit="1mb">
          <pendingSubscriberPolicy>
          </pendingSubscriberPolicy>
        </policyEntry>
        <policyEntry queue=">" producerFlowControl="true" memoryLimit="1mb">
        </policyEntry>
      </policyEntries>
    </policyMap>
</destinationPolicy>

Can anyone verify the if the following is correct:
This means that for each individual queue/topic the memory limit is 1MB.  What exactly happens when this 1MB is hit, does the queue block for producers or does it page to disc?
The total allowed memory for all queues and topics is 200MB.  Meaning that we could have 200 channels operating at their full capacity of 1MB.  We currently have 16 queues and topics in total so obviously that is never reached.
Are we better to remove the individual policy entry on the memory limit and share the memory between the various channels?
If we do this at what point would they block?
Any help very much appreciated!  Can paypal you some beer money!

A: You're touching on a number of points here, which I'll answer out of order.
memoryUsage corresponds to the amount of memory that's assigned to the in-memory store. storeUsage corresponds to how much space should be given to the KahaDB store. You either use one or the other, depending on how you want your broker to persist messages or not. tempUsage is a special case for file cursors (http://activemq.apache.org/message-cursors.html) - a mechanism to overflow the memory from the in-memory store to disk if the memory limit is exceeded (you have to configure this behaviour at the destination level if you want it).
policyEntry@memoryLimit is a sub-limit for individual destinations.
What happens when memory limits are exceeded depends on whether producer flow control (PFC) is turned on. It's on by default for queues, off for topics and asynchronous sends to queues; all this can be configured in the policyEntry (http://activemq.apache.org/per-destination-policies.html).
If you hit a "memory limit" when PFC is on, your clients will block until someone frees up space by consuming messages from the store. If it's off, the send will throw an exception (better the client fall over than the broker). "Memory limit" means either the one defined by memoryUsage across all queues, or the queue-specific limit (it's possible to hit the former before the latter).
Whether or not you want a destination-specific limit depends on your use case. I'd suggest to ignore it unless you're trying to achieve a specific outcome.


text:
Q: Speed up Xamarin App Start Yo!
My Xamarin App takes now 3 seconds till my breakpoint gets to the first line of code. I want to speed things up if possible or at least make some loading animation or Logo while we wait.
is this possible?
some infos: my whole code is loaded in the App.xaml.cs, i build my whole user interface there, i just load 2 images as resources (2x200KB) and one font in the android folder.
Namespaces i use:
using System;
using System.Net;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Threading.Tasks;
using System.Reflection;
using System.Text;
using Xamarin.Forms;
using Rg.Plugins.Popup;
using Rg.Plugins.Popup.Services;
using Rg.Plugins.Popup.Pages;
using PCLStorage;
using SQLite;
using ModernHttpClient;
using System.Net.Http;

it would be nice at least having a little startup animation e.g. an App logo or something like that to cover up the 3s delay but if it takes 3s to reach the code i can't do it in code.
btw: i just tested on android because i don't have an IOS or Windows Phone

Maybe it's helpful to post this link to my current source code:
https://pastebin.com/v2hv0ur4
the rest of my project is just the standard Xamarin Project, when opening a new one plus a new font in the android folder and 2x200KB images.
also the other code files are exactly as they were, i do not use XAML.


text:
Q: Share user's information with other apps with same signature My play store account has over 100 apps published and all of them have this common user generation process which includes OTP verification. Interesting to note is all the apps have same user object with same properties for a particular OTP verified number, which gets stored in the respective SharedPreferences as string.
For better User Experience I would like to trim down the user generation process if there is any one app installed in the device and has done OTP verification. I want to share this user object, which is saved as string in each app's SharedPreferences.
So here's what I want when I install com.domain.app.cX app:
1) com.domain.app.cX -> (Do you have a verified user?) -> com.domain.app.cY
2.1) com.domain.app.cY -> (Yes I have, here is it "user json") -> com.domain.app.cX
or
2.2) com.domain.app.cY -> (No I don't have any user) -> com.domain.app.cX
3) Move to check if com.domain.app.cZ is installed and do over from step 1
Options I have:
1) I have read about ContentProvider and understood that you need to put in a URI of ContentProvider which is package name specific.
2) Use package name with createPackageContext and get SharedPreferences for any app.
In both the solutions I don't know which app is already installed on device and hence URIs of all ContentProvider and package name of the app.
Is there any solution in which I can leverage the signature of the app, since all the app are signed with same certificate.

A: Using Broadcast receivers and Custom Broadcasts.
with redundant common data across all apps with shared preferences.
All the apps contain a pair of broadcast receiver and sender.
The app which wants verification status will send a broadcast.
The other apps which listen to the broadcast will receive it and add the verification status in the intent and send again as a broadcast.
Now the 1st app which send the broadcast for verification status will receive the latest status and update the UI accordingly. If the default value is false then show the verification screen.


text:
Q: Can I be sure that the binary code of the functions will be copied sequentially? Sorry if this question already exist, because I hope this approach is used but i just don't know how this called. So, my purpose to execute sequence of functions from memory, for this I copied size of first and last func.
This is my first try:
source.cpp

void func1(int var1, int var2)
{
  func2();
  func3();
  //etc.
}
void func2(...){...}
void func3(...){...}
void funcn(){return 123;}//last func as border, I do not use it

//////////////////////////////////////////////////

main.cpp

#include"source.cpp"

long long size= (long long)funcn-(long long)func1;// i got size of binary code of this funcs;
// and then i can memcpy it to file or smth else and execute by adress of first

Firstly it's worked correct, but after updating my functions it's crashed. Size has become negative.
Then i tried to attach it to memory hardlier:
source.cpp

extern void(*pfunc1)(int, int);
extern void(*pfuncn)();

void(*pfunc1)(int , int) = &func1;
void(*funcn)() = &funcn;

static void __declspec(noinline) func1(int var1, int var2)
{
 //the same impl
}
static void __declspec(noinline) func2(...){...}
static void __declspec(noinline) func3(...){...}
static void __declspec(noinline) funcn(...){retunr 123;}

//////////////////////////////////
main.cpp
#include"source.cpp"

long long size= (long long) pfuncn - (long long) pfunc1;
//same impl

This worked after my 1st update, but then, I had to update it again, and now this gives me wrong size. Size was  near 900+ bytes. I changed some funcs, and size become 350+ bytes i haven't changed that many.
I disabled optimizations and inline optimizations.
So my question is how to be sure that my func1 will be less adress then last funcn and what could change their locations in memory. Thank you  for attention.

A: // and then i can memcpy it to file or smth else and execute by adress of first

copy it in memory and then call it in allocated memory and then call by adress of allocation.

This needs to be stated:
You cannot copy code from one location to another and hope for it to work.

*

*There's no guarantees that all the code required to call a function
be located in a contiguous block.

*There's no guarantee the function pointer actually point to the
beginning of the needed code.

*There's no guarantees you can effectively write to executable memory. To the OS, you'd look a lot like a virus.

*there's no guarantees the code is relocatable (able to work after being moved to a different location). for this it requires to use only relative addresses

In short: unless you have supporting tools that go beyond the scope of standard C++, don't even think about it.

A: GCC family only!
You can force the compiler to put the whole function to separate section. Then you can know the memory area where the funcion resides.
int __attribute__((section(".foosection"))) foo()
{
    /* some code here */
}

in linker script in the .text you need to add
 .text :
  {

      /* ... */

    __foosection_start = .;
     *(*foosection)
     *(.foosection*)
     __foosection_end = .;

     /* .... */

and in the place where you want to know or use it
extern unsigned char __foosection_start[];
extern unsigned char __foosection_end[];

void printfoo()
{
    printf("foosection start: %p, foosection end: %p\n ", (void *)__foosection_start, (void *)__foosection_end);
}

A: This is probably not possible because of a requirement you did not mention, but why not use an array of function pointers?
std::function<void()> funcs[] = {
    func2,
    func3,
    [](){ /* and an inline lambda, because why not */ },
};

// Call them in sequence like so:
for (auto& func: funcs) {
   func();
}


text:
Q: Laplacian on a Lie group Let $G$ be an $n$-dimensional Lie group over $\mathbb R$ (I am happy to assume $G$ is compact) and $(V_1,\dots,V_n$) a basis for its Lie algebra, $\mathfrak g$. Viewing the $V_i$ as left-invariant vector fields on $G$, they act linearly $C^{\infty}(G)\to C^{\infty}(G)$ by $$V_if(x):=\lim_{t\to 0}\frac{f(X_t^x)-f(x)}{t},$$
where $$\dot X_t^x=V_i(X_t^x), \quad X_0^x=x\in G.$$ We can then build another linear operator $L:C^{\infty}(G)\to C^{\infty}(G),\; L=\sum_i V_i^2$, where $V_i^2= V_i\circ V_i$.

Letting $\mu$ be a left Haar measure on $G$ and $f,g\in C_c^{\infty}(G)$ smooth functions of compact support, do we have the identity $$\int_GLf(x)g(x)\mu(dx)=\int_Gf(x)Lg(x)\mu(dx)?$$ I.e., is $L$ symmetric on $L^2(G,\mu)$?
I've tried fiddling around with the above definitions, but seem only to arrive at massive, unrevealing formulae!


text:
Q: MVC - Showing validation message in place of Label Suppose this is my view...

         @Html.LabelFor(model => model.Title, new { @class = "control-label" })
         @Html.ValidationMessageFor(model => model.Title, null, new { @class = "help-inline" })

            @Html.EditorFor(model => model.Title)

In case of error How we can hide the Label and display validation message in place of Label?
Please suggest on this...

A: You could display the Label only if the ModelState is valid:

    @if (this.ViewData.ModelState.IsValid)
    {
        @Html.LabelFor(model => model.Title, new { @class = "control-label" })
    }
    @Html.ValidationMessageFor(model => model.Title, null, new { @class = "help-inline" })

        @Html.EditorFor(model => model.Title)

Notice that if you are using client side validation you will also need to hook up to the validate method on the client and toggle the corresponding label visibility as well.

A: Just to compliment Darin's answer, if you are using client-side validation you will need to do something like
$("#myForm").validate({
    invalidHandler: function(event, validator) {
        $('.control-label').hide();
    }
});

Otherwise the label won't hide.
It's worth still checking ModelState.IsValid when the page loads as well though incase the user has JS disabled.


text:
Q: How to "update_attributes" without executing "before_save"? I have a before_save in my Message model defined like this:
   class Message < ActiveRecord::Base
     before_save lambda { foo(publisher); bar }
   end

When I do:
   my_message.update_attributes(:created_at => ...)

foo and bar are executed.
Sometimes, I would like to update message's fields without executing foo and bar.
How could I update, for example, the created_at field (in the database) without executing foo and bar ?

A: Use the touch method. It's elegant and does exactly what you want

A: In rails 3.1 you will use update_column.
Otherwise:
In general way, the most elegant way to bypass callbacks is the following:
class Message < ActiveRecord::Base
  cattr_accessor :skip_callbacks
  before_save lambda { foo(publisher); bar }, :unless => :skip_callbacks # let's say you do not want this callback to be triggered when you perform batch operations
end

Then, you can do:
Message.skip_callbacks = true # for multiple records
my_message.update_attributes(:created_at => ...)
Message.skip_callbacks = false # reset

Or, just for one record:
my_message.update_attributes(:created_at => ..., :skip_callbacks => true)

If you need it specifically for a Time attribute, then touch will do the trick as mentioned by @lucapette .

A: update_all won't trigger callbacks
my_message.update_all(:created_at => ...)
# OR
Message.update_all({:created_at => ...}, {:id => my_message.id})

http://apidock.com/rails/ActiveRecord/Base/update_all/class

A: You could also make your before_save action conditional.
So add some field/instance variable, and set it only if you want to skip it, and check that in your method.
E.g.
before_save :do_foo_and_bar_if_allowed

attr_accessor :skip_before_save

def do_foo_and_bar_if_allowed
  unless @skip_before_save.present?
    foo(publisher)
    bar
  end
end

and then somewhere write
my_message.skip_before_save = true
my_message.update_attributes(:created_at => ...)

A: update_column or update_columns is the closest method to update_attributes and it avoids callbacks without having to manually circumvent anything.


text:
Q: Modified depth first search to find total sum Disclaimer: This is not a class project, more of work related. I tried finding example online but generally its just for transversing through the tree. I am coding it in C#
Hi all,
I am trying to use DFS to calculate the biggest possible number sum combination which will be equal to the number given with some other conditions.

*

*Total sum of weight needs to be below 150 in a class.

*Total height in the class cannot be more than 600.

*Max number of student if possible in Class A

*If same height and weight, the person with the smaller ID will be considered first.

ID - Weight - Height
1 - 80 - 150
2 - 30 - 100
3 - 30 - 150
4 - 50 - 100
5 - 60 - 150
6 - 40 - 100
Class 1: 1, 2, 6
Class 2: 3, 4, 5
Class 3:
Anyone can point me in the right direction or DFS shouldn't be used in this case?

A: DFS and BFS works with trees, which you currently do not have. IMO, creating a tree with all possible combinations is not the right way in this case (but of course you can do it). If your set is small you can try to enumerate all solutions without creating a tree and using DFS or BFS (as @Dennis.Verweij is proposing).
I think that your problem is a variation of the Knapsack problem, which is unfortunately NP-Complete
Otherwise take a look at Integer Programming. This is a hard problem to solve, but you can find some relevant algorithms (which might actually use internally DFS) to help you with the solution.


text:
Q: How to get output of a Java program EXACTLY as if it was running on the terminal? I can redirect output to a file or other output stream with System.setOut(...), but if I do:
System.out.print("\rTesting")
System.out.print("\rHello world!")

Then on the terminal I would just see "Hello world!" at the end, but if I write to a file, I get all the characters printed, and I ONLY want to get "Hello world!"
I could write a custom OutputStream that does that, but I want to handle things identically to my terminal, such as handling weird escape sequences like "\033[2K". I've tried using cat, echo, and tee, and redirecting to a file, but it all gives me the full sequence of characters.
Platform specific solutions are fine (though ideally it would run on any reasonable Linux distribution at least). I'm even fine with a bash command or something that will let me do this.

A: The thing that happens here is you are using CR (\r) instead of LF (\n). In your case it means that you first print line number 1 and then you jump all the way to the left but you Don't jump down one line and the result is that your first line disappears behind the second.


text:
Q: Mathematical Techniques to Reduce the Width of a Gaussian Peak In the chemical analysis by instruments, the signals of several molecules are overlapped which makes it difficult to determine the true area of each peak, such as those shown in red. I simulated this as a sum of six Gaussians (with some tailing elements)

*

*One of the simplest technique is to raise the discrete signal values to any positive power (n>0). The standard deviation of the Gaussians becomes smaller and smaller (C, in blue). The big drawback is that we lose all the original peak area information. The transformed data is highly resolved now at the cost of losing true area information.

*Alternatively, we can add a first derivative of the signal and subtract the second derivative from the original signal i.e.,
Sharpened signal= Original signal +K (first derivative) - J(second derivative)
K and J are small positive real numbers. This neat "trick" maintains the true area because area under the derivatives is negligible (zero in ideal cases).
Do mathematicians use any other transformations which can make each overlapping peak very narrow, yet maintain the original peak areas. I am not interested in curve fitting techniques at this moment. Any pointers to some similar "peak sharpening" transformations would be appreciated which can resolve overlapping signals.
Thanks.

A: OK, here are my 2 cents. I'll try to outline the logic and then make a conclusion. We'll start with the Gaussian case.
Suppose that we have a Gaussian peak $f(t)=e^{-t^2/2}$. We want to de-convolve it to the Dirac delta-measure. Since the Fourier transform $\widehat f(s)=\int f(t)e^{-ist}\,dx$ satisfies $\widehat{(f*g)}=\widehat f \widehat {g{,}}$ and the Fourier transform of the standard Gaussian is (up to a constant factor) the standard Gaussian again, the naive but natural idea is just to multiply $\widehat f$ by $e^{s^2/2}$ and to take the inverse Fourier transform of the resulting identically $1$ function.
Unfortunately this is unfeasible as written because of the noise, finite computational precision, etc., so we have to truncate the natural Fourier mulitplier $e^{s^2/2}$ somehow. The idea is to multiply it by some even positive cutoff function $\Psi$ with bounded support. Then the noise will be amplified (on the worst frequency) by
$$
M=\max_s e^{s^2/2}\Psi(s)
$$
but instead of the Dirac point mass, we will get the inverse Fourier transform of $\Psi$. We want that inverse Fourier transform to be as concentrated near the origin as possible. We also want to make it a non-negative function rather than some sign-changing wave. Since we must have $\Psi(0)=1$ to preserve the integral of $f$, we come to the problem of choosing an even function $\Psi$ with bounded support (say $[-\pi,\pi]$; we can always scale later) such that $\Psi(0)=1$, the inverse Fourier transform $\Psi^\vee\ge 0$, and $-\Psi''(0)=\int\Psi^\vee(t)t^2\,dt$ is minimized (other measurements of concentration give slightly different optimizers but pretty much the same results).
This problem is solvable and the solution is the (properly normalized) convolution of $\chi_{[-\pi/2,\pi/2]}(s)\cos s$ with itself, i.e.,
$$
\Psi(s)=\frac 1\pi[(\pi-|s|)\cos s+\sin|s|]
$$
(I'll skip the derivation). Thus, after various scalings, the final family of multipliers is
$$
H_{\alpha,K}(s)=e^{\alpha^2 s^2/2}\Psi(K^{-1}\alpha s)\,.
$$
and the "peak sharpening formula" is $f\mapsto (H_{\alpha,K}\widehat f)^\vee$.
It turns out that $K=1$ does not noticeably change the picture (but filters out the high frequency noise from the measurements). The noise amplification grows pretty fast with $K$. The corresponding maxima are about
$$
\begin{matrix}
K &\max
\\
1.0 & 1.09
\\
1.1 & 1.55
\\
1.2 & 2.65
\\
1.3 & 5.33
\\
1.4 & 12.4
\\
1.5 & 33.2
\end{matrix}
$$
(with noise at $1$ to $10\%$ of the signal, the higher values of $K$ are pretty useless), so I would recommend setting $K$ between $1.3$ and $1.4$. The whole game is choosing $\alpha$. The legitimate choice is up to the width of the narrowest peak but somewhat higher values are also sort of admissible except you'll get peaks exchanging energy a bit. The rule of thumb is to watch for noticeable negative values in the transformed signal: once they appear, you certainly went too far. Before that moment you are reasonably safe (but not entirely foolproof).
The only difference for EMG is that you want to add one more factor $1+i\beta s$ to your multiplier, i.e., to play with the family
$$
H_{\alpha,\beta, K}(s)=e^{\alpha^2 s^2/2}(1+i\beta s)\Psi(K^{-1}\alpha s)\,.
$$
If $\beta>0$ gets large, it may force you to make $K$ smaller. The effect of going too far in $\beta$ is the same: you'll see noticeable negative values in the transform plus the peaks will noticeably shift to the left. Playing with $2$ parameters is harder than with one and I have no clear advice on in which order to adjust them to get the best results. Just try and let me know what you think.
.
The original signal is in green, the dots are the actual locations at which EMG's are "centered". Something like that is possible IF you can guess one particular parameter right. I still cannot figure out how to teach the machine that guessing.
You'll, probably, like this one too:

Or this one:

The current version of the code. This is a dirty homemade contraption, of course, but it is totally automatic.
import graph;
access settings;
//settings.outformat="png";

size(500,300,IgnoreAspect);

int sec=seconds();
srand(sec); //Just generates a new picture every time
//srand(1562245957); //was really bad, fixed
//srand(1562264140); //was bad, fixed
//srand(1562265837); //still bad

bool ON=false; //Set to true if you want to see suppressed low values

real beta=0.04; //Noise level (maximum; you need to adjust the code a bit to use the average)
real Beta=0.12; //Cutoff level (approximately 3 times maximal noise)

real K=1.7, L=3, TOL=2.5;  //Don't change these UNLESS
int res=8, dirr=5;//you understand what you are doing

int M=4; //The number of peaks. Set to 1 to see the individual response.

int n=4096; //The sampling range (4096 time ticks with no signal before and after)
real h=1/n;

real QQ=0.07*unitrand(); //Average lambda; set to 0 to see pure Gaussians
real AA=0.15*sqrt(unitrand()); //Average sigma; set to zero to see pure exponentials
real det=unitrand(); //Peak spacing from equidistant det=1 to random det=0

real[] A,Q,X,Y;
for(int m=0;m<M;++m)
{
A[m]=AA*(0.2+unitrand());
Q[m]=QQ*(0.5+0.5*unitrand());
X[m]=det*m/M*n/2+(1-det)*(rand()%quotient(n,2))+quotient(n,8);
Y[m]=0.45+0.55*unitrand();
}

X=sort(X); A=sort(A); //sigma grows with time

real qual(real x)
//deconvolution quality control: the bigger the sum of qual(p[k]), the better.
{
return
max(x-2*Beta,0)^3-min(x,0)*Beta^2;
}

//write(A); write(Q); pause();

pair[] p, ptemp;
//p is the (simulated) raw data. It would be interesting to try it on something real.

////////////////Generation of p /////////////////

for(int k=0;k<n;++k) {p[k]=(0,0); ptemp[k]=(0,0);}
p.cyclic=true; ptemp.cyclic=true;

for(int m=0;m<M;++m)
{
pair f(int k)
{
return exp(-pi*A[m]^2*k^2)*expi(-2*pi*k*X[m]*h)/(1,2*pi*Q[m]*k);
}
for(int k=-floor(n/2);k<n/2;++k) ptemp[k]=f(k);
ptemp=fft(ptemp);
ptemp/=max(map(abs,ptemp));
ptemp.cyclic=true;
p+=Y[m]*ptemp;
}

real s=0;
for(int k=0;k<n;++k) {s+=p[k].x;}

for(int k=0;k<n;++k) p[k]+=beta*(2*unitrand()-1);

//////////// End of generation of p ///////////////////

//////////// Algorithm begins ///////////////////

pair[] g=fft(p)/n;

real psi(real t)
{
real s=abs(t);
if(s>pi) return 0;
else
//return sin(s)/s*(1-s/pi);
return ((pi-s)*cos(s)+sin(s))/pi;
}

pair R(pair x)
//Suppression of low values.
{
if (ON) return x;
real y=max(x.x-Beta,0);
if(x.x<0) return (0,0);
else return ((x.x<4*Beta? y*4/3:x.x),x.y)/(1-4*Beta^2);
}

real expp(real x)
{
return 1+x+x^2/2+x^3/12;//A bit more stable than the true exp
return exp(min(x,15));
}

struct T {pair[] p; real u; real q;}

int count=0;

real[] pM; pM[n]=0;
for(int k=n-1; k>-1; --k) pM[k]=max(p[k].x,pM[k+1]);

pair[] pp=copy(p), p1;

T U(pair D, real qq)
{
++count;
write("U "+string(count));

real u=0,v=1;

void proc()
{
for(int kk=0; kk<10;++kk)
{

real w=(u+v)/2;
real a=w*D.x, q=w*D.y;

real b=min(max(a*sqrt(2*pi)/K,2*pi*q/L),1/5);

pair[] G=fft(pp)/n, mult;
p1=copy(pp);

for(int k=0;k<n;++k) mult[k]=(0,0);
mult.cyclic=true;

G.cyclic=true;

for(int k=floor(-n/2);k<n/2;++k)
{
mult[k]=expp(pi*a^2*k^2)*(1,-2*pi*q*k)*psi(b*k);
if(abs(mult[k])>TOL) mult[k]=TOL*unit(mult[k]);
G[k]*=mult[k];
}

pair[] ppp=fft(G); ppp=reverse(ppp);
ppp.cyclic=true;

bool flag=true;

//for(int k=0;k<n;++k) if(abs(mult[k])>TOL) flag=false;

for(int k=floor(n*qq-n/res);k<n+n/2/res && flag;++k)
{
if(
ppp[k].x<-0.8*Beta || (k>-1 && k<n && pM[k]<Beta/2 && ppp[k].x>Beta)
)
flag=false;
}

if(flag && abs(G[floor(n/2)-1])<1/10^10) {u=w; p1=copy(ppp);} else v=w;
}
}

proc();
p1.cyclic=true;

if(p1[n-1].x>Beta) {write(p1[n-1].x,pM[n-1]); pause();}

real q=0;
for(int k=floor(n*qq-n/res);k<n;++k) q+=qual(p1[k].x);

T tt=new T;
tt.p=copy(p1); tt.u=u; tt.q=q;

write(tt.u);

return tt;

}

T[] tt;

for(int k=0; k<res; ++k)
{
draw(box((k/res,0),((k+1)/res,1)),yellow);
pair D=expi(pi/2);
tt[k]=U(D,k/res); real W=tt[k].q;
for(int m=dirr-1; m>-1; --m)
{
D=dir(90*m/dirr);
T ttt=U(D,k/res);
if(ttt.q>W) {W=ttt.q; tt[k]=ttt;}
}
//write (tt[k].u, tt[k].q);
pp=copy(tt[k].p);
}

for(int k=0;k<n;++k)
{
int q=floor(k/n*res);
if(q<1) {pp[k]=tt[0].p[k];}
else
{
real t=q+1-k/n*res;// t=sin(pi*t/2);
pp[k]=((1-t)*tt[q].p[k]+t*tt[q-1].p[k]);
}
}

pp=map(R,pp);
real ss=0;
for(int k=0;k<n;++k) {ss+=pp[k].x;}

write("*************");

path Q=nullpath,  P=nullpath;
for(int k=0;k<n;k+=4)
{
Q=Q--(k*h,pp[k].x);
P=P--(k*h,p[k].x);
}

draw(P,green);
draw(Q);
draw((0,1)--(0,0)--(1,0));
draw(box((0,-Beta),(1,Beta)),red);

for(int m=0; m<M ;++m)
{
dot((X[m]*h,0));
pair Z=intersectionpoint((X[m]*h,-20*M)--(X[m]*h,20*M),Q),ZZ=(X[m]*h,Y[m]);
draw((X[m]*h,0)--Z,blue); dot(ZZ,magenta);
}

label(string(sec),(0,0),S);

label("Area ratio="+string(floor(1000*ss/s)/1000),(0.8,1.13),(0,0),fontsize(8));

//pause();

A: Here is an overview of peak sharpening (resolution enhancement) techniques:
1. even derivative sharpening: $R=Y-k_2 Y''+k_4 Y''''$: works well for symmetric line shapes, reduces the width of a Gaussian peak by 20% and of a Lorentzian peak by 60%
2. first derivative symmetrization: $R=Y+k_1 Y'$: converts an exponentially broadened peak into a symmetric Gaussian, and then the width can be reduced via method 1.
3. power law method: raise each data point to a power $n>1$: moves the peaks apart, increasing the resolution, to be followed by sharpening method 1.
4. deconvolution: effective if the original shape of the peaks has been broadened and/or made asymmetrical by a broadening process that is known or can be measured separately.

A: There are numerous methods in the context of "inverse problems". Assuming that the Gaussian peaks are generated by a convolution of a "spike train" (i.e. a sum of positive Diracs peaks) with a Gaussian (plus some noise), you can do any of the numerous methods for regularized deconvolution.
Let me just mention variational regularization: Let $g$ be the Gaussian and $\mu$ be the spike train. Then your signal is $f=g*\mu + $ noise. A regularized deconvolution can be obtained by minimizing
$$\|g*\mu - f\| +\alpha\|\mu\|$$
but the choice of norms and the regularization parameter $\alpha>0$ really matter. A simple choice is the $L^2$ norm for the residual and the variation norm (aka Radon norm) for the measure $\mu$. This provably leads to a spiky reconstruction and the process is stable.


text:
Q: wait for java Async calls created in a loop to complete I have a for loop that creates several Async calls to the client, and in this loop, I want to wait until the client's response is given.
for (SocketIOClient soc : server.getRoomOperations(roomName).getClients()) {
                soc.sendEvent("giveRoundData", new AckCallback<String>(String.class) {
                    @Override
                    public void onSuccess(String s) {
                        System.out.println("Hello 1");
                    }
                });
}
System.out.println("Hello 2")

problem is the order of execution.
for example in the code above the output is ( for one iteration ) :
Hello 2
Hello 1

but I want this to be like :
Hello 1
Hello 2

is there a way I can wait until every onSuccess() is executed?

A: Use Java Synchronizers like CountDownLatch. Use appropriate method that gives the count of the clients when creating the CountDownLatch.
    CountDownLatch latch =
        new CountDownLatch(server.getRoomOperations(roomName).getClients().size());
    for (SocketIOClient soc : server.getRoomOperations(roomName).getClients()) {
                soc.sendEvent("giveRoundData", new AckCallback<String>(String.class)
    {
                    @Override
                    public void onSuccess(String s) {
                        System.out.println("Hello 1");
                        latch.countDown();
                    }
                });
    }
    latch.await();
    System.out.println("Hello 2")


text:
Q: Передача данных из представления в контроллер ASP.NET Мне нужно передать данные из представления в контроллер и затем передать другому представлению. При получении данных из представления я получаю все значения равные 0. Помогите пожалуйста разобраться в чем проблема.
Контроллер:
public class CalculationController: Controller
{
    private readonly ICalculationParameters calculationParameters;
    private Parameters pam = new Parameters();

    public CalculationController(ICalculationParameters calculationParameters)
    {
        this.calculationParameters = calculationParameters;
    }

    public IActionResult CalculationParameters()
    {
        return View();
    }

    [HttpPost]
    public ActionResult CalculationParameters(Parameters pam)
    {
        if (ModelState.IsValid)
        {
            calculationParameters.Calculation(pam);
            return RedirectToAction("CalculationSize");
        }
        return View(pam);
    }

    public IActionResult CalculationSize(Parameters pam)
    {
        CalculationOfParameters calPam = new CalculationOfParameters(pam);
        return View(calPam.parameters);
    }
}

Представления из которого берутся данные вводимые пользователем:
@model Parameters

            <form asp-action="CalculationParameters" method="post">

                                    Напряжение питания инвертора

                                        <input asp-for="En" class="form-control" />

                                    Внешняя нагрузка

                                        <input asp-for="Cn" class="form-control" />

                                    Высокий уровень входного напряжения

                                        <input asp-for="Uvh1" class="form-control" />

                                    Толщина диэлектрика

                                        <input asp-for="hd" class="form-control" />

                                    Низкий уровень входного напряжения

                                        <input asp-for="Uvh0" class="form-control" />

                                    Время включения

                                        <input asp-for="t" class="form-control" />

                                    Высокий уровень выходного напряжения

                                        <input asp-for="Uvyh1" class="form-control" />

                                    Диэлектрическая проницаемость диэлектрика

                                        <input asp-for="Ed" class="form-control" />

                                    Низкий уровень выходного напряжения

                                        <input asp-for="Uvyh0" class="form-control" />

                                    Подвижность электронов

                                        <input asp-for="u" class="form-control" />

                                    Пороговое напряжение

                                        <input asp-for="U0" class="form-control" />

                                <input class="btn btn-success" type="submit" value="Рассчитать" />

            </form>

Класс CalculationOfParameters (здесь проводится расчет параметров по значениям полученным из представления):
public class CalculationOfParameters
{
    public Parameters parameters = new Parameters();

    public CalculationOfParameters(Parameters pam)
    {
        this.parameters = pam;

        parameters.K = Math.Pow(1 - parameters.Uvyh0 / (parameters.En - parameters.U0), 2) / (2 * (parameters.Uvh1 - parameters.U0)
            / (parameters.En - parameters.U0) *
            parameters.Uvyh0 / (parameters.En - parameters.U0) - Math.Pow(parameters.Uvyh0 / (parameters.En - parameters.U0), 2));
        parameters.wn_ln = (2 * parameters.hd * Math.Pow(10, -9) * parameters.Cn * Math.Pow(10, -12)) /
            (8.85 * Math.Pow(10, -12) * parameters.Ed * parameters.u * Math.Pow(10, -4) * parameters.t * Math.Pow(10, -6) *
            (parameters.En - parameters.U0 - parameters.Uvyh1));
        parameters.wk_lk = parameters.K * parameters.wn_ln;
    }
}

Представление CalculationSize в которое передаются данные полученные в классе CalculationOfParameters:
@model Parameters

Результаты

        Отношение крутизны характеристики ключевого МДП транзистора к соответствующей характеристике нагрузочного МДП транзистора Kк / Kн = @Model.K

        Отношение wн / lн для нагрузочного МДП транзистора = @Model.wn_ln

        Отношение wk / lk для ключевого МДП транзистора = @Model.wk_lk

        Введите минимально возможные при данной технологии значения lк и wн

        <form asp-action="CalculationParameters" method="post">

                                Длина ключевого транзистора

                                    <input asp-for="lk" class="form-control" />

                                Ширина нагрузочного транзистора

                                    <input asp-for="wn" class="form-control" />

        </form>