text:
Q: how to get rid of the orders of zeroes of analytic function? I was reading complex variable theory by fisher.In ch 3 i faced the following problem.
let me draw the background.
Then i will ask the problem,show my attempt.
Suppose that h is an analytic function  on a domain $\mathcal{D}$ except for a finite number of poles.
Let $\gamma$ be a piecewise smooth close curvein $\mathcal{D}$
 whose inside lies in $\mathcal{D}$.
  and which passes through no zeroes or poles of h.
  Let $z_1,z_2,\cdot \cdot z_n$ be the distinct zeroes of h inside $\gamma$ and let $w_1,w_2,\cdot \cdot w_n$ be distinct poles of h inside $\gamma$
Let $n_j$ be the order of zero of h at $z_j,j=1,2,\cdot \cdot N$
Then
$$
h(z)=(z-z_j)^{n_j}G_j(z)
$$
where $G_j$ is analytic near $z_j$ and $G_j(z_j)\neq 0$.
Hence
$$
\frac{h'(z)}{h(z)}=\frac{n_j}{(z-z_j)}+\frac{G'_j(z)}{G_j(z)}
$$
so we get
$$
Res\Big(
\frac{h'}{h};z_j
\Big)=n_j
$$
Likewise if $m_k$ is the order of the pole of h at $w_k,k=1,2...M$ then
$$
h(z)=\frac{H(z)}{(z-w_k)^{m_k}}
$$
where $H_k$ is analytic near $w_k$ and $H_k(w_k)\neq 0$
Thus
$$
\frac{h'(z)}{h(z)}=\frac{-m_k}{z-w_k}+\frac{H'_k}{H_k}
$$
for z near $w_k$ so
$$
Res\Big(
\frac{h'}{h};w_k
\Big)=-m_k
$$
Applying the residue thm to the function $\frac{h'}{h}$ we get
$$
\frac{1}{2\pi i}
\int_{\gamma}\frac{h'(z)}{h(z)}dz=
\sum_{j=1}^N n_j-\sum_{k=1}^M m_k
$$
ok,thats the background.Now in the exercise the  statement is
Suppose g be an analytic function on a domain containing $\gamma$ and its inside.
 then
$$
\frac{1}{2\pi i}
\int_{\gamma}\frac{h'(z)}{h(z)}g(z)dz=
\sum_{j=1}^N  g(z_i)-\sum_{k=1}^M g(w_j)
$$
where $z_1,....z_n$ are the zeroes and $w_1,....w_n$ are the poles of h inside $\gamma$,each listed according to its $\textit{multiplicity}$
An obvious thing to do is multiply $g(z)$ with $\frac{h'}{h}$ and the residue then becomes
$$
\lim_{z \rightarrow z_j}
\frac{h'}{h}g(z)=n_jg(z_j)
$$
but cant get rid of the $n_j$
Again $g(z)$ is analytic inside the domain $\mathcal{D}$.so integrating along $\gamma$ will yield 0 due to no pole.and also $g'(z)$ is analytic inside $\mathcal{D}$.so integrating it too along $\gamma$ yield 0
and $(gh)'=g'h+h'g$ so $h'g=(gh)'-g'h$ dividing by $h$ we get
$$
\frac{h'}{h}g=\frac{(gh)'}{h}+\frac{g'h}{h}
$$
 the seond term is $g'$ which will give zero  integrating along $\gamma$
now writing $h(z)$ near a pole $z_j$, $h(z)=(z-z_j)^nG(z)$ ,where $G(z)$
is regular analytic inside $\mathcal{D}$ we see
$$
\begin{split}
(hg)'=&((z-z_j)^nG(z)g)'\\
=& n(z-z_j)^{n-1}Gg+(z-z_j)^nG'(z)g+(z-z_j)^nG(z)g'
\end{split}
$$
dividing by $h$ we get
$$
\frac{(hg)'}{h}=\frac{ng}{(z-z_j)}+\frac{G'g}{G}+g'
$$
but then again the residue is still $n_jg(z_j)$ as $\lim{z\rightarrow z_j}$


text:
Q: .htaccess Vanity/Nice URLs Causing 404 Error to be Homepage I recently switched from using this in my .htaccess file
RewriteRule ^example index.php?page=example [L]

To this:
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^./]+)/?$ index.php?page=$1 [L,QSA]

The issue is that if I visit something like example.com/euffhfrfreif - it'll just display me my homepage.
I'm trying to configure vanity URLs, so that rather than visitors using example.com/index.php?page=contact, they'll just visit example.com/contact - I've seen this a lot online and it's supposed to be better for Google, etc.
This error doesn't apply to any folders, so visiting example.com/djfhds/fdjdnf will display a 404 error.
How can I get my 404 error back but keep (or keep something similar too) my new system?
Also: I have rewriteengine on and a 404 error page defined in .htaccess.

A: Based on your shown samples, could you please try following rules. Please make sure you clear your browser cache before testing your URLs.
RewriteEngine ON
RewriteRule ^([^./]+)/?$ index.php?page=$1 [L]

The issue is that you are using an else statement in index.php to show your homepage.
Change your else statement to a 404 error page and make your home page be at index.php?page=home, then add this to htaccess:
RewriteRule ^([^./]+)/?$ index.php?page=$1 [L]

redpajama_set_name: RedPajamaStackExchange


text:
Q: C# Implicit/Explicit Byte Array Conversion I have following problem. I want to convert an integer value or float value into an byte array. Normaly I use the BitConverter.GetBytes() method.
int i = 10;
float a = 34.5F;
byte[] arr;

arr = BitConverter.GetBytes(i);
arr = BitConverter.GetBytes(a);

Is there a possibility to do this with implicit/explicit methods??
arr = i;
arr = a;

and also the other way around??
i = arr;
a = arr;

A: You can do it through an intermediate class. The compiler won't do two implicit casts by itself, so you must do one explicit cast and then the compiler will figure out the second one.
The problem is that with implicit casts, you must either cast to or from the type you declare the cast in, and you cannot inherit from sealed classes like 'int'.
So, it is not elegant at all. Extension methods are probably more elegant.
If you declare the class below, you can then do things like:
        byte[] y = (Qwerty)3;
        int x = (Qwerty) y;

public class Qwerty
{
    private int _x;

    public static implicit operator byte[](Qwerty rhs)
    {
        return BitConverter.GetBytes(rhs._x);
    }

    public static implicit operator int(Qwerty rhs)
    {
        return rhs._x;
    }

    public static implicit operator Qwerty(byte[] rhs)
    {
        return new Qwerty {_x = BitConverter.ToInt32(rhs, 0)};
    }

    public static implicit operator Qwerty(int rhs)
    {
        return new Qwerty {_x = rhs};
    }
}

A: you could create extension methods to clean up the calling code a little bit - so you'd end up with:
 int i = 10;
 float a = 34.5F;
 byte[] arr;

 arr = i.ToByteArray();
 arr = a.ToByteArray();

The code for the extension methods would be something like:
public static class ExtensionMethods
    {
        public static byte[] ToByteArray(this int i)
        {
            return BitConverter.GetBytes(i);
        }

        public static byte[] ToByteArray(this float a)
        {
            return BitConverter.GetBytes(a);
        }
    }


text:
Q: Custom Preview Template for Dropzone JS I created a form with the dropzone, but I'm having issues passing the files to the server. I created a custom preview template, similar to the one on the bootstrap demo, but when I click on submit on my form, the files are not being passed to the server. Any help would be appreciated. Below is the code.
 <form action="<?php the_permalink(); ?>" method="post" class="dropzone" id="my-awesome-dropzone" enctype="multipart/form-data">

<input type="text" class="dzinput" placeholder="Type Caption" style="font-style:italic;" />

✔

✘

Or use the basic uploader

      Title*

      <input type="text" name="exampletitle" id="exampletitle" class="fullwidth" required>

<input type="submit" class="btn btn-primary mypanoramabtn" style="background-color:#3ebede" value="Publish" id="submitter"/>
 </form>

My Javascript:
//getting thumbnail template
  var previewNode = document.querySelector("#template");
  previewNode.id = "";
  var previewTemplate = previewNode.parentNode.innerHTML;
  previewNode.parentNode.removeChild(previewNode);

 //script to handle dropzone
  jQuery("#my-awesome-dropzone").dropzone = { // The camelized version of the ID of the form element

  // The configuration we've talked about above
  autoProcessQueue: false,
  uploadMultiple: true,
  thumbnailWidth: 180,
  thumbnailHeight: 120,
  parallelUploads: 100,
  maxFiles: 100,
  previewTemplate: previewTemplate,
  previewsContainer: "#dropzoner2",

  // The setting up of the dropzone
  init: function() {
    this.on("addedfile", function(file) { document.getElementById("dropzoner2").style.background = "none";});  //will remove background after file added
    var myDropzone = this;

    // First change the button to actually tell Dropzone to process the queue.
    this.element.querySelector("input[type=submit]").addEventListener("click", function(e) {
      // Make sure that the form isn't actually being sent.
      e.preventDefault();
      e.stopPropagation();
      myDropzone.processQueue();
    });

    // Listen to the sendingmultiple event. In this case, it's the sendingmultiple event instead
    // of the sending event because uploadMultiple is set to true.
    this.on("sendingmultiple", function() {
      // Gets triggered when the form is actually being sent.
      // Hide the success button or the complete form.

    });
    this.on("successmultiple", function(files, response) {
      // Gets triggered when the files have successfully been sent.
      // Redirect user or notify of success.
    });
    this.on("errormultiple", function(files, response) {
      // Gets triggered when there was an error sending the files.
      // Maybe show form again, and notify user of error
    });
  }

}

I've tried the demos on the wiki and a few others on stackoverflow, but have been unable to get this to work. Right now when I drag and drop my images, I do see the thumbnail in my template, but when I click submit, the images are not passed to the server for me to handle. ANY help would be appreciated.


text:
Q: JavaScript set bits from the left I have a number, for example 128. Its bit representation is 10000000.
I want to set the 3rd bit from the left to have 10100000 (160).
I thought that I could do this with:
var foo = 128;
foo = foo | 1 << 2;

But this gives me 132 or 10000100. It set the 3rd from the right!
How to set it from the left to 0 or to 1?

A: Try this. >> will do work from right side shifting
var foo = 128;
foo = foo | foo >> 2;

Refrence for Bitwise operators

A: This worked:
var foo = 128;
foo = foo | foo >> 2

But what if you want to turn it on and off?
var foo = 128;
var mask = foo >> 2;

// Flick the bit on
foo = foo | mask;
// foo now equals 160

// Set the bit back to 0
foo = foo & ~mask;
// foo equals 128 again

A:

function transformBits(bits, order, target) {
  var bitStr = bits
    .toString(2)
    .split('')
    .map(function(value, index) {
      return index == (order - 1) ? target : value;
    })
    .join('');

  return parseInt(bitStr, 2);
}

document.writeln(transformBits(128, 3, 1));
document.writeln(transformBits(128, 3, 0));


text:
Q: Label in asp.net(vb.net) does not display after click button I have a label which will display if the button submit already enter, how about my label does not display even though have make it visible = true.
This is the asp.net:
 <asp:Label ID="lblReportIsSaving" runat="server" Visible="False" >Report Is Saving In Progress</asp:Label>

 <asp:Button ID="btnRegister" runat="server" Height="22px" Text="Enter" Width="100px" />

This my vb.net, for this matter I would like to display the label first before the 'Save & Update Successful' pop up:
Protected Sub btnRegister_Click(sender As Object, e As EventArgs) Handles btnRegister.Click

        lblReportIsSaving.Visible = True

    Dim intSaveProject, intLastInsertID, intCompanyID As Integer

    strErrMessage = ""

    Try

        lblReportIsSaving.Visible = True

        _strTarget = Page.ResolveClientUrl("test.aspx")
        strPopUpScript = "<script type=""text/javascript"">"
        strPopUpScript = strPopUpScript + "window.location.replace('" & _strTarget & "');"
        strPopUpScript = strPopUpScript + "</script>"

        intSaveProject = fnSaveIntoProject(_strErrMessage)
        lblReportIsSaving.Visible = True

        intLastInsertID = _objCommonData.fnGetLastInsertUserID()

        If intSaveProject = 1 Then
            StringBusinessObject.Web.baseClass.fnAlert(Me.Page, "Save & Update Successful.")
            ClientScript.RegisterClientScriptBlock(Me.GetType(), "PopupScript", strPopUpScript)
        Else
            StringBusinessObject.Web.baseClass.fnAlert(Me.Page, "Save & Update Unsuccessful. " & strErrMessage)
        End If

        'btnRegister.Enabled = True

    Catch ex As Exception
        StringBusinessObject.Web.baseClass.fnAlert(Me.Page, ex.Message.ToString)
    End Try

End Sub

Can someone help me on this? I just want to make the label visible before the pop up comes out.


text:
Q: Read filenames from CSV and then copy the files to different directory I have been able to write a batch file to find files and put the file paths into a CSV. I haven't been able to figure out how to read the file locations from the CSV and then move the files to a different storage device with the same folder structure using python.  This is what I'd like to do.
I wish I had some code to show you but none of it has worked.

A: Adding to Daniel's post, since he did warn he hadn't tested it :), I think you'll need to make a couple small changes. Basically, I think the issue in the suggested code is that filename is assumed to be the full path. But then that creates a problem when you get to the os.path.join command for new_filename because you're adding a new path to a full path and name.
I would suggest including a filepath and filename in your csv to make the code run. The changes appear to work when I testd it, although I didn't run as a function (and I used print() statements for Python 3.4 syntax):
with open(csv_file, 'rb') as f:
    reader = csv.reader(f)
    for row in reader:
      # Assuming the columns in the CSV file we want are the first two  // Changed
      filename = row[0]
      filepath = row[1]   #Changed

     '''Changed: I skipped over this next part, didn't need it, but should be
     easy enough to figure out
     if filename.startswith(existing_path_prefix):
       filename = filename[len(existing_path_prefix):]
     '''

     new_filename = os.path.join(new_path_prefix, filename)

     print ('Copying %s to %s...' % filepath, new_filename)  #Changed
     shutil.copy(filepath, new_filename)   #Changed
     print 'done.'
print 'All done!'

A: Here's a quick and dirty solution. (I haven't tested it yet, YMMV!)
import csv
import os
import shutil
import sys

def main(argv):
  # TODO: this should do some error checking or maybe use optparse
  csv_file, existing_path_prefix, new_path_prefix = argv[1:]

  with open(csv_file, 'rb') as f:
    reader = csv.reader(f)
    for row in reader:
      # Assuming the column in the CSV file we want is the first one
      filename = row[0]

      if filename.startswith(existing_path_prefix):
        filename = filename[len(existing_path_prefix):]

      new_filename = os.path.join(new_path_prefix, filename)

      print ('Copying %s to %s...' % filename, new_filename),
      shutil.copy(filename, new_filename)
      print 'done.'
  print 'All done!'

if __name__ == '__main__':
  main(sys.argv)


text:
Q: redux-saga why do you need a yield next to the put? I have the following saga
export function* login(userName, password) {
  yield put({ type: 'LOGIN_DONE', status: 'success', userName: 'test' });

  // Redirect to the landing page
  yield put(push('/location'));
}

I'm confused about the following
if I do not put the yield before the first put the action does not get dispatched.  Is this the expected behavior and if so why?  I assumed that having a yield next to the final put should be enough, but this only seems to dispatch only the second action
thanks

A: Generator function have the ability to suspend its process until subsequent generator functions are terminated. This is achieved by the use of the yield keyword:

The middleware then executes the yielded Effect as specified by the
  Effects API. Meanwhile, the Generator will be suspended until the
  effect execution terminates. Upon receiving the result of the
  execution, the middleware calls next(result) on the Generator passing
  it the retrieved result as an argument. This process is repeated until
  the Generator terminates normally or by throwing some error.

So in your case the action might trigger another sagas which might be needed to finish their work before moving on to the next yield. If you wont place that yield, this might cause a side effect where subsequent generator functions are running asynchronously and the outcome wouldn't be as expected.


text:
Q: Set service keyboard shortcut and have change take effect programtically I have the following script to set a services shortcut:
set serviceName to "(null) - VimAnywhere - runWorkflowAsService"
set libPrefPath to POSIX path of (path to preferences folder from user domain as text)
set plistFile to "pbs.plist"
set plistPath to libPrefPath & plistFile as text
set mainPropertyItem to "NSServicesStatus"
set keyBindingKey to "key_equivalent"
set keyBinding to "^@v"

tell application "System Events"
  set gp to (get property list item serviceName of property list item mainPropertyItem of property list file plistPath)
  tell gp
    set value of property list item keyBindingKey to keyBinding
  end tell
end tell

do shell script "defaults read > /dev/null"

This sets a keyboard shortcut for a service I have defined in the appropriated property list and it even displays properly when viewing in System Preferences. The problem is, the change doesn't seem to take effect. Invoking the keyboard shortcut has no effect.
How can I set this shortcut and have it take effect immediately (completely through shell/applescript)?

A: The changes made by the AppleScript are applied for me after I quit and reopen applications. Same for this command:
/usr/libexec/PlistBuddy -c 'Delete NSServicesStatus:"(null) - VimAnywhere - runWorkflowAsService"' ~/Library/Preferences/pbs.plist 2>/dev/null;defaults write pbs NSServicesStatus -dict-add '"(null) - VimAnywhere - runWorkflowAsService"' '{key_equivalent = "~@v";}'

I don't know any way to apply the changes without reopening applications. Running /System/Library/CoreServices/pbs -flush or terminating pbs doesn't seem to work.


text:
Q: Marshalling hashmap with Jackson to XML - wrong structure I have a Hashmap<String, List<Object>> and I want to marshal the map with Jackson. It's working with JSON perfectly and looks like this:
{
    "entriesByTable": {
        "Karlsruhe": [
            {
                "counts": 126,
                "hashTag": "#Karlsruhe"
            },
            {
                "counts": 26,
                "hashTag": "#jobs"
            },
            {
                "counts": 3,
                "hashTag": "#etka16"
            }, ...

But when it comes to XML my structure looks like this:
<?xml version="1.0"?>
<Database>
  <entriesByTable>
    <Karlsruhe>
      <hashTag>#Karlsruhe</hashTag>
      <counts>127</counts>
    </Karlsruhe>
    <Karlsruhe>
      <hashTag>#jobs</hashTag>
      <counts>27</counts>
    </Karlsruhe>
    <Karlsruhe>
      <hashTag>#etka16</hashTag>
      <counts>3</counts>
    </Karlsruhe> ...

But I want/need the same Json-strucutre:
<Database>
 <entriesByTable> (mapname)
  <Karlsruhe>     (key)
   <entries>      (value (list))
    <entry>
     <counts>126</counts>
     <hashTag>#Karlsruhe</hashtag>
    </entry>
   </entries>
  </Karlsruhe>
 </entriesByTable>
</Database>

My class:
@JacksonXmlRootElement
public class Database {

    private static String DATABASE_LOCATION;

    @JsonProperty
    private Map<String, List<DatabankEntry>> entriesByTable = new HashMap<>(); ...

Second class:
@JacksonXmlRootElement
public class DatabankEntry implements Comparable<DatabankEntry> {

    @JsonIgnore
    private String tableName;

    @JacksonXmlProperty
    private String hashTag;
    @JacksonXmlProperty
    private int counts;

Would be awesome if someone has an idea. Maybe I made a mistake with the annotations?

A: Ok, I handled the problem by myself. I created a new class which contains a list of entries and annotated the listobject.
@NoArgsConstructor
public class DatabaseEntries {

    @JacksonXmlProperty(localName="Entry")
    @JacksonXmlElementWrapper(localName="Entries")
    @JsonProperty
    private List<DatabaseEntry> databaseEntries = new LinkedList<>();

    public int size(){
        return databaseEntries.size();
    }

    @JsonIgnore
    public List<DatabaseEntry> getAllEntries(){
        Collections.sort(databaseEntries);
        return databaseEntries;
    }

    public void add(DatabaseEntry databaseEntry){
        databaseEntries.add(databaseEntry)  ;
        }

}

My Hashmap looks like this now Hashmap<String,Object>
@JsonProperty
@JacksonXmlProperty(localName = "EntriesByTable")
private Map<String, DatabaseEntries> entriesByTable = new HashMap<>();

and my XML:
<?xml version="1.0"?>
<Database>
  <EntriesByTable>
    <Karlsruhe>
      <Entries>
        <Entry>
          <HashTag>#Karlsruhe</HashTag>
          <Counts>700</Counts>
        </Entry>
        <Entry>
          <HashTag>#Feuerwehr</HashTag>
          <Counts>114</Counts>
        </Entry>
....

JSON:
{
    "entriesByTable": {
        "Karlsruhe": {
            "databaseEntries": [
                {
                    "counts": 700,
                    "hashTag": "#Karlsruhe"
                },
                {
                    "counts": 114,
                    "hashTag": "#Feuerwehr"
                },


text:
Q: PostgresSQL \d command tells about not existing table When I type \l into psql I got
                                                 List of databases
   Name    |  Owner   | Encoding |          Collate           |           Ctype            |   Access privileges
-----------+----------+----------+----------------------------+----------------------------+-----------------------
 postgres  | postgres | UTF8     | English_United States.1251 | English_United States.1251 |
 template0 | postgres | UTF8     | English_United States.1251 | English_United States.1251 | =c/postgres          +
           |          |          |                            |                            | postgres=CTc/postgres
 template1 | postgres | UTF8     | English_United States.1251 | English_United States.1251 | =c/postgres          +
           |          |          |                            |                            | postgres=CTc/postgres

So here I have 1 database names postgres, but if I type \d I got
        List of relations
 Schema | Name | Type  |  Owner
--------+------+-------+----------
 public | db1  | table | postgres
(1 row)

In pgAdmin I can see 1 database named "postgres", so why \d tells me about db1 database? (I created it earlier and dropped)

A: From the psql help:
Informational
  (options: S = show system objects, + = additional detail)
  \d[S+]                 list tables, views, and sequences

And as your output shows, db1 is a table, not a database...
DROP TABLE db1; will get rid of it.


text:
Q: "Fell onto" x "Fell on" What's the difference? What's the difference between these two sentences? Are they correct?

The water drop fell onto my head
  The water drop fell on my head

Could anyone explain me difference between these terms?

A: In some cases, especially ones involving inanimate objects, the two prepositional phrases are interchangeable; your example sentences are identical in meaning.
In other situations, particularly involving people or animals, there is a difference:  onto implies motion from some other position, while on implies only a current location.  So "John fell onto the roof" means that John was somewhere above the roof, fell, and landed on the roof.  (At this point he could be standing, kneeling, or lying down; it depends on how far he fell and how much control he was able to exercise during the landing.)  "John fell on the roof", however, means that John was already on the roof in a standing or walking position, fell, and is now lying down.


text:
Q: Silverlight Applications to Access SharePoint 2010 Data is not loading I am trying to load Silverlight DataGrid Control in my SharePoint 2010, I have followed this code example linl. http://msdn.microsoft.com/en-us/library/ff728647.aspx#Y1200.
I have just replaced this codelines(in MainPage() method):
List Projects = context.Web.Lists.GetByTitle("Calendar");
string camlQueryXml ="asd"+ ""+ "";
Output Error:Could not download the Silverlight application or the Silverlight Plugin did not load.

A: Check this link
http://msdn.microsoft.com/en-us/library/cc265156(v=vs.95).aspx
The silverlight version selected while creating the application should match with the version of plugin installed.


text:
Q: Sum all values in row using Index/Match I'm trying to build (what I thought to be a simple) Excel formula that matches a line item from one sheet with another line item from a second sheet and sums up all values in that matched row.

Any help is appreciated

A: In Sheet1, cell B3 enter:
=SUM(INDIRECT("Sheet2!"&ADDRESS(MATCH(A3,Sheet2!A:A,0),2)&":" & ADDRESS(MATCH(A3,Sheet2!A:A,0),16384)))

There is probably a better formula than this using INDEX() rather than INDIRECT()


text:
Q: New Win 8.1 can't share files to Ubuntu 13.10 Ubuntu cannot access the shared resources on the Windows 8.1 machine.
I have gotten the share to work from Ubuntu to win 8.1 but the Ubuntu system does not seem to want to allow me to sign-on to the win 8.1 system. I have enabled networking on the win machine (it is using Home Group as the net/domain name so I tried changing the SAMBA config file to match it is giving/suggesting the user name of tom for me which is my Ubuntu name and Windows provides an arbitrary password, but it won't take...
Ubuntu seems to see the Win 8.1 machine fine (presents it in the network browser,, but I just can't seem to get authorised? I'm using Uid=Tom Domain=HOMEGROUP and the win 8.1 supplied password.. I have set the win 8.1 machine to share all.. pic docs printers etc...
The referenced question in the comment below is pointing out issues sharing from Ubuntu not accessing a Windows share.... or how to find the D*** windows settings that are screwing things up.. So I MAY be a duplicate but not of that one!

A: Not exactly sure.. I did update the share permission on folders..Specifically the Documents folder... but I think that perhaps what did it was that I found that I needed to use my Win User id (tom) not the full one user id which was Tom,,,@outlook.com....and the full Windows password, same as my outlook.com password... not the generated one that Windows instructions said....
Not user friendly but worked, that is MS for you...


text:
Q: SVD on a non-square matrix I'm using numpy.linalg.svd() to get the singular value decomposition of matrices. But I can't get back from the decomposition to the original matrix for a non-square matrix.
For example, for a square matrix :
import numpy as np
n=5
# make a random (n,n) matrix
A= np.reshape( np.random.random_integers(0, 9, size= n**2), (n, n))
#SVD
U,S,Vh = np.linalg.svd(A)
# to get A from the SVD back
A_svd = U@np.diag(S)@Vh
#check if its the same
print(np.allclose(A,A_svd))

I get :  >>> True
Now for a non-square matrix, for example A of shape (m,n), then the shape U is (m,m), the shape V is (n,n) and S is a diagonal matrix of (of length k), with k = min(m,n). For example :
import numpy as np
n=5
m= 8
# make a random (m,n) matrix
A= np.reshape( np.random.random_integers(0, 9, size= m*n), (m, n))
#SVD
U,S,Vh = np.linalg.svd(A)

With the following shapes :
>>> U.shape
(8, 8)
>>> S.shape
(5,)
>>> Vh.shape
(5, 5)

I dont know how to get the matrix A back if I have the svd decomposition though.
I cant do a simple multiplication because of the shapes difference.  U@np.diag(S)@Vh  or  np.matmul(U,S,Vh) or with np.dot.
So I tried to reshape S and fill it with zeroes.
S_m = np.diag(S)
S_m.resize((U.shape[1], Vh.shape[0]))
#check if its the same
print(np.allclose(A,U @S_m@ Vh))

>>> False

A: I found an answer here, using diagsvd from scipy.linalg.
import scipy.linalg as la
A_svd = U@la.diagsvd(S,*A.shape)@Vh


text:
Q: Background Video Width and Height CSS I'm making a website with a video on the background. I'm using 80vh (viewport height), but when I press f12, the video background height went smaller, how to fix it? Should I change it to px or %?
This is my code
HTML:

        <video autoplay muted loop>
            <source src="frontend/media/header-background.mp4" type="">
        </video>

FASHION

FESTIVAL

IS HERE

SCSS:
.head-banner {
    width: 100%;
    height: 80vh;
    box-sizing: border-box;

    .head-background {
        position: relative;
        video {
            width: 100%;
            height: 80vh;
            object-fit: cover;
        }
    }

    .head-content {
        position: absolute;
        color: whitesmoke;
        z-index: 1;
        top: 0;
        left: 5%;
    }

    h1 {
        font-family: 'Montserrat', sans-serif;
        font-size: 72px;
        font-weight: 700;
    }

    .hoks {
        margin-top: -20px;
    }
}

Thanks.


text:
Q: Spring boot application Logging We have a spring boot application and in the application.properties we set the log file location to be written to /var/log/onbase.log
But whenever the server is started there is one more log that is written to var/onbaseAPP.log (this log is filling up the memory on the box and the server is getting hung up)
We don't have any were in the code to create a onbaseApp.log not sure how it is getting created
please help. thanks in advance.

A: if you use Log4j or Log4j2, you'll need to change your dependencies to include the appropriate starter for the logging implementation you want to use and to exclude Logback.
For Maven builds, you can exclude Logback by excluding the default logging starter transitively resolved by the root starter dependency:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-logging</artifactId>
        </exclusion>
    </exclusions>
</dependency>

In Gradle, it's easiest to place the exclusion under the configurations section:
configurations {
    all*.exclude group:'org.springframework.boot',
    module:'spring-boot-starter-logging'
}

With the default logging starter excluded, you can now include the starter for the logging
implementation you'd rather use. With a Maven build you can add Log4j like this:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-log4j</artifactId>
</dependency>

In a Gradle build you can add Log4j like this:
compile("org.springframework.boot:spring-boot-starter-log4j")

your application.properties like this :
logging.path=/var/log/
logging.file=onbase.log
#logging.level.root=WARN
#logging.level.root.org.springframework.security=DEBUG

Source: Spring Boot in action Craig Walls


text:
Q: Grid movement in requestanimationFrame(loop), Continious button press I have these two pieces of code that work however when pressing down a key it does multiple instances instead of once. How can I fix this issue?
i've tried multiple places with setTimeout()
eventually came to the conclusion that keyup event can be replaced by just inserting keys.a.pressed = false after charX--
Is there a better solution?

function animate(){
    requestAnimationFrame(animate)
    b.clearRect(-gameWidth / 2, 0, gameWidth, gameHeight)

    boundaries.forEach(boundary => {
        boundary.draw()
        // console.log(boundary.position.x, boundary.position.y)
        // console.log('boundary', boundary.position.x, boundary.position.y)
    })

    floors.forEach(floor => {
        floor.draw()
    })

        if (keys.w.pressed && lastKey === 'w' && canMove(charX, charY - 1)) {
            console.log('w', charY)
            charY--;
        // drawCharacter(charX, charY);
    }
    else if (keys.a.pressed && lastKey === 'a' && canMove(charX - 1, charY)) {
        charX--;
        // drawCharacter(charX, charY);
    }
    else if (keys.d.pressed && lastKey === 'd' && canMove(charX + 1, charY)) {
        charX++;
        // drawCharacter(charX, charY);
    }
    else if (keys.s.pressed && lastKey === 's' && canMove(charX, charY + 1)) {
        charY++;
        // drawCharacter(charX, charY);
    }

    player.update(charX, charY)
    // console.log('player',player.position.x, player.position.y)

}
animate()

addEventListener ('keydown', ({key}) =>{
    switch (key) {
        case 'a': // left
            keys.a.pressed = true
            lastKey = 'a'
            break;
        case 'w': // up
            keys.w.pressed = true
            lastKey = 'w'
            break


text:
Q: Setting an environment variable before a command in Bash is not working for the second command in a pipe In a given shell, normally I'd set a variable or variables and then run a command. Recently I learned about the concept of prepending a variable definition to a command:
FOO=bar somecommand someargs

This works... kind of. It doesn't work when you're changing a LC_* variable (which seems to affect the command, but not its arguments, for example, [a-z] char ranges) or when piping output to another command thusly:
FOO=bar somecommand someargs | somecommand2  # somecommand2 is unaware of FOO

I can prepend somecommand2 with FOO=bar as well, which works, but which adds unwanted duplication, and it doesn't help with arguments that are interpreted depending on the variable (for example, [a-z]).
So, what's a good way to do this on a single line?
I'm thinking something on the order of:
FOO=bar (somecommand someargs | somecommand2)  # Doesn't actually work

I got lots of good answers! The goal is to keep this a one-liner, preferably without using export. The method using a call to Bash was best overall, though the parenthetical version with export in it was a little more compact. The method of using redirection rather than a pipe is interesting as well.

A: Use env.
For example, env FOO=BAR command. Note that the environment variables will be restored/unchanged again when command finishes executing.
Just be careful about about shell substitution happening, i.e. if you want to reference $FOO explicitly on the same command line, you may need to escape it so that your shell interpreter doesn't perform the substitution before it runs env.
$ export FOO=BAR
$ env FOO=FUBAR bash -c 'echo $FOO'
FUBAR
$ echo $FOO
BAR

A: You can also use eval:
FOO=bar eval 'somecommand someargs | somecommand2'

Since this answer with eval doesn't seem to please everyone, let me clarify something: when used as written, with the single quotes, it is perfectly safe. It is good as it will not launch an external process (like the accepted answer) nor will it execute the commands in an extra subshell (like the other answer).
As we get a few regular views, it's probably good to give an alternative to eval that will please everyone, and has all the benefits (and perhaps even more!) of this quick eval "trick".  Just use a function! Define a function with all your commands:
mypipe() {
    somecommand someargs | somecommand2
}

and execute it with your environment variables like this:
FOO=bar mypipe

A: FOO=bar bash -c 'somecommand someargs | somecommand2'

A: How about exporting the variable, but only inside the subshell?:
(export FOO=bar && somecommand someargs | somecommand2)

Keith has a point, to unconditionally execute the commands, do this:
(export FOO=bar; somecommand someargs | somecommand2)

A:
A simple approach is to make use of ;

For example:
ENV=prod; ansible-playbook -i inventories/$ENV --extra-vars "env=$ENV"  deauthorize_users.yml --check

command1; command2 executes command2 after executing command1, sequentially. It does not matter whether the commands were successful or not.

A: Use a shell script:
#!/bin/bash
# myscript
FOO=bar
somecommand someargs | somecommand2

> ./myscript


text:
Q: Correctly Handling Variable Constructor Arguments I have a user class with a constructor
public class User{
    public User(string name, string role, IWebElement submitButton)
    {
         this.Name = name;
         this.Role = role;
         this.SubmitButton = submitButton;
    }

    public string Name { get; private set; }
    public string Role { get; private set; }
    public IWebElement SubmitButton { get; private set; }
}

This class is a representation of a table of web elements from a selenium test.
var rowTds = rows[i].FindElements(By.TagName("td"));
User user;

if (rowTds.Count > 0)
{
    userRow = new UserRow(rowTds[0].Text, rowTds[1].Text, rowTds[2]);
}

My goal is to write the above code in such a way that if the rowTds change my test will not break. Would a better solution be to loop around the elements adding them to an array and pass a different constructor an array that handles the variable array and uses the first 3 elements for the constructor?


text:
Q: Image preview no longer working after upgrade to Ubuntu 22.04 Need help with being able to restore image preview function when looking through file folders. It's no longer an option in Ubuntu 22.04 and was able to install Sushi as a work around so when directly exploring files in 22.04 you can hit the space bar to preview images. But when uploading images in Chrome and Firefox Sushi doesn't work. Image preview used to work fine in both browsers before upgrade to 22.04
Please try to be helpful rather than deleting me again! My question has been deleted several times now and I'm not trying to break any rules, just trying to get ubuntu to work correctly again and deleting a simple request for help is not ok.


text:
Q: c# chart change max and min values on the x axis Can someone tell me how to change the min and max values on the x axis on a C# chart?  I want to go from 0 to 13, but it goes from -1 to 14 right now.

A: You might try myChart.ChartAreas[0].AxisX.RoundAxisValues(). It is on by default for the Y axis and I find it generally works better for the X Axis as well.

A: If you are using System.Windows.Forms.DataVizualisation.Charting you can set the Axis range by manipulating the chart's ChartAreas property. So something like
myChart.ChartAreas[0].AxisX.Maximum = 13;
myChart.ChartAreas[0].AxisX.Minimum = 0;

A: This will work better :
myChart.ChartAreas[0].AxisX.IsMarginVisible = false;

A: New Chart().SetYAxis("GPA",0,4);
If You using The chart Class
you could set the Y or X axis using the SetYAxis Method

A: *

*chart1.ChartAreas[0].AxisX.Minimum = 0;

*chart1.ChartAreas[0].AxisX.Maximum = 10;

*chart1.ChartAreas[0].AxisY.Minimum = -5;

*chart1.ChartAreas[0].AxisY.Maximum = 5;


text:
Q: Why is exhaust stroke isochoric in otto cycle? Please help me clarify this simple concept. In otto cycle, after the power stroke, the gas expands adiabatically and during the exhaust stroke why is the volume of the gas constant? Doesn't the volume of the gas change after the exhaust valve is open? Is the volume considered constant because the temperature of the gas drops quickly at the end of the power stroke? If so, how does the temperature of the gas drop so quickly in such small time interval? I am confused, please help me. Thank you!

A:
Doesn't the volume of the gas change after the exhaust valve is open?

Yes it does, for the real Otto cycle which is an irreversible open system. But it does not for the reversible closed system model of the cycle.
The ideal reversible model of the Otto cycle does not include the intake or exhaust strokes because it is a closed thermodynamic system model of the cycle. Instead of thermal energy being lost along with mass in the exhaust stroke for an open system, it is shown as heat rejected at constant volume for the reversible closed system model. See the PV diagram of the ideal reversible cycle.
For reference I have included arrows to represent the intake and exhaust strokes of a real open system cycle which are not normally shown for the reversible closed system model. This has no impact on the net work done, since there is no net work done for the combination of the exhaust and intake strokes both of which occur at the same constant external pressure and the same increase and decrease in volume.  All the thermal energy lost during the real exhaust stroke is accounted for as heat rejected at constant volume for the reversible cycle model.
Hope this helps.


text:
Q: Storing cached files so they are accessible by more than one server I want to start using multiple front-end Apache servers for my website.
At the moment I store various HTML files in a caching directory, e.g. "/htmlcache/homepage.html"
Obviously I don't want to re-cache these files on a per-server basis, I'd rather have one central store. How is this usually done?
The options as I see it are:

*

*Database (MySQL) - extra load - should I be storing larrge .html files?

*Memcache - should this be used for large .html files?

*Some kind of accessible shared disk - no idea how this would work

Latency is key for me. The disk read opperation is working very nicely for me at the moment.
As an additional complication, I'll also need to keep my PHP session data in a central location too.
This thread: https://stackoverflow.com/questions/580671/configure-session-to-work-on-applications-that-are-deployed-over-multiple-server recommends using session_set_save_handler to store the session data in a shared database.
How are you overcoming this issue?

A: memcached can store "large" HTML files (for suitably small values of large) - Varnish (as Michael Mior mentioned) or Squid are other options.  Out of those three I would lean toward Varnish (Squid is overkill for most small environments, and I believe Varnish scales better through medium/large environments: Last time I checked Squid wasn't capable of distributed cacheing).
You will need to test any of these solutions before you deploy them, obviously.
Re: the PHP session part - session_mysql is one solution here.  Writing your own custom session handler in PHP is another.  I would suggest one of the PECL extensions personally as they tend to be marginally more efficient/faster than PHP code.


text:
Q: cpp-ffmpeg how to resolve deprecated warning? I am working with FFmpeg Lib, and I get a warning, my code as below:
if ( avformat_find_stream_info( pFormatCtx, NULL ) < 0 ) {
        std::cout << "Get Stream Information Error 13" << std::endl;
        avformat_close_input( &pFormatCtx );
        pFormatCtx = NULL;
        return -13;
 }
av_dump_format( pFormatCtx, 0, filenameSrc, 0 );

for ( unsigned int i = 0; i < pFormatCtx->nb_streams; i++ ) {
        if (pFormatCtx->streams[i]->codec->coder_type == AVMEDIA_TYPE_VIDEO) {
            video_stream_index = i;
            break;
        }
 }

And I meet the warning at line: pFormatCtx->streams[i]->codec->coder_type == AVMEDIA_TYPE_VIDEO
Warning: AVCodecContext::coder_type' is deprecated (declared at /usr/local/include/libavcodec/avcodec.h:2815) [-Wdeprecated-declarations]
I dont understand what does this warning mean and how to resolve it.
Anyone can help me !
Thank

A: Try to use codec_type from codecpar:
if (pFormatCtx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
        video_stream_index = i;

A: As you can see in your warning message and also you can see in ffmpeg docs using AVCodecContext::coder_type directly is deprecated.
But in docs you can see what else you can do, use encoder private options instead.
You create your AVCodecContext base on some AVCodec. Then you can just use AVCodec::type. Or you can get it again from AVCodecContext like this :
AVCodec *codec = avcodec_find_encoder(codec_context->codec_id);
int coder_type = codec->type;

In your case you can change your code like this :
for(unsigned int i = 0; i < pFormatCtx->nb_streams; i++)
{
    if(avcodec_find_encoder(pFormatCtx->streams[i]->codec->codec_id)->type == AVMEDIA_TYPE_VIDEO)
    {
        video_stream_index = i;
        break;
    }
}

A: Please disable Visual Studio's SDL checks.
In Project / Properties / C/C++ / General / SDL checks,
change from Yes(/sdl) to No(/sdl-).
This is tested in Visual Studio 2017.


text:
Q: Can't Pass HTML Markup Through AJAX to PHP I have my html form sending data through AJAX to PHP. the form data contains a little HTML markup which I want to send to my PHP server.
My Form data is set up like so:
<form id="mail-formData">
    <input type="hidden" name="a" value="send-custom-mail">
    <input type="hidden" name="uid" id="cm-uid">
    <input type="text" class="form-control" id="cm-email2" name="to">
    <input type="text" class="form-control" name="message-subject" required>
    <textarea class="form-control" name="message-body" required></textarea>
    <button type="submit" class="btn btn-lg btn-primary sendMail">SEND MAIL</button>
</form>

NOTE: the content in my message-body contains markups like  and most especially

My AJAX i well set up like so:
$.ajax({
    url: "send-mail.php",
    type: "POST",
    data: $("#mail-formData").serialize(),
    cache: false,
    success:function(response){
        console.log(response);
    }
});

and my send-mail.php is set up like so:
 if (isset($_POST['a'])&&$_POST['a']=='send-custom-mail') {
     die(var_dump($_POST));
 }

NOW,

*

*When I send this request without the html markups in it, it works flawlessly

*when I send with html markups like  witouth the style="" it works.
BUT
Once I introduce style="color:red" it doesn't work. the form submits quite fine but I'm guessing without the data in serialize();
=========UPDATE==========
Here are the screenshots from the response I got.

*

*When sending with markups like  etc:

*When I add markup like :

Kindly note that the response below Image 2 is just the content of the page containing the form.


text:
Q: Jqgrid how to write cell click event I want to write an event when user click on a cell of jqgrid. Is there build in method?
I could not find any event at this link

A: Callbacks and jQuery events are described here. jqGrid register click handler on the body of the grid. Inside of the click handler the callbacks beforeSelectRow and later onCellSelect will be called. In the same way jQuery events jqGridBeforeSelectRow and jqGridCellSelect will be called too.
The callbacks and the events contains e parameter (jQuery Event object) which target property could be used to get all information about the click event if the other parameters of the beforeSelectRow callback (or onCellSelect callback) don't provides already what you need. The old answers: the answer, this one, this one, this one, this one, this one and many other provide you examples of the usage of onCellSelect and beforeSelectRow callbacks.

A: there is a inbuilt event.. you can find it here LINK
onCellSelect: function (rowId, iCol, content, event) {
      //YOUR STUFF
    }

A: We have double click event in jqgrid which can be used like this
ondblClickRow: function (rowId, iRow, iCol, e) { //Your Code  }

A: you can try with this
onSelectRow: function(){
                var row_id = $("#grid_nueva_caja_matriz").getGridParam('selrow');
                jQuery('#grid_nueva_caja_matriz').editRow(row_id, true);
            }

or you can use the differentes events how
ondblClickRow
you can check on the documentation of jqgrid


text:
Q: CSS styling precedence I have two CSS classes:
.thick-green-border {
border-color: green;
border-width: 10px;
border-style: solid;
border-radius:10px;
}

.smaller-image {
width: 100px;
border-radius:30px;
}

Usage in HTML document:

When the image element is assigned both the classes, the rule for the style border-radius described in the class .smaller-image is taking effect, not the radius set inside thick-green-border class. That is the border-radius of the image is becoming 30px, not 10px.
Can anyone please tell me why? I have tried changing the order in which the classes are assigned to the image but the result is the same.

A: Change the order of the classes in the CSS.

.thick-green-border {
  border-color: green;
  border-width: 10px;
  border-style: solid;
  border-radius: 10px;
}
.smaller-image {
  width: 100px;
  border-radius: 30px;
}
.smaller-image2 {
  width: 100px;
  border-radius: 30px;
}
.thick-green-border2 {
  border-color: green;
  border-width: 10px;
  border-style: solid;
  border-radius: 10px;
}

They both have the same hierarchy level, so the latter one will be applied.

A: Is this what you want?

.thick-green-border {
border-color: green;
border-width: 10px;
border-style: solid;
border-radius:10px;
display: inline-block;
}

.smaller-image {
width: 100px;
border-radius:30px;
}


text:
Q: I need help interpreting an expression I have the following formula:

$$\min_{\beta_0,\beta}\sum_{i=1}^n[1-y_if(x_i)]_++\frac1{2C}\lVert \beta\rVert^2$$

What does the bracket with the subscripted plus mean?
I greatly appreciate your help. Thank you.

A: Quite often, $x_+$ indicates $\max\{x,0\}$ and $x_-$ indicates $-\min\{x,0\}=(-x)_+$. Under these conventions $$\lvert x\rvert=x_++x_-\\ x=x_+-x_-$$


text:
Q: how to customize the delimiter in std::getline I was solving attribute parser on hackerRank but I am stuck with delimiter. I want to grab an element from ("any thing"), in this case it will give me (any thing), but when I do this:
while (getline(ob, item, '""')) {//but its be true when i put single one ('"')
        std::cout << item << "\n";
    }

It gives me this error:

E0304 no instance of "getline" matches the argument list

A: As @RetiredNinja said, you can use '\"' as the delimiter. The code may look like this:
#include <iostream>
#include <string>

int main()
{
    std::string str;
    while (std::getline(std::cin, str, '\"'))
        if (!str.empty() && str[0] != '(' && str[0] != ')')
            std::cout << '(' << str << ")\n";
}

You can change the code based on the rules of the problem. Note that the delimiter would give you "(" first, then the actual word and so on. So you'd have to filter the values you're not interested in.


text:
Q: Can the rank of harmonic maps decrease far from the boundary? Let $\mathbb D^n$ be the closed unit disk in $\mathbb R^n$. Let $f:\mathbb D^n \to \mathbb{R}^n$ be a smooth immersion . ($df$ is everywhere invertible). Let $\omega:\mathbb D^n \to \mathbb{R}^n$ be the harmonic map corresponding to the Dirichlet problem imposed by $f$, i.e. $\omega|_{\partial \mathbb D^n}=f|_{\partial \mathbb D^n}$, and each component of $\omega$ is a harmonic function.

Does $\text{rank}(d\omega)\ge n-1 $ everywhere on $\mathbb D^n$?

For every $p \in \partial \mathbb D^n  :\, \, \text{rank}(d\omega_p)\ge \text{rank}\big(d(\omega|_{\partial \mathbb D^n})_p\big)= \text{rank}\big(d(f|_{\partial M})_p\big)=n-1$.
Since the rank does not decrease locally, there is an open neighbourhood of $\partial \mathbb D^n$ where $\text{rank}(d\omega)\ge n-1 $.

Edit: In the particular case of dimension $2$, the question is whether $\omega$ has a critical point ($d\omega=0$).

Let us consider the 2$D$ case more closely: Write $f=(f_1,f_2)$ for $f_i:\mathbb D^2 \to \mathbb R$, and similarly $\omega=(\omega_1,\omega_2)$. Then $df_i \neq 0$ everywhere on $\mathbb D^2$.  However, this fact alone does not imply that $d\omega_i \neq 0$ on $\mathbb D^2$. A counter example is given here:
Set $f_i(x,y)=x-2y^2$. Then $\omega_i(x,y)=x^2-y^2+x-1$, and $d\omega_i=(2x+1,-2y)$ is zero at the point $(-\frac{1}{2},0)$.
Of course, to get a counter-example to the current question, we need $d\omega_1,d\omega_2$ to vanish at the same point simultaneously; However we cannot take $f_1=f_2$, since then $f=(f_1,f_2)$ won't be an immersion. I tried tweaking this construction, e.g. by composing one copy of the $f_i$ with some rotation around $(-\frac{1}{2},0)$, but this got me nowhere.


text:
Q: Автоматическое снятие checkbox через 10 секунд Как на JS сделать автоматическое снятие checkbox с id="1" через 10 секунд после нажатия по нему?
<input type="checkbox" class="btn-check" id="1" autocomplete="off">
Выбрать на 10 секунд

A: В целом, всё просто. Нужно повесить событие по нажатию и если поставили флажок - запустить таймер, который по истечении времени снимет флажок. Если же нажатием флажок сняли, то и таймер нужно остановить.
Вот решение:
<input type="checkbox" class="btn-check" id="cb-1" autocomplete="off">
Выбрать на 10 секунд


text:
Q: How to create kafka topic with partitions in nodejs? I am using kafka-node link api for creating kafka topics. I did not find how to create a kafka topic with partitions.
var kafka = require('kafka-node'),
    Producer = kafka.Producer,
    client = new kafka.Client(),
    producer = new Producer(client);
// Create topics sync
producer.createTopics(['t','t1'], false, function (err, data) {
    console.log(data);
});
// Create topics async
producer.createTopics(['t'], true, function (err, data) {});

producer.createTopics(['t'], function (err, data) {});// Simply omit 2nd arg

how to create kafka topic with partitions in nodejs.

A: From your node.js app execute the shell script $KAFKA_HOME/bin/kafka-topics.sh —create —topic topicname —partitions 8 —replication-factor 1 —zookeeper localhost:2181
Where $KAFKA_HOME is the location where you installed Kafka

A: As documentation describes, this method works only when auto.create.topics.enable is set to true:

This method is used to create topics on the Kafka server. It only works when auto.create.topics.enable, on the Kafka server, is set to true. Our client simply sends a metadata request to the server which will auto create topics. When async is set to false, this method does not return until all topics are created, otherwise it returns immediately.

This means that any operation on unknown topic will lead to its creation with default number of partitions configured by num.partitions parameter.
I'm not sure, but maybe one of the node-rdkafka implementations could allow you to call corresponding librdkafka method to create topic?

A: I am not that sure but I think as per your requirement the code has updated here:- https://github.com/SOHU-Co/kafka-node#createtopicstopics-cb, adding a parameter "replicaAssignment".
  // Optional explicit partition / replica assignment
  // When this property exists, partitions and replicationFactor properties are ignored
  replicaAssignment: [
    {
      partition: 0,
      replicas: [3, 4]
    },
    {
      partition: 1,
      replicas: [2, 1]
    }
  ]

A: The Producer.createTopics takes a partitons option.  See https://www.npmjs.com/package/kafka-node#createtopicstopics-cb
Pass an object, rather than a string
producer.createTopics(['t', 't1'], true, function (err, data) {});

becomes
producer.createTopics(
  [
    { topic: 't', paritions: 5 },
    { topic: 't1', partitions: 23 },
  ],
  true,
  function (err, data) {}
);


text:
Q: ASP.NET Identity make Email/Password token never expires I know this doesn't make a lot of sense, but my client request that the tokens to be made never expires.
I did some research and found out that I can specify the duration for TokenLifespan, so my first thought is to make the duration super long thus making the tokens seem to be "never expire"
var dataProtectionProvider = options.DataProtectionProvider;
        if (dataProtectionProvider != null)
        {
            manager.UserTokenProvider =
                new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"))
                {
                    TokenLifespan = TimeSpan.FromHours(2160)
                };
        }

However, regardless what I set for the TokenLifespan, the token will still expire 3 days later.
I did a test, say 1 day or 2, they work just fine, but for some reasons it cannot get past 3 days. What exactly is happening here?

A: take a look here http://www.codeproject.com/Articles/762428/ASP-NET-MVC-and-Identity-Understanding-the-Basics
You shouldn't make the token persistent you should define that on the login part
AuthenticationManager.SignIn(
            new AuthenticationProperties { IsPersistent = isPersistent },
            userIdentity,
            rememberBrowserIdentity);


text:
Q: Attempt to call a nil value LUA FiveM Coding I am currently coding a special revive script that allows regular players to revive each other if there are no EMS on.
This is the code I have in my "previve-s.lua" (server-sided script):
ESX=nil
Citizen.CreateThread(function()
    while ESX==nil do
        TriggerEvent('esx:getSharedObject',function(obj) ESX=obj end)
        Citizen.Wait(0)
    end
end)

RegisterCommand("previve", function()
    local ped=GetPlayerPed(-1)
    local playerCoords=GetEntityCoords(ped)
    local cplayer,cdistance=GetClosestPlayer()
    local playerCoords2=GetEntityCoords(ped2)
                    if EmsCount==0 and cdistance<10 and IsPedDeadOrDying(cplayer,1) then
                        TaskStartScenarioInPlace(ped,'CODE_HUMAN_MEDIC_TEND_TO_DEAD',0,true)
                        Citizen.Wait(7000)
                        TriggerClientEvent("revive",ped2)
                        ClearPedTasks(ped)

                    elseif EmsCount>0 then
                        Notif("There are EMS on! You cannot revive this player. Contact EMS for help!")

                    elseif cdistance>10 and IsPedDeadOrDying(cplayer,1) then
                        Notif("Get closer to the player.")

                    elseif not IsPedDeadOrDying(cplayer,1) then
                       Notif("The player isn't dead! Why are you even trying?")
                    end
    end)

RegisterNetEvent("revive")
AddEventHandler("revive", function(k)
    local plyCoords = GetEntityCoords(k)
    ResurrectPed(k)
    ClearPedBloodDamage(k)
    SetEntityHealth(k, 200)
    ClearPedTasksImmediately(k)
    SetEntityCoords(k, plyCoords.x, plyCoords.y, plyCoords.z + 1.0, 0, 0, 0, 0)
end)

function GetClosestPlayer()
    local players = GetPlayers()
    local closestDistance = -1
    local closestPlayer = -1
    local ply = GetPlayerPed(-1)
    local plyCoords = GetEntityCoords(ply, 0)

    for index,value in ipairs(players) do
        local target = GetPlayerPed(value)
        if(target ~= ply) then
            local targetCoords = GetEntityCoords(target, 0)
            local distance = Vdist(targetCoords.x,targetCoords.y,targetCoords.z,plyCoords.x,plyCoords.y,plyCoords.z)
            if(closestDistance == -1 or closestDistance > distance) then
                closestPlayer = value
                closestDistance = distance
            end
        end
    end

    return closestPlayer, closestDistance
end

And this is the code I have in the "previve-c.lua":
function Notif(msg)
    SetNotificationTextEntry("STRING")
    AddTextComponentString(msg)
    DrawNotification(true, false)
end

Citizen.CreateThread(function()
    EmsCount=0
    for _, player in ipairs(GetActivePlayers()) do
        Citizen.Wait(5)
        local ped1 = GetPlayerPed(player)
        if ped1.job.name=='ambulance' then
            EmsCount=EmsCount+1
        end
    end
    return EmsCount
end)

The error I am getting from the console when I try to "/previve" is:

[      script:previve] SCRIPT ERROR: @previve/server/previve-s.lua:53:
attempt to call a nil value (global 'Vdist') [      script:previve] >
GetClosestPlayer (@previve/server/previve-s.lua:53) [
script:previve] > ref (@previve/server/previve-s.lua:12)

A: I'm no expert in FiveM but according to the docs there is no Vdist function in the server API. That's a function in the client API
https://docs.fivem.net/natives/?_0x2A488C176D52CCA5
In line 53 you're trying to call a nil value which should be Vdist.


text:
Q: Reading STL files in Flash Has a library been released to read .STL files in AS3? It seems to be a common 3d file and i have yet to find any hope in outputting an .STL file in Stage3d.

A: I've written just the library you were looking for. You can find it at https://github.com/pranavh/AS3STLViewer
It uses Away3D to display the parsed stl file.
Hope you like it.


text:
Q: Top-level build folder in multi-module gradle project I'm playing around with gradle, mostly to explore if its a viable alternative to maven for my builds. I quite like the idea of a more programmatic approach to build configuration, so it's quite promising so far.
However, I do have a couple of minor annoyances I'm trying to wrap my head around. One particular issue is to identify what actually generate the top level build folder in my project, as the top level project doesn't have the java plugin applied.
For example, I got a hierarchy something akin to this:
 /POC
    build.gradle
    settings.gradle
    /subproject1
    /subproject2

Now, in my top-level configuration, I'm applying the java plugin only to the subprojects, and I can see from the output of gradle build, that indeed the build steps are only executed on the subprojects.
However, I still get a build folder in the top level directory, in addition to the build folders in the subprojects.
This isn't a huge deal, but, it tickles my OCD, I want to know why it pops up there. I feel like I'm missing something important in respect to how gradles build lifecycle works.


text:
Q: Improve test questions shown during review of suggested edits I review edits for some time now ( I got the steward badge ). I often wondered if I was too severely judging the edits and rejecting too many, or if on the other hand I let pass mediocre edits.
The test questions helped me alot to get right feeling. But I also find that there's a big potential for improvement.
Representability
Most of the test edits that needed to be rejected were examples of vandalism with some nonsense words randomly inserted, while in the real edits I don't remember one such edit.
On the other hand there are missing examples of common invalid edits like introducing wrong formatting or errors in the code, arbitrary tag changes, etc, that should also be rejected.
I don't know how these fake edits are selected or generated, but in my opinion there is a vast field for improvement.
Follow up and sanctions
I saw discussions about reviewers that mechanically approve all questions. I think that the test edits are a good means to educate those reviewers, especially if they were better sampled. Also it would be good for this purpose if a repeated incorrect review of the test questions would result in a sanction, like : only be allowed to review 10 edits per day instead of 20, until some test questions are answered correctly.
Such a sanction would have more effect for educating superficial reviewers than the "Stop and listen" message only.
What do you think about these improvements ?


text:
Q: Delete duplicates after coding response on one variable R Overall aim: Delete duplicates after coding response on one variable
I have a dataset where an individual can select multiple options on a variable [e.g. Country Code]. I want to delete the duplicates but first I want to make sure that I capture all of the information.
For example Country Code, where options 1-5 is Europe and 6-10 is Africa- I created variables that coded Europe= 1 if Country Code =1:5 and 0 if 6:10 (visa versa for Africa).

ID
Country Code
Europe
Africa

1
1
1
0

1
4
1
0

1
10
0
1

2
3
1
0

2
10
0
1

3
7
0
1

But I want to see if they answered 1 to both, and then delete the duplicate IDs.
Hence I want to create a dataset that looks like this:

ID
Europe
Africa
Both

1
1
1
1

2
1
1
1

3
0
1
0

I've tried this:
aggregate(x=Europe,by=list(ID),FUN=sum))
to create a sumEurope (followed by sumAfrica) to then say "if sumEurope*sumAfica >0 = 1"
However, the above code has an error that the "Assigned data..must be compatible with existing data." as there are more existing rows than assigned rows.

A: We could use summarise with max across Europe and Africa and then an ifelse statement:
library(dplyr)

df %>%
  group_by(ID) %>%
  summarise(across(c(Europe, Africa), max)) %>%
  mutate(Both = ifelse(Africa == 1 & Europe == 1, 1, 0))

     ID Europe Africa  Both
  <int>  <int>  <int> <dbl>
1     1      1      1     1
2     2      1      1     1
3     3      0      1     0

data:
structure(list(ID = c(1L, 1L, 1L, 2L, 2L, 3L), CountryCode = c(1L,
4L, 10L, 3L, 10L, 7L), Europe = c(1L, 1L, 0L, 1L, 0L, 0L), Africa = c(0L,
0L, 1L, 0L, 1L, 1L)), class = "data.frame", row.names = c(NA,
-6L))

A: In BASE R:
transform(+aggregate(cbind(Europe, Africa)~ID, df, any), Both = Europe * Africa)
  ID Europe Africa Both
1  1      1      1    1
2  2      1      1    1
3  3      0      1    0

If you dont mind the logical values:
transform(aggregate(cbind(Europe, Africa)~ID, df, any), Both = Europe * Africa)
  ID Europe Africa Both
1  1   TRUE   TRUE    1
2  2   TRUE   TRUE    1
3  3  FALSE   TRUE    0


text:
Q: Prove that a linear transformation exists with certain conditions
Let $V$ be a finite vector space and $U$ a sub-vector space to $V$
Prove that a linear transformation $T:V\rightarrow V$ exists, where:
$\ker T = U$ & $\ker T \cap\operatorname{Im}T = \{0\}$

I understand that each vector in $U$ is a vector that follows:
$v \in V$ & $T(v)=0$
And technically $U$ can just be the zero vector space, and $T(v) =v$
But this doesn't feel like a proof to me, if anybody can help me understand better how to approach such a question, that would be highly appreciated.

A: Hint: Let $W$ be an arbitrary complement of $U$ (say, extend a basis of $U$ to a basis of $V$ and keep only the new basis elements).
Then you can apply the identity on $W$.


text:
Q: What is the origin and scope of usage of the phrase "So long...." used to bid goodbye? We often colloquially use the phrase so long to say goodbye. For eg. So long, we'll see you next week or He said so long and left.
What is the origin of this phase? Rather, how did it come into being? I would also like to know the circumstances under which its usage would be deemed appropriate.
EDIT: Is this phrase some sort of corruption of any phrase in some other language(looking at the answers) or it has some meaning to it in English Language as well?

A: The OED gives a first use in 1865. No explanation is given, but comparison is made with German so lange. It is a purely colloquial expression, and one that seems to be limited to particular idiolects. I wouldn't use it myself. It may be more common in American than in British English.

A: I don't have a clear answer about the origin of "so long" in the sense of "good-bye" or "au revoir," but I did find some striking early discussions of the expression. From a list of student slang expressions categorized as "Arbitrary or Unexplained Coinages: Origin Unknown," in Willard Gore, "Student Slang" (1895):

so long. Good-bye; au revoir.
...
So long, in the sense of good-bye, or au revoir (p. 4). An interesting discussion of this phrase appears in Notes and Queries, 6th Series, Vols. II., III. On p. 67 of Vol. II., 'B. P.' says that the expression is fully seventy-five years old; it is used by sailors, by uneducated people in the United States, and by colored people of the Middle States. On p. 194, T. C. McMichael remarks that it is heard frequently in Liverpool, especially amongst the seafaring class; it probably derived from the East Indian word salaam, used as a salutation almost universally  in some parts of the East. On p. 195 B. D. Moseley says that it is an absurd rendering of the French saluons. {Cf. the low comedian's rendering of au revoir, by 'over the river' or olive oil'.} On p. 496 'A West Coaster' makes objection to these derivations on the ground that salaam and saluons are expressions of greeting,'so long', one of leave taking. 'So long' means 'so long as we do not meet'. In Vol. III., p. 18, Augustus Weisbacher notes that 'so long' is common amongst English and Dutch in Grahamston, South Africa.
For a literary use of the expression see Walt Whitman's Leaves of Grass (Phil., 1884), p. 380: A poem entitled "So Long."

The poem headed "So Long!" appears in a section of Leaves of Grass called "Songs of Parting." It does not appear in the 1856 edition of Leaves of Grass, but it does appear in an edition published in 1860. Not surprisingly, "So Long" uses the expression "so long" multiple times:

To conclude—I announce what comes after me, / The thought must be promulged, that all I know at any time suffices for that time only—not subsequent time; / I announce greater offspring, orators, days, and then depart.
...
I have pressed through in my own right, / I have offered my style to every one—I have journeyed with confident step, / While my pleasure is yet at the full, I whisper, So long, / And take the young woman's hand, and the young man's hand for the last time.
...
So long! / I announce natural persons to arise, / I announce justice triumphant, / I announce uncompromising liberty and equality, / I announce the justification of candor, and the justification of pride.
So long! I announce a man and a woman coming—perhaps you are the one / I announce a great individual, fluid as Nature, chaste, affectionate, compassionate, fully armed. / So long! I announce a life that shall be copious, vehement, spiritual, bold, / And I announce an old age that shall lightly and joyfully meet its translation.
...
Dear friend, whoever you are, here, take this kiss, /I give it especially to you—Do not forget me, / I feel like one who has done his work—I progress on,— / (long enough have I dallied with Life,) / The unknown sphere, more real than I dreamed, more direct, darts awakening rays about me—So long! / Remember my words—I love you—I depart from materials, / I am as one disembodied, triumphant, dead.

At least some of these instances of the phrase—in the context of the poem, which is the last on in this edition of the book—clearly allude to the meaning "farewell." This is five years earlier than the earliest example of "so long" in the sense of "goodbye" that the OED cites, according to Barrie England's answer. Whitman was born and raised in Long Island, New York, and spent much of the first half of his life there.
In the context of Whitman's usage it is amusing to dive into the discussion of "so long" that runs across multiple numbers of Notes and Queries, starting with this one from July 24, 1880:

"So LONG."—This is a queer expression, used in the sense of "good-bye," often heard int he United States, but always by uneducated people. Sailors, on bidding you good day, say "So long'" Coloured people in the Middle States employ these words. It is not of recent adaptation, being fully seventy-five years old. Is there any word or combination of words sounding like so long, meaning "good-bye" in use on the African coast or in the East Indies? Do English sailors use these words? [signed,] B. P.

The first respondents to B.P.'s query were Thomas McMichael of Liverpool an B.D. Moseley of Burslem, in the September 4, 1880 issue of Notes and Queries. First McMichael:

This expression may very frequently be beard in this city, especially amongst the seafaring class, and it is interesting to learn that it is in common use in various parts of the United States. The result of some thought and inquiry convinces me that this expression takes its origin from the East Indian word "salaam," used as a salutation almost universally in some parts of the East, hence its use in the corrupted form of "So long" is principally by sailors who have heard it in those countries, and, sailor-like, are not very particular as to its correct pronunciation. By-the-bye, is not this word "salaam" another form of the Hebrew "salem," meaning peace? I should be glad if any reader could enlighten me on this point.
I will just remark, in conclusion, that several other explanations of "So long" have been suggested to me ; but although some of them are plausible, yet none of them will bear comparison with the foregoing.

And second from Moseley:

This is an absurd rendering of the French "saluons," from a fancied resemblance in sound to the English expression "So long," pronounced as one word. A similar affectation, now much in vogue amongst our gommeux, is th rendering of au revoir with "olive oil."

Next from "A West Coaster" in the December 18, 1880 issue of Notes and Queries:

Since the appearance of the replies of Messrs. T. C. McMichael and Moseley in your number of the 4th Sept. I have waited to see if some known authority would not set them right. Salaam and Saluons are words of greeting, the expression "So long" one of leave-taking. Were either of your two correspondents dropped down among the English residents of any Spanish-American city, from Montevideo southward to Panama northward on the opposite coast, he would find that he could not fail to use this form on leaving his guest or acquaintance on every possible occasion without risk of being deemed unmannerly or unobservant. The Spaniards, always known as a punctilious race, never leave one another without this polite ceremony : and their expressions have nothing to do with health. "So long" means "So long as we do not meet." But the polite Spaniard goes further, and says how long that will probably be. Hence the phrases"Hasta ahora," "Hasta luego," "Hasta mas tarde," "Hasta despues," "Hasta la vista" (Au revoir), and finally "Adios." Could either of your correspondents suggest a more convenient form of rendering all these gradations than that adopted by the scions of English and Spanish parents—the indefinite "So long"? Sailors who have never used the phrase before acquire it on their arrival on the Spanish-American coasts ; and, once learnt, the custom is never forgotten. West coast folks in England always use it to one another as a pleasing custom, but we are chary as to employing it in purely English circles.

And from Augustus Weisbecker of Grahamstown, South Africa, in the January 1, 1881 issue of Notes and Queries:

This phrase is a common salutation in this colony amongst the English and Dutch, and used on a temporary separation of friends, as au revoir by the French. I remember hearing it amongst the Blue Noses of Nova Scotia and the New Brunswickers.

The expression also appears in Frederick Jago, "The Ancient Language, and the Dialect of Cornwall, with an Enlarged Glossary of Cornish Provincial Words" (1882):

So-long! Good bye! Adieu! (Heard in Looe and Waldebridge). W.T.A.P[attison, "of Duporth, near St. Austell"]

Perhaps the most intriguing early example of "so long" that I came across was from a translation of a story by the German writer E.T.A. Hoffmann, "The Mines of Falun," in Graham's Illustrated Magazine (January 1858):

The wedding-day at length approached. It was St. John's day. Early in the morning Elias knocked at his bride's door. She opened it, and drew back affrighted when she beheld Elias in his wedding suit, pale as a corpse, and with sunken, gleaming eyes.
"I will confide in you my dearest Ulla," he said, in a feeble, trembling voice, "that we are now on the eve of the highest happiness of which mortals are capable. Every thing was revealed to me last night. Below in the mines in the granite and mica lies a bright red, sparkling ruby, on which our horoscope is engraved. It is finer than the ruddiest carbuncle ; and when we are united in true love, and gaze into its clear light, we shall see plainly how wonderfully our hearts are interwoven with the strange sprig that grows from the heart of the queen in the centre of the earth. It only needs that I should bring that ,jewel up to the daylight, and that, moreover, I will do. For so long, farewell, beloved Ulla, I shall soon return."

A similar phrasing appears in a translation of Fritz Reuter, Seed-Time and Harvest; or, During My Apprenticeship, serialized in The Living Age (January 1, 1871):

"But"—here he drew out from his pocket an immense double-cased watch, such a thing as one calls a warming-pan—"really, it is close upon seven! I must hurry, for my people need looking after."
"Hold on," said Habermann, "I will go part way with you. Good-bye for so long, Jochen."
"Good-bye, also, brother-in-law," said Jochen, and remained sitting in his corner.

It thus seems possible that "So long" may represent a telescoped form of the longer phrase "Goodbye for so long [as I do not see you]"—or in other words, "Goodbye until I see you again."

A: It certainly seems American to me. If it has a German origin, it might well have to do with migration from Germany to America in the nineteenth century.


text:
Q: scatterLine using Kendo Chart - how to add error errorBars? I have my DoJo here http://dojo.telerik.com/oxoYE . I am struggling to find out a way to add error bar to this:
    function createChart() {
        $("#chart").kendoChart({
            seriesDefaults: {
              type: "scatterLine",
              xErrorLowField: "low",
              xErrorHighField: "high",
            },
            series: [{
              data: [{x: 1.7, y: 11, low: 1, high: 3}, {x: 5.4, y: 8, low: 3, high: 6}, {x: 6.4, y: 13.4, low: 5, high: 7}]
            }],
            tooltip: {
                visible: true,
                format: "{0},{1}"
            }
        });
    }

http://docs.telerik.com/kendo-ui/controls/charts/features/error-bars says error bar supported in scatter line.
Please help.
Thanks
Datha

A: Oops , I found answer http://docs.telerik.com/kendo-ui/controls/charts/features/error-bars#bind-to-categorical-series
I modified my DoJo http://dojo.telerik.com/oxoYE


text:
Q: How to use "explain" for _search queries in ElasticSearch I'm using ElasticSearch 2.3.3.
I have the following mapping:
"mappings": {
    "entries": {
        "dynamic": "strict",
        "properties": {
            "Data": {
                "properties": {
                    "FirstName": {
                        "type": "string",
                        "index": "not_analyzed"
                    }
                }
            }
        }
    }
}

I have the following query:
POST /frm4356/entries/_search
{
    "query" : {
        "match" : {"Data.FirstName" : "BBB"}
    }
}

Which works fine and yields the following response:
{
  "took": 1,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  },
  "hits": {
    "total": 1,
    "max_score": 1,
    "hits": [
      {
        "_index": "frm4356_v3",
        "_type": "entries",
        "_id": "57c867715f7ecd2a78610ec6",
        "_score": 1,
        "_source": {
          "Data": {
            "FirstName": "BBB"
          }
        }
      }
    ]
  }
}

I tried to used the "Explain API" but failed miserably.
The following did not work:
Attempt #1
POST /frm4356/entries/_explain
{
    "query" : {
    "match" : {"Data.FirstName" : "BBB"}
    }
}

Attempt #2:
POST /frm4356/entries/_search
{
    "explain" : true,
    "query" : {
    "match" : {"Data.FirstName" : "BBB"}
    }
}

In both cases, I keep getting this response:
{
   "error": {
      "root_cause": [
         {
            "type": "strict_dynamic_mapping_exception",
            "reason": "mapping set to strict, dynamic introduction of [query] within [entries] is not allowed"
         }
      ],
      "type": "strict_dynamic_mapping_exception",
      "reason": "mapping set to strict, dynamic introduction of [query] within [entries] is not allowed"
   },
   "status": 400
}

What am I doing wrong ? I'd like to see the explanation of the query.

A: Try something like this:
GET /blog/post/_validate/query?explain
{
  "query": {
    "match": {
      "title": "Smith"
    }
  }
}

Source

A: Here's the official documentation for Explain API.
It looks like you missed the _id there.
POST /frm4356/entries/57c867715f7ecd2a78610ec6/_explain
{
  "query": {
    "match": {
      "Data.FirstName": "BBB"
    }
  }
}


text:
Q: jQuery: Check if button is clicked I have two buttons in a form and want to check which one was clicked.
Everything works fine with radioButtons:
if($("input[@name='class']:checked").val() == 'A')

On simple submit button everything crash.
Thanks!

A: jQuery(':button').click(function () {
    if (this.id == 'button1') {
        alert('Button 1 was clicked');
    }
    else if (this.id == 'button2') {
        alert('Button 2 was clicked');
    }
});

EDIT:- This will work for all buttons.

A: $('input[type="button"]').click(function (e) {
    if (e.target) {
        alert(e.target.id + ' clicked');
    }
});

you should tweak this a little (eg. use a name in stead of an id to alert), but this way you have more generic function.

A: $('#submit1, #submit2').click(function () {
   if (this.id == 'submit1') {
      alert('Submit 1 clicked');
   }
   else if (this.id == 'submit2') {
      alert('Submit 2 clicked');
   }
});

A: $('#btn1, #btn2').click(function() {
    let clickedButton = $(this).attr('id');
    console.log(clickedButton);
});

A: You can use this:
$("#id").click(function()
{
   $(this).data('clicked', true);
});

Now check it via an if statement:
if($("#id").data('clicked'))
{
   // code here
}

For more information you can visit the jQuery website on the .data() function.

A: try something like :
var focusout = false;

$("#Button1").click(function () {
    if (focusout == true) {
        focusout = false;
        return;
    }
    else {
        GetInfo();
    }
});

$("#Text1").focusout(function () {
    focusout = true;
    GetInfo();
});


text: Q: Alternatives to scipy.optimize Newton-CG for minimization if I have the Hessian? I've got a complicated, nonlinear problem to minimize, but I have analytic expressions for the Jacobian and Hessian. I'm currently using scipy.optimize.minimize with the Newton-CG method and am looking to test some alternative methods. Can anyone recommend packages that have other python minimization routines that use pre-computed Hessians and not numerical approximations?


text:
Q: Find all Entire Functions $f$ such that $u(x, y) = av(x, y) + b$ for $a, b \in \mathbb{R}$ I want to find all entire functions $f$ such that for all $z \in \mathbb{C}$, $u(x, y) = av(x, y) + b$ for $a, b \in \mathbb{R}$. My attempt is as follows.$\DeclareMathOperator{\Re}{Re}\DeclareMathOperator{\Im}{Im}$
If $u(x, y) = av(x, y) + b$, then $u(x, y) - av(x, y) - b = 0$. Since $\Re(f(z)) = u(x, y)$ and $\Im(f(z)) = -\Re(if(z)) = v(x, y)$, then it follows that
\begin{equation*}
\Re(f(z)) - a\Re(if(z)) - b = 0
\end{equation*}
Therefore,
\begin{align*}
\Re(f(z) - aif(z) - b) &= 0 \\
f(z) - aif(z) - b &= iC, \exists C \in \mathbb{R} \\
f(z)(1 - ai) &= iC + b \\
f(z) &= \dfrac{b + iC}{1 - ai}
\end{align*}
I am not sure if this is the right approach, and if not, how can I improve finding all entire functions satisfying the conditions? Appreciate some help or techniques.

A: Your $C$ depends on $z$ so you have not solved the problem.
By Cauchy Riemann equations we get $v_y=u_x=av_x$ and $-v_x=u_y=av_y$. Hence, $v_y=av_x=-a^{2}v_y$. So $(1+a^{2})v_y=0$ If $a^{2} \neq -1$ (i.e. $a \neq \pm i$) this gives $v_y=0$. But $av_x=v_y$ so $v_x=0$ if $a \neq 0$. In the case $a \neq 0, a \neq \pm i$ we have proved that $v_x=v_y=0$ so $v$ is a  constant (and so is $u$). In this case $f$ is necessarily a constant function.
The cases, $a=0, a=i, a=-i$ are left to you.
EDIT: It is given that $a$ is real. So only the case $a=0$ is left to you. Thanks to Samuel M. A. Luque for pointing this out.


text:
Q: Email validation in mvc view? I know we can add Regular Expression in Model class in MVC but I was wondering is there any way to add that in MVC view.
   <div class="form-group">
                            @Html.LabelFor(model => model.Email, new { @class = "control-label" })
                            @Html.TextBoxFor(model => model.Email, new { @class = "form-control", @placeholder = "E mail", @required = "Required", @type = "email" })
                            @Html.ValidationMessageFor(model => model.Email)
                        </div>

By using @type="email" I must have to put @ in the textbox e.g abc@abc but it allows me to submit the form without entering .com i.e abc@abc.com, so how can I force it to ask a user to enter "." in email to submit a form.
Thanks


text:
Q: Caused by: com.jayway.jsonpath.PathNotFoundException Error I am writing test case for my controller. And, I am using .andExpect method to match jsonpath expression. Below is my code:
    @Test
    public void getALLEmails() throws Exception {

        Email email = new Email();
        email.setTicketID("123");

         List<Email> emails = Collections.singletonList(new Email());

        assertThat(this.emailService).isNotNull();
        given(emailService.getEmails()).willReturn(emails);

        mockMvc.perform(get("/emails"))
                .andExpect(status().isOk())
                .andExpect(content().contentType("application/json;charset=UTF-8"))
                .andExpect(jsonPath("$", hasSize(1)))
                .andExpect(jsonPath("$.ticketID", is("123")));

    }

However, I am getting the following error;

Error: java.lang.AssertionError: No value at JSON path "$.ticketID"
      at org.springframework.test.util.JsonPathExpectationsHelper.evaluateJsonPath(JsonPathExpectationsHelper.java:295)
      at org.springframework.test.util.JsonPathExpectationsHelper.assertValue(JsonPathExpectationsHelper.java:72)
      at org.springframework.test.web.servlet.result.JsonPathResultMatchers.lambda$value$0(JsonPathResultMatchers.java:87)
      at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:195)
      at com.example.rstsdemo.controller.EmailControllerTest.getALLEmails(EmailControllerTest.java:67)
      at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
      at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
      at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
      at java.base/java.lang.reflect.Method.invoke(Method.java:566)
      at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
      at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
      at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
      at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
      at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)
      at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
      at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
      at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
      at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
      at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
      at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
      at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
      at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
      at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
      at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
      at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
      at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
      at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
      at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
      at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
      at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
      at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
      at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
      at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
      at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
      at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
      at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
  Caused by: com.jayway.jsonpath.PathNotFoundException: Expected to find an object with property ['ticketID'] in path $ but found 'net.minidev.json.JSONArray'. This is not a json object according to the JsonProvider: 'com.jayway.jsonpath.spi.json.JsonSmartJsonProvider'.

Please, help me find the solution to it. I believe I am using correct java expression.
I have already tried using different jsonpath expressions such as:
[0].ticketID, $.[0].ticketID and others. Thanks!


text:
Q: jQuery text fading effect on mac I am trying to achieve a consistent text fading effect cross-browser using jQuery.
As you'll see in the example below, in the last frame or so of the animation as the text fades in, the font weight suddenly increases which makes it look jerky/clunky.
This occurs on:

*

*Chrome Snow Leopard

*Safari with Snow Leopard

*FF4 pre Snow Leopard.

However, the fading looks completely smooth on

*

*FF4 Snow Leopard

*IE6 on windows XP

*Chrome on Windows 7

(have not tested any more). To see the effect, visit the below:
http://jsfiddle.net/jZdzK/5/
Has anyone seen this before/know of any workarounds or is it a browser implementation we can do nothing about?

A: I tested it on Snow Leopard and it looks fine. My want to restart your computer maybe it is just slowing with some of the new hardware acceleration.


text:
Q: phpunit get exception message I've just started with php unit.
In my test cases UsersController should return:
public function UsersController() {
    ....
    throw new \Cake\Network\Exception\NotFoundException();
}

phpunit code
$this->setExpectedException('Cake\Network\Exception\NotFoundException');

returns an assertion failed that looks like:

App\Test\TestCase\Controller\UsersControllerTest::testActivate
  Failed asserting that exception of type "Cake\Network\Exception\NotFoundException" is thrown.

Meanwhile browser return a 404 PageNotFound and $this->assertResponseOk() returns:

App\Test\TestCase\Controller\UsersControllerTest::testActivate
  exception 'Cake\Network\Exception\NotFoundException' with message 'Not Found' in /vagrant/ifmx.local/src/Controller/UsersController.php:215

Does somebody know why it's happened? And is there any way to get exception message in unit test.

A: You seem to have misunderstood how the integration test case works.
It doesn't just wrap a call to a controller method, like $controller->action(), it simulates a whole request, and as such, exceptions are being catched, and result in error pages being rendered, just like it happens when you are visiting a URL in your browser.
So PHPUnit will never know about the exception, and thus you cannot use the expected exception feature as you would when directly testing specific code parts where exceptions bubble up to PHPUnit. If that would happen, then it wouldn't be possible to assert responses, which one might want to do, even when an exception has been thrown.
Possible exceptions are being buffered in the IntegrationTestCase::$_exception property, which you can for example use to test if, what kind of exception has been thrown, etc, like
$this->assertInstanceOf('\Cake\Network\Exception\NotFoundException', $this->_exception);
$this->assertEquals('Not Found', $this->_exception->getMessage());


text:
Q: Converting leads without giving edit perm on Accounts My requirement is that sales reps cannot create or edit accounts but we want to enable them to convert leads when there is an existing account in place, in order to create new contacts and Opportunities under them.

*

*I have written a custom Lead Convert page that allows them to lookup an existing Account and then the controller code will call the database.leadconvert() method to convert the lead to that Account.  However SF requires that the user running this operation has edit rights on the Account in order to convert a lead under it, even if I declare the class as without sharing.  Shoot.

*I next tried to give them edit perm on the Account and then lock down anything I could to prevent them from editing accounts - removed the Edit button from layout, made all fields on the layout readonly etc.  But this is a pain and there are some fields we just can't lock down, like Name and Owner.  It allowed them to convert but too many bad side effects.

*My next brain wave was to insert a permission set assignment record giving them edit permission, convert the lead and then delete the permission set assignment.  This seemed awesome until I hit the Mixed DML error when trying to convert the lead after inserting the Permission Set Assignment.
Any ideas on how to get around the mixed DML?  I don't really want any part of this to be @future since I need to show the user any error messages from the lead conversion operation or take them to the Account page after it completes.
// if user doesn't have edit rights on Account, add the permission set now
    if (!Account.sObjectType.getDescribe().isupdateable()) {
        permAdd = new PermissionSetAssignment(PermissionSetId = '0PS80000000blLl', AssigneeId = UserInfo.getUserId());
        insert permAdd;
    }
    // prepare lead conversion here...snipped for brevity

    //convert the lead
    Database.LeadConvertResult leadConvertResult = Database.convertLead(leadConvertObj);
    if (permAdd != null)
        delete permAdd;

A: Good solution the 3rd one (given all the limitations of the case).
Anyway. To avoid the Mixed DML error you could split the operation in 3 different transactions, "almost seamlessly" to the User, using good old (but still well used with OAUTH) white web page with location refresh header.
Using this technique you can make your Users:

*

*get the permission set - redirect...

*convert the lead - redirect...

*get the permission set removed - get finally redirected to next step in process

which is suboptimal but still makes the way for what you need.
The only security spot I see is in the case a User clicks on "Stop loading page" while in the middle of that. A scheduled class/future method to check the User isn't a bad guy? But that's another story.


text:
Q: LaTeX Biblatex Build for Ubuntu 16.04 I'm new to using Linux (Ubuntu 16.04), but I'm committed to full immersion. A catch to this is that I am writing a masters thesis in LaTeX and I ran into bibliography issues. Apparently this is a common issue with Ubuntu 16.04. I think maybe this is related. Here's my preamble:
\documentclass[12pt]{report}
\usepackage{graphicx}
\usepackage[letterpaper, left=1in, right=1in, top=1in, bottom=1in]{geometry}
\usepackage{setspace}
\usepackage{times}
\usepackage[explicit]{titlesec}
\usepackage[titles]{tocloft}
\usepackage[backend=biber]{biblatex-history}
\usepackage[bookmarks=true, hidelinks]{hyperref}
\usepackage[page]{appendix}

The error it throws is "! LaTeX Error: File `biblatex-history.sty' not found."
This issue seems to be discussed in a lot of special cases or in bits and pieces, but I can't seem to find a complete answer of how to fix this, or how to be sure if this is the bug that was found when Ubuntu updated. What should I do to fix this problem?

A: This is indeed a bug as you have linked however there is a workaround that is reported to work. Try this.
Source: https://bugs.launchpad.net/ubuntu/+source/biber/+bug/1565842
Edit: It appears there is a newer source package here: https://launchpad.net/ubuntu/xenial/+package/biber
As far as the specific error introduced by your preamble you might examine    \usepackage[backend=biber]{biblatex-history} and determine if you indeed have the package named or if there is a typo involved.
Related: https://tex.stackexchange.com/questions/52368/how-can-i-insert-by-bib-file-into-my-tex-file
and
https://tex.stackexchange.com/questions/20317/internal-bibliography-with-biblatex


text:
Q: select row with max value of a group of rows in sql I have a table "products" that has the columns "name" and price". There are multiple prices for the same name. The table looks like
shampoo 7
shampoo 10
shampoo 8
bread   1
bread   1.5
water   0.5
water   0.7
......

I want the row with the max price. I tried
select name, price
from products
group by name
having max(price);

Note: My problem isn't that, but I wanna know the logic behind the solution. Thanks.

A: Create one group or rows for each distinct name using group by name.  You can then select the name (because every row in the group has the same name.)  The group has many prices, and you can use the aggregate function max() to retrieve the highest price for the group.
select  name
,       max(price) as MaxPrice
from    Products
group by
        name


text:
Q: unable to attached a custom CSS on a site page using "code snippet" I have added a new aspx site page inside my team site and I want to reference a custom style sheet inside this site page only. So what I did is I edited the page then I chose to add a code snippet, and i add the following inside the code snippet :-
 <link href="/Style%20Library/Custom%20CSS/s.css" rel="stylesheet" type="text/css" />

Once I add the above reference inside the vcode snippet, I can see that the layout was affected directly, but when I click on apply button, it seems something hangs as I keep seeing the following page for more than 10 minutes till now :

i also try to add the css rules directly inside a <style> tag on the code snippet instead of referencing the css file. and i also can see the effect once i copied the css rules, but when i save the page the css effect will disappear , and i will get the following inside the code snippet:-
<style unselectable="on"></style>

A: Try to embed javascript this way:
<script type="text/javascript"></script>

It worked for me