text:
Q: To be able to select and operate as [0] and [0] or [1] and [1] in the pyhton list I have a code like this. I use constant th12 and constant dm12 in the first definition and accordingly I get an oscillation varying between 12. I also want to use "th23" "dm23" "th13" "dm13" values in this definition.
But if I use th12 in the process that takes place inside the def, the value of dm12 should come, or if I use th23, the value of dm23 should be used. So if th and dm have the same set of numbers, the transaction should occur.
If th12 and dm23 are used as an example, the operation will give incorrect results.
I don't know how to prepare a definition under this information.
Do you have any suggestions to fetch the th and dm values like this?
# (converted from degrees to radians)
th12 = np.radians(33.82)
th23 = np.radians(48.3)
th13 = np.radians(8.61)
th = [th12,th23,th13]
# del_m square
dm12 = 7.39*10**(-5)# eV^2
dm13 = 2.45*10**(-3) # eV^2
dm23 = dm12-dm13
dm = [dm12,dm23,dm13]

def prob(E,th12,dm12,L):
    return pow(np.sin(2*th12) * np.sin(1.27*dm12 * L /(E)),2)
def plotprob(E_list,th12,dm12,L_min,L_max,L_step):
    L = np.arange(L_min,L_max,L_step)
    for E in E_list:
        plt.plot(prob(E,th12,dm12,L), label=r"$E =$"+str(E) +" GeV")
    plt.xlim([L_min,L_max])
    plt.ylim([0,1.0])
    plt.xlabel(r"$L{\rm [km]}$")
    plt.ylabel("$Probability$")
    plt.legend()
    plt.show()
plotprob([0.1,0.01],th12,dm12,1,10000,1)

A: You can try the zip function with for loop to get the pairs of those lists
for i,j in zip(th,dm):
    plotprob(elist, i, j , *otherstuff)

A: I came up with such a result. I used dictionary for th and dm values. I can use both at the same time.
I wanted to use a separate definition for plotting, but I couldn't manage to plot outside.
th12 = np.radians(33.82)
th23 = np.radians(48.3)
th13 = np.radians(8.61)

# del_m square
dm12 = 7.39*10**(-5)# eV^2
dm13 = 2.45*10**(-3) # eV^2

def prob(th12,th23,th13,dm12,dm13,E,L_min,L_max,L_step):
    L = np.arange(L_min,L_max,L_step)
    dm23 = dm12 - dm13
    dms = {"21": dm12, "32": dm23, "31": dm13}
    ths = {"21": th12, "32": th23, "31": th13}
    lnus = {"21": r'$P(\nu_\mu \to \nu_e)$', "32": r'$P(\nu_\tau \to \nu_\mu)$', "31": r'$P(\nu_\tau \to \nu_e)$'}
    for i in range(3):
         for j in range(i):

            dm = dms[str(i+1)+str(j+1)]
            th = ths[str(i+1)+str(j+1)]
            lnu = lnus[str(i+1)+str(j+1)]
            prob = pow(np.sin(2*th) * np.sin(1.27*dm * L /(E)),2)
            plt.plot(L,prob,label= "Osc. "+lnu)
            plt.xlim([L_min,L_max])
            plt.ylim([0,1.0])
            plt.legend()
            plt.xlabel(r"$L{\rm [km]}$")
            plt.ylabel("$Probability$")

    return prob

prob(th12,th23,th13,dm12,dm13,1,1,35000,1)

plt.show()


text:
Q: FreeBSD: How to check how many threads are running in a process by PID? In Linux I can do this by checking the /proc/pid/status file and looking for a line: Threads: 1 (or any number). How can I achieve the same in FreeBSD? I am not interested in any interactive tool. Is there any C function, or a system file? I have tried BSD's procfs and and linprocfs and I could not find any similair feature there.

A: You want:
procstat -t <pid>
This answer is short, but I'm typing more to get the answer up to the minimum length.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Multiple Database Usage, Second Connection After Login There is a scenario like in the picture. There is a common database. Customers are connecting to the same database. After the connection, company-specific information is kept in a separate database. The connecting string is pulled from the company information in the database after the user logs in. How can I do this logic in .net core. I'm new and need ideas.
Click to see the script
When the user logs in, company information is also taken as in the picture.
Click for user company information
I can't define it in the "startup.cs" file because the user needs to be logged in.
Where and how can I define the connecting clause? Can you give an idea?
Startup.cs file
appsettings.json file
login method
In the login method, I need to migrate first. To create the tables. If there are tables, I need to connect to the company's product table. Can this special link be added to swagger too?

A: Specifically within .net core project you can utilise DBFactoryBase class, and create a constructor which accept appsettings json key to fetch another connection string.


text:
Q: How to write a GStreamer plug-in in Cython I want to prototype a new type of audio filter. At the moment I use GStreamer to return a buffer of my audio, and Cython to apply the filter to it. Then I send the result back to GStreamer.
Everything is wrapped in a python main code, the GStreamer accesses are done using pygst. Using Cython to prototype is great because it automatically recompiles when the code is run, and it very efficient.
However I feel this would be even better if I could use my Cython files to produce a GStreamer native plug-in (those are written in C).
Do you have an idea on how that could be achieved?

A: Cython is primarily designed for generating Python extension modules and isn't really designed to support other plugin APIs. However, if you're willing to hand-tweak the output you may be able to get something reasonable.
For example, you could hand-write a small C stub to initialize your module as a gstreamer plugin:
#include "Python.h"
#include "gst_plugin.h"

static gboolean plugin_init (GstPlugin *plugin) {
    // initialize the extension module
    #if PY_MAJOR_VERSION < 3
        initgstreamer();
    #else
        PyInit_gstreamer();
    #endif

    // call into function exported from cython module
    return register_plugin(plugin);
}

GST_PLUGIN_DEFINE (
    GST_VERSION_MAJOR,
    GST_VERSION_MINOR,
    my_filter,
    "My filter plugin",
    plugin_init,
    VERSION,
    "LGPL",
    "GStreamer",
    "http://gstreamer.net/"
)

You can then export that register_plugin function from your cython module:
cdef public int register_plugin(void *plugin):
    # use the gstreamer API in here to register your plugin

However, this is not the whole story. In order for this to work you'll have to somehow convince gstreamer to load libpython into its process, since cython depends on it even just to initialize. You'll probably need to initialize the Python interpreter a little before your code will run as you want. You'll need to define cython stubs for all of the gstreamer plugin registration APIs you want to use. And if anyone else tried to do the same thing in the same gstreamer process it'd probably all fall apart.
So with all of this said, a more straightforward path may be to make a gstreamer plugin that bridges to Python code, and then use that plugin to access your cython module. This way the python embedding is explicit and you'll get a chance to initialize the Python interpreter properly before loading your code. Such a plugin could be useful for other people trying to do similar projects to yours, whether using cython or the ctypes module.
Such a plugin would effectively be an upside-down PyGST: it'd load Python as a library into GStreamer, rather than loading GStreamer as a library into Python. There's probably some PyGST code you could re-use for this purpose, but you'd still have the limitation that each process can only contain one Python, so multiple modules using this mechanism would all need to share the same Python interpreter, much as when multiple applications are loaded into the mod_python module for the Apache webserver.

A: Cython generates Python extension modules which need to be initialized within Python context to be useful. I think what you're trying to accomplish won't be possible unless you work with gstreamer developers to add Python module support into gstreamer first.


text:
Q: How can I send more than one variable to a php file using ajax and a get request? I am trying to send an I.D. value and a name value to a php file using ajax. I can send just the I.D. variable just fine but when I try to add the name variable, the function stops working. How can I send both?
This works:
function click() {
    var name = clickedelement.getElementsByTagName('input')[0].value;
    var id = clickedelement.getElementsByTagName('input')[1].value;
    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    } else {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            document.getElementById("popupBox").innerHTML = xmlhttp.responseText;
        }
    }

    xmlhttp.open("GET", "friends2.php?id="+id, true);
    xmlhttp.send();
};

But when I try to add the name variable, it dosnt work.
function click() {
    var name = clickedelement.getElementsByTagName('input')[0].value;
    var id = clickedelement.getElementsByTagName('input')[1].value;
    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    } else {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            document.getElementById("popupBox").innerHTML = xmlhttp.responseText;
        }
    }

    xmlhttp.open("GET", "friends2.php?id="+id"&name="+name, true);
    xmlhttp.send();
};

A: change to "friends2.php?id="+id+"&name="+name you just have a missing +

A:      "friends2.php?id="+id+"&name="
// missing plus sign here ^


text:
Q: Cancel emulated hover event/color on touch device? Given this setup
a { color: #ccc; }
a:hover { color: #fff; }

Test

$('#abc').click(function() {
    doSomething();
    return false;
});

Everything "works" as expected, but "test" is left with white text on phone/tablets since iOS treats it as a hover now. What can I do to "reset" this?

A: You move the focus to another element and the hover style is reset. E.g. Try to create another link, let's say you call them "link1" and "link2": when you click on link 1 it becomes white. Then you click link 2: link 2 becomes white and link1 will be back to its #ccc colour.
See this Fiddle (I just tried it on my iPad):
http://jsfiddle.net/uuFxR/
If you want to do it programmatically you have to work on the .focus() JQuery method, see here:
http://api.jquery.com/focus/


text:
Q: Nginx regex based location directive does not capture whole requested path I have this location directive:
    location ~* ^/(_nuxt|_libs|_img|_fonts)/(.*) {
        alias /srv/nuxt/tools/dist/$1;
        try_files /$2 =404;
    }

This matches and serves successfully:
/_img/logo.png
but not:
/_libs/AryaBootstrap/css/bootstrap.min.css (returns 404).
Any idea what is going wrong here?


text:
Q: Microsoft Crypto API Disable Use of RSAES-OAEP Key Transport Algorithm I'm using CryptEncryptMessage to generate a PKCS#7 enveloped message. I'm using szOID_NIST_AES256_CBC as the encryption algorithm.
The generated message appears to be valid but is the RSAES-OAEP for the Key Transport Algorithm which has limited support in the wild (Thunderbird, OpenSSL SMIME Module among many others don't support it).
I'll like for CAPI to revert to the older RSAencryption for key transport.
Is there any possible way to do that, I could revert to the low level messaging functions if there is a way rather than to use CryptEncryptMessage but I can't find a way to do that even using the low level functions.
Code:
CRYPT_ENCRYPT_MESSAGE_PARA EncryptMessageParams;
EncryptMessageParams.cbSize = sizeof(CMSG_ENVELOPED_ENCODE_INFO);

EncryptMessageParams.dwMsgEncodingType = PKCS_7_ASN_ENCODING;

EncryptMessageParams.ContentEncryptionAlgorithm.pszObjId = szOID_NIST_AES256_CBC;
EncryptMessageParams.ContentEncryptionAlgorithm.Parameters.cbData = 0;
EncryptMessageParams.ContentEncryptionAlgorithm.Parameters.pbData = 0;

EncryptMessageParams.hCryptProv = NULL;
EncryptMessageParams.pvEncryptionAuxInfo = NULL;
EncryptMessageParams.dwFlags = 0;
EncryptMessageParams.dwInnerContentType = 0;

BYTE pbEncryptedBlob[640000];
DWORD pcbEncryptedBlob = 640000;

BOOL retval =  CryptEncryptMessage(&EncryptMessageParams, cRecipientCert, pRecipCertContextArray, pbMsgText, dwMsgTextSize, pbEncryptedBlob, &pcbEncryptedBlob);

A: The Key Transport Algorithm  is a bit tricky to handle, and it may not serve its purpose (I see you noted that you'd like CAPI to support RSAencryption; trust me, I would too). It looks like you've alaready detected the bulk of your problem - The generated message appears is valid, but your method makes it necessary to use CryptEncryptMessage, which won't work well/at all in the long run.
Step 1 - Examine the Code
CRYPT_ENCRYPT_MESSAGE_PARA EncryptMessageParams;
EncryptMessageParams.cbSize = sizeof(CMSG_ENVELOPED_ENCODE_INFO);

EncryptMessageParams.dwMsgEncodingType = PKCS_7_ASN_ENCODING;

EncryptMessageParams.ContentEncryptionAlgorithm.pszObjId = szOID_NIST_AES256_CBC;
EncryptMessageParams.ContentEncryptionAlgorithm.Parameters.cbData = 0;
EncryptMessageParams.ContentEncryptionAlgorithm.Parameters.pbData = 0;

EncryptMessageParams.hCryptProv = NULL;
EncryptMessageParams.pvEncryptionAuxInfo = NULL;
EncryptMessageParams.dwFlags = 0;
EncryptMessageParams.dwInnerContentType = 0;

BYTE pbEncryptedBlob[640000];
DWORD pcbEncryptedBlob = 640000;

BOOL retval =  CryptEncryptMessage(&EncryptMessageParams, cRecipientCert, pRecipCertContextArray, pbMsgText, dwMsgTextSize, pbEncryptedBlob, &pcbEncryptedBlob);

Pretty basic, isn't it? Although efficient, it's not really getting the problem done. If you look at this:
EncryptMessageParams.dwFlags = 0;
EncryptMessageParams.dwInnerContentType = 0;

you will see that it is pre-defined, but used only in the definition of retval. However, I could definitely see this as a micro-optimization, and not really useful if we're going to re-write the code. However, I've outlined the basic steps blow to integrate this without a total re-do of the code (so you can keep on using the same parameters):
Step 2 - Editing the Parameters
As @owlstead mentioned in his comments, the Crypto API is not very user-friendly. However, you've done a great job with limited resources. What you'll wanna add is a Cryptographic Enumeration Provider to help narrow down the keys. Make sure you have either Microsoft Base Cryptographic Provider version 1.0 or Microsoft Enhanced Cryptographic Provider version 1.0 to use these efficiently. Otherwise, you'll need to add in the function like so:
DWORD cbName;
DWORD dwType;
DWORD dwIndex;
CHAR *pszName = NULL;
(regular crypt calls here)

This is mainly used to prevent the NTE_BAD_FLAGS error, although technically you could avoid this with a more low-level declaration. If you wanted, you could also create a whole new hash (although this is only necessary if the above implementation won't scale to the necessary factor of time/speed):
DWORD dwBufferLen = strlen((char *)pbBuffer)+1*(0+5);
HCRYPTHASH hHash;
HCRYPTKEY hKey;
HCRYPTKEY hPubKey;
BYTE *pbKeyBlob;
BYTE *pbSignature;
DWORD dwSigLen;
DWORD dwBlobLen;
(use hash as normal w/ crypt calls and the pbKeyBlobs/Signatures)

Make sure to vaildate this snippet before moving on. You can do so easily like so:
if(CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_FULL, 0)) {
     printf("CSP context acquired.\n");
}

If you're documenting or releasing, might want to add a void MyHandleError(char *s) to catch the error so someone who edits but fails can catch it quickly.
By the way, the first time you run it you'll have to create a new set because there's no default. A nice one-liner that can be popped into an if is below:
CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_FULL, CRYPT_NEWKEYSET)

Remember that syncing server resources will not be as efficient as doing the re-work I suggested in the first step. This is what I will be explaining below:
Step 3 - Recode and Relaunch
As a programmer, re-coding might seem like a waste of time, but it can definitely help you out in the long run. Remember that you'll still have to code in the custom params when encoding/syncing; I'm not going to hand-feed you all the code like a baby. It should be well sufficient to show you the basic outlines.
I'm definitely assuming that you're trying to handle to the current user's key container within a particular CSP; otherwise, I don't really see the use of this. If not, you can do some basic edits to suit your needs.
Remember, we're going to bypass CryptEncryptMessage by using CryptReleaseContext, which directly releases the handle acquired by the CryptAcquireContext function. Microsoft's standard on the CAC is below:
BOOL WINAPI CryptAcquireContext(
  _Out_  HCRYPTPROV *phProv,
  _In_   LPCTSTR pszContainer,
  _In_   LPCTSTR pszProvider,
  _In_   DWORD dwProvType,
  _In_   DWORD dwFlags
);

Note that Microsoft's scolding you if you're using a user interface:

If the CSP must display the UI to operate, the call fails and the NTE_SILENT_CONTEXT error code is set as the last error. In addition, if calls are made to CryptGenKey with the CRYPT_USER_PROTECTED flag with a context that has been acquired with the CRYPT_SILENT flag, the calls fail and the CSP sets NTE_SILENT_CONTEXT.

This is mainly server code, and the ERROR_BUSY will definitely be displayed to new users when there are multiple connections, especially those with a high latency. Above 300ms will just cause a NTE_BAD_KEYSET_PARAM or similar to be called, due to the timeout without even a proper error being received. (Transmission problems, anyone with me?)
Unless you're concerned about multiple DLL's (which this doesn't support due to NTE_PROVIDER_DLL_FAIL errors), the basic set up to grab crypt services clientside would be as below (copied directly from Microsoft's examples):
if (GetLastError() == NTE_BAD_KEYSET)
 {
   if(CryptAcquireContext(
      &hCryptProv,
      UserName,
      NULL,
      PROV_RSA_FULL,
      CRYPT_NEWKEYSET))
    {
      printf("A new key container has been created.\n");
    }
    else
    {
      printf("Could not create a new key container.\n");
      exit(1);
    }
  }
  else
  {
      printf("A cryptographic service handle could not be "
          "acquired.\n");
      exit(1);
   }

However simple this may seem, you definitely don't want to get stuck passing this on to the key exchange algorithm (or whatever else you have handling this). Unless you're using symmetric session keys (Diffie-Hellman/KEA), the exchange keypair can be used to encrypt session keys so that they can be safely stored and exchanged with other users.
Someone named John Howard has written a nice Hyper-V Remote Management Configuration Utility (HVRemote) which is a large compilation of the techniques discussed here. In addition to using the basic crypts and keypairs, they can be used to permit ANONYMOUS LOGON remote DCOM access (cscript hvremote.wsf, to be specific). You can see many of the functions and techniques in his latest crypts (you'll have to narrow the query) on his blog:
http://blogs.technet.com/b/jhoward/
If you need any more help with the basics, just leave a comment or request a private chat.
Conclusion
Although it's pretty simple once you realize the basic server-side methods for hashing and how the client grabs the "crypts", you'll be questioning why you even tried the encryption during transmits. However, without the crypting clientside, encrypts would definitely be the only secure way to transmit what was already hashed.
Although you might argue that the packets could be decrypted and hashed off the salts, consider that both in-outgoing would have to be processed and stored in the correct timing and order necessary to re-hash clientside.


text:
Q: printf format f versus d in Python Some C code I am working in has an int set to -145. Depending on the format, the value returns as either 0.00 or -145. Take the following
int a = -145;

printf("%.2lf", a); // returns 0.00
printf("%.2ld", a); // returns -145

First question is how is it that the first line is returning 0.00? Second question is how to return 0.00 in Python?
Among the many iterations I've tried, here are a few:
a = -145

"%0.2lf" % a # -145.00
"%0.2ld" % a # -145
"%0.2li" % a # -145
"%0.2f" % a # -145.00

A:  int a = -145;

printf("%.2lf", a); // returns 0.00
printf("%.2ld", a); // returns -145

Both function calls invoke undefined behavior. The correct conversion specifier to print an int is d not lf (for double), not ld (for long).

A:
Second question is how to return 0.00 in Python?

If you insist:
import struct

def misinterpret_int_as_double(n):
    int_bytes = struct.pack('i', n)
    padding = b'\x00' * (struct.calcsize('d') - struct.calcsize('i'))
    return struct.unpack('d', int_bytes + padding)[0]

>>> misinterpret_int_as_double(-145)
2.1219957193e-314

This is essentially what your C code is doing behind the scenes.  C doesn't do any type-checking (at compile-time or run-time) on the arguments passed in the ... part of a call to a varargs function.  What happens is that the memory that stores printf's arguments contains:

*

*A pointer to the string literal "%.2lf.

*The bytes representing the number -145.  (On x86-32 or x86-64, this is the 4 bytes 91 FF FF FF.)

*Some garbage data.  (In the Python code above, this is assumed to be all zeros, but in your C program it need not be.)

The printf function sees the lf specifier and expects a double.  So, it interprets the following bytes, 91 FF FF FF xx xx xx xx (where xx = garbage) as  one.  For about 1/4 of the possible values of the garbage (including 00 00 00 00), the number is small enough to round to zero.
Note that I've assumed a bunch of stuff: That you have a little-endian system with 4-byte int and 8-byte double.  That function arguments are passed in ascending order in memory.  And that your code doesn't segfault.  YMMV on other hardware/OS/compiler combinations.  That's how it is with undefined behavior.
Python works differently, because it's safely typed.  If you pass the "wrong" type to str's % operator, it will automatically convert the operand to the correct type by calling the magic __float__ method (or __str__ or __int__ or whatever depending on which format it is).


text:
Q: Secure upload and show image or file in codeigniter 3 I want to upload image in my codeigniter 3  , and I want to show the uploaded image to my users (this is in register level and users is inputing his profile data)
 I should showe the uploaded image to him.
 I have read this :

Moving it outside of the public_html is a good idea, also try to
  rename the file and just add the extension to it.

and  another :

Do not move uploaded file to directory which is accessible from URL

but I don't know how can I have show the picture which is not directory which is accessible from URL ! .
 I don't have any idea it's really important for me the security I have used  codeigniter  upload class and I don't you know what kind of security other operations  should I do
this is my controller :
public function do_resize($img_name ,$image_original_width , $image_original_height   )
{

    // $nesbat = $image_original_height  / $image_original_width ;

    $config_manip = array(
    'image_library' => 'gd2',
    'source_image' => '../uploads/'.$img_name,
    'new_image' => '../uploads/'.$img_name,
    'maintain_ratio' => TRUE,
    'create_thumb' => TRUE,
    'thumb_marker' => '_thumb',
    'width' => 150,
    'height' => 150
    );
    $this->load->library('image_lib', $config_manip);
    if (!$this->image_lib->resize()) {
        // echo $this->image_lib->display_errors();
        return false ;
    }
    else
    {
        return true ;
    }
    // clear //
    $this->image_lib->clear();

}

function do_upload()
{

    $file_name = $this->input->post("file_name") ;

    $config['upload_path'] = '../uploads/';
    $config['allowed_types'] = 'gif|jpg|png';
    $config['max_size'] = '10000';
    $config['max_width']  = '1024';
    $config['max_height']  = '768';
    $config['file_name']  = $file_name;

    // delete if .gif image exists before

    if ( is_file('./uploads/'.$file_name.".gif")   )
    {
        unlink("./uploads/".$file_name.".gif");
        unlink("./uploads/".$file_name."_thumb.gif");
    }

    // delete if .gif image exists before

    if ( is_file('./uploads/'.$file_name.".jpg")   )
    {
        unlink("./uploads/".$file_name.".jpg");
        unlink("./uploads/".$file_name."_thumb.jpg");
    }

    // delete if .gif image exists before

    if ( is_file('./uploads/'.$file_name.".png")   )
    {
        unlink("./uploads/".$file_name.".png");
        unlink("./uploads/".$file_name."_thumb.png");
    }

    $this->load->library('upload', $config);

    if ( ! $this->upload->do_upload())
    {
        $error = array('error' => $this->upload->display_errors());
        echo "
fail
";
        echo "
".$this->upload->display_errors()."
";
    }
    else
    {
        $data = array('upload_data' => $this->upload->data());
        $upload_data = $this->upload->data();

        $uploaded_file_name =   $upload_data['file_name'];

        $resize = $this->do_resize($uploaded_file_name  , $upload_data['image_width'] , $upload_data['image_height'] ) ;
        if ($resize == true )
        {
            echo "
success
";
            echo "
".$upload_data['file_name']."
 ";
            $thumb_link = str_replace($file_name,$file_name."_thumb",$upload_data['file_name']);
            echo "
".$thumb_link."
 ";
        }
        //if $resize == true , nabashe -> uploade koli fail eleam mishe ta dobare anjam beshe
        else
        {
            echo "
fail
";
        }

    }
}

A: Images are generally a public asset but you can protect them in a few ways.

*

*Put an index.html or index.php file in your images directory.

*Turn off directory listing in your .htaccess file

*Rewrite the file name (will obfuscate orginal name)

To view the image after it's uploaded will require AJAX, or a page refresh. A page refresh is easier to code, simply upload the file and show that file on the preceeding page.
You can protect the folder to make sure a particular page has access to displaying an image. This makes things more complicated but working with some kind of resource access system might help you achieve this.
Once the page is loaded though - the image will be available to that user and once downloaded there.
I am not sure on what youre protecting exactly (profile pics, adult content..) but images, like CSS files are public assets.
Rich

A: Using this way, we can prevent Image call from other server.
Prevent image hotlinking (IMP)
- Image hotlinking is the process/technique of using someone else's Image URL in our Website and using their bandwidth. In order to prevent this mystery, we can prevent access for external server by adding following line in htaccess.
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?yourdomain.com [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ - [NC,F,L]

A: Just create a blank index.html file and put the index.html file on all other public folders except application/system folders (they already have it).
This is a simple security technique to restrict viewers to view your files on public folders.


text:
Q: How to fix that overlapping XML? I have a problem. I am making some changes in XML code but sometimes it gets overlapped like:
<xref><mytag></xref></mytag>

I am thinking about a script that will parse XML file and fix that problem like:
<xref><mytag></mytag></xref><mytag></mytag>

Can anyone help my with that? Maybe some regular expression? Or some tool ready for use, python script etc. I got many files to fix and I will appreciate every advice!s

A: Use lxml; the library can make an attempt at parsing your invalid XML and clean it up, by setting the recover flag:
>>> from lxml import etree
>>> from StringIO import StringIO
>>> ex = '<xref><mytag>there is some text</xref></mytag>'
>>> parser = etree.XMLParser(recover=True)
>>> tree = etree.parse(StringIO(ex), parser)
>>> etree.tostring(tree.getroot())
'<xref><mytag>there is some text</mytag></xref>'

A: This is the best tool for me to deal with xml in Python: lxml
Your problem however, i'm afraid it can't be solved with lxml, since that xml is invalid. I encourage you to use some xml tool or library (lxml) to generate valid xmls and avoid this kind of issues.

A: As for C++ you can use the POCO library XML (Document) features to edit your XML files: Poco::XML::Document


text:
Q: Determining the range of parameters that yield real values for a certain NIntegrate form I have specified just one set of $s$ and $g$ values that yields a real value for the NIntegrate below. It is possible that some $s,g$ combination can give rise to an imaginary output. I would like to know  the method of determining the whole  range of $s,g$ values that give rise to real value outcome for the integration. A region plot might be useful, but nevertheless a neat way of doing this will be appreciated.
s = 1.1;
g = 0.1;

NIntegrate[
  (p^2* Sqrt[1 - (2*p)/(-g + p*(1 + p))])/(-1 + (p/g)*(p - 1)) -
  p^2/((1 + p/g)*(1 + p))*Sqrt[1 - (2*p)/(g + p*(1 + p))]),
  {p, s, 1000}]

A: Amplifying on Chenminqi's answer
g = 1/10;

func = (p^2*Sqrt[1 - (2*p)/(-g + p*(1 + p))])/(-1 + (p/g)*(p - 1)) -
    p^2/((1 + p/g)*(1 + p))*Sqrt[1 - (2*p)/(g + p*(1 + p))] // Simplify;

fd = FunctionDomain[func, p]

This is equivalent to requiring that the arguments of Sqrt be positive
fd == Reduce[
  Thread[
   Cases[func, Sqrt[x_] -> x, Infinity] > 0],
  p]

True

fd // N

p < -1.09161 || -0.091608 < p < 0.091608 || p > 1.09161

Plot[func, {p, -5, 2.5},
 Frame -> True,
 Axes -> False,
 PlotPoints -> 101]


text:
Q: Const Class Member Copy Constructor #include "booking.h"
#include <iostream>
booking::booking (  const std::string p_title,  const std::string p_notice,  const category p_category,  const person p_person,  const booking::Type p_type,  const double p_value ) :
m_type{ p_type },
m_title{ p_title },
m_notice{ p_notice },
m_person{ p_person },
m_category{ p_category },
m_value { p_value }
{
    std::cout << "Booking was created" << std::endl; // Debug Message
}

These are the files (everything thats necessary to know in my opinion)
#pragma once
#include <string>
#include "person.h"
#include "category.h"
class booking
{
public:
    enum Type { TYPE_REVENUE, TYPE_EXPENDITURE };
    booking ( const std::string p_title, const std::string p_notice, const category p_category, const person p_person, const booking::Type p_type, const double p_value ); //Basic Constructor
    ~booking();
    Type GetType ( );
    std::string GetTitle ( );
    std::string GetNotice ( );
    category GetCategory ( );
    double GetValue ( );

private:
     Type m_type;
     std::string m_title;
     std::string m_notice;
     category m_category;
     person m_person;
     double m_value;

};

If i put one of the class members (like m_type or the double value, it doesnt matter which) to const, it throws following error:

Fehler    1   error C2280: booking &booking::operator =(const booking &) : attempting to reference a deleted function   C:\Program Files (x86)\Microsoft Visual C++ Compiler Nov 2013 CTP\include\utility   53

I dont get why the compiler complains about the copy constructor and whats basicly the matter.

A: You can't (reasonably) assign to an object of a class that has const members.
That's why you get an error about the copy assignment operator.
You're not getting a complaint about the copy constructor.

In other news:

*

*In C++ ALL UPPERCASE names are a convention for macros. If they're used for anything else (e.g. constants, as in Java) then you increase the risk of name collisions and inadvertent text replacement. Besides it's an eyesore, read by many as extra heavy emphasis. Java doesn't have a preprocessor. C++ does have one.

*It's a good idea to pass non-basic-type arguments in general as reference to const (you only added const). There are some extra considerations for large arguments that are copied. In C++11 these are best passed by value and moved.

*Simple "getter" member function should be declared const so that they can be called on a const object.
Regarding the Java-inspired Get prefixes, consider GetSin(u)+GetCos(v) versus sin(u)+cos(v). In Java a Get prefix can have some value for tools that use introspection. Java has introspection. C++ doesn't have instrospection. The conventions employed should better be adapted to the language used.

A: When you declare a const member, the compiler does not generate a default assignment operator (it has no clue what to do with this member during assignment, after all, it is const ?), you will have to write the assignment operator yourself.
Note:

*

*pass you parameters by reference to const.

A: operator= is not the copy-constructor, it is the assignment operator.
const objects cannot be updated, so in your assignment operator you cannot modify the object.
If you don't declare your own assignment operator, the compiler generates one for you which does member-wise copy. But if there is a const member, this doesn't work, so it can't generate the assignment operator after all. (In C++11 this is called having a deleted assignment operator).
Finally, if you have some code that tries to use the assignment operator, then you get this error about attempting to use the deleted assignment operator.  Some of the standard library containers or algorithms require the assignment operator to be present. You didn't show all your code but somewhere you will have tried to perform an operation that requires assignment.

A: referring this thread, as to the copy constructor with const members,
the general form of the copy constructor is,
class Foo {
Foo( const Foo& f ) :
  mem1( f.mem1 ), mem2( f.mem2 ) /* etc */
{}
};

where mem1 and mem2 are data members of Foo, which can be const
members, non-const members, const references or non-const references.


text:
Q: Can you pull the connectionString for a log4net AdoNetAppender from elsewhere in a web.config file? I already have a db connection string in my web.config file. I scanned the log4net docs, but can't seem to find a way to use it within the log4net section of my web.config file. Is is possible to do something like this?
<connectionStrings>
    <add name="connStr" connectionString="Data Source=localhost; ..." />
</connectionStrings>

<log4net>
    <appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
    <connectionString connectionStringName="connStr"/>
      ...
</log4net>

A: It is possible to use a DB connection string specified in web.config without creating a new class, though you would need to use log4net build that hasn't been released yet. It can be downloaded from SVN repository http://svn.apache.org/viewvc/logging/log4net/trunk/
Your config will look as follows:
<connectionStrings>
    <add name="connStr" connectionString="Data Source=localhost; ..." />
</connectionStrings>

<log4net>
    <appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
    <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
    <connectionStringName value="connStr" />
      ...
</log4net>

Please note that connectionType still needs to be specified.

A: fyi this will be implemented in 1.2.11 according to this. however I have no idea when they are going to release it.

A: the answers above all do not work. i got another solution for this, i tried and it worked:
private static void ConfigureLog4Net()
{
    Hierarchy hierarchy = LogManager.GetRepository() as Hierarchy;
    if(hierarchy != null && hierarchy.Configured)
    {
        foreach(IAppender appender in hierarchy.GetAppenders())
        {
           if(appender is AdoNetAppender)
           {
               var adoNetAppender = (AdoNetAppender)appender;
               adoNetAppender.ConnectionString = ConfigurationManager.AppSettings["YOURCONNECTIONSTRINGKEY"].ToString();
               adoNetAppender.ActivateOptions(); //Refresh AdoNetAppenders Settings
           }
        }
    }
}

How i can use the connectionString of the current website for log4Net instead of configuring

A: Create a class that extends AdoNetAppender - say, WebAppAdoNetAppender.  Implement the ConnectionString property in that class, and retrieve the connection string from your web.config file in that property setter.
<log4net>
    <appender name="AdoNetAppender" type="MyApp.WebAppAdoNetAppender">
    ...

...
public class WebAppAdoNetAppender : log4net.Appender.AdoNetAppender
{
    public new string ConnectionString
    {
        get { return base.ConnectionString; }
        set { base.ConnectionString = ...   }
    }
}

A: As of 2017 (log4net 2.0.8.0), the following works:
public class MyAdoNetAppender : AdoNetAppender
{
    public MyAdoNetAppender()
    {
        ConnectionString = ...
    }
}

<appender name="AdoNetAppender" type="MyApp.MyAdoNetAppender">

(Very similar to @Michael Petrotta's answer)


text:
Q: UITableView does not work after switching rootViewController? I couldn't find any tutorial that i could understand about switching views but i found out that i can switch them by changing the window's rootViewController property.
The problem is my other view has 2 UITableViews in it, but they don't respond to swipes when the controller just became the rootViewController, but after i turn my ipad 90 degrees the view changes to landscape then it starts to work.
Can anyone tell me how to make them work when the view is loaded?

A: You can't change directly the windows rootViewController property and have it to work, because the system doesn't get notify that that change occurred. That is why the change took effect only when the system asked for that view again.
You need to use a method to change it.  Depending on your architecture you may want to use a method from UIViewController
transitionFromViewController:toViewController:duration:options:animations:completion:

UINavigationController :
setViewControllers:animated:

UIView :
transitionFromView:toView:duration:options:completion:


text:
Q: AWS Lambda with AWS MSK trigger - Role and event source must be in the same account as the cloud function I'm trying to deploy a Lambda function which is triggered by AWS MSK Kafka. I came across this error - Role and event source must be in the same account as the cloud function.
Does this mean that the AWS MSK and the Lambda must be under the same account ?
Isn't there a way to workaround that?
And in case there isn't a workaround:

*

*will implementing an in-code Kafka consumer work?

*what's the recommended way to trigger it? cron expression perhaps? as I won't be aware if new messages arrived to the topic.

Thanks in advance.

A: From https://aws.amazon.com/premiumsupport/knowledge-center/lambda-cross-account-kinesis-stream/

Lambda doesn't currently support cross-account triggers from Kinesis or any stream-based sources.

To get around this, you can follow the recommended architecture from the above link. While it is for Kinesis, the overall structure should remain the same for Kakfa:

*

*In the same account as the Amazon MSK Kafka (Account A), create Lambda function which is triggered by it.

*Invoke the Lambda in another account (Account B) using the Lambda function from Account A.

The above link contains a warning that some benefits of Kinesis Data Streams are not available with this solution, you will need to evaluate whether the same applies for MSK Kafka.


text:
Q: Add random number of key-value pair to dictionary in Python My question is how can I add random number of the {(name, f), (parameters, []}) object to my dictionary with a loop iteration (I see a loop as only way to solve it).
In my example I have only 1 finding specified, but what if I want to have several (random number in a range)?
I have an array of f's and relevant parameters, so I want to have different number of findings each time I'm running the code.
"findings": [{ #constructor for BSON
    "name": f,
    "parameters": [parameters, parameters2, parameters3]
}, {..
}]

A: You could try the following. I am assuming you want a random number of name f (likely f is a str) findings with their associated parameters (a list) appended as a dict to a list (which is the value part of a dictionary with key findings). I am also assuming that you have a function get_params that take an f (name?) argument and returns a list of parameters.
import random

# ...
# get a random number of f's from f_list (your list of f's)
# NOTE: don't get more than you have in the list
max_num_f = min(10, len(f_list))
num_f = random.randint(0, max_num_f)
# get an initial index to take a slice from your f_list
index = random.randint(0, len(f_list) - num_f)

# iterate over slice of f's chosen, get params and add to dict
for f in f_list[index : index+num_f]:
    # if findings key is missing, add it
    if 'findings' not in findings_dict:
        findings_dict['findings'] = []
    # add the findings dict to the list
    findings_dict['findings'].append({'name' : f, 'parameters' : get_params(f)})


text:
Q: VB.net Logic Error This is supposed to be a program that tells how long it would take you to download a given size of file after the user inputs their download speed. intOne doesn't seem to be affected at all by the function that I have created to determine what intOne's value should be. I'm reasonably sure that the equation I'm using is correct.
Public Class Form1

    Private tSize As System.Drawing.Size
    Private checkUserSpeed As Long = 0
    Private checkBitByte As Integer = 0
    Private setSize As Integer = 0
    Private checkUserSize As String = ""
    Private Answer As Double = 0

    Private ReadOnly Property checkDwnldSize() As String
        Get
            Return ComboBox1.Text
        End Get
    End Property

    Function checkDownloadSize(ByVal checkUserSize As String)
        Dim suffixes As New List(Of String)({"b", "k", "m", "g", "t", "p", "e", "z"})
        Dim index As Long = suffixes.IndexOf(checkUserSize.Substring(0, 1).ToLower) > -1
        If index > -1 Then
            Return checkUserSpeed / 1024 ^ index
        Else
            Return False
        End If
    End Function

    Function checkForByte(ByVal checkUserSize)
        If Microsoft.VisualBasic.Right(checkUserSize.ToLower, 7) = "byte(s)" Then
            checkBitByte = 1
            checkDownloadSize(checkUserSize)
            Return True
            End
        Else
            Return False
        End If
        Return checkBitByte
        Return checkUserSpeed
    End Function

    Function checkForBit(ByVal checkUserSize)
        If Microsoft.VisualBasic.Right(checkUserSize.ToLower, 6) = "bit(s)" Then
            checkBitByte = 8
            checkDownloadSize(checkUserSize)
            Return True
            End
        Else
            checkForByte(checkUserSize)
            Return False
        End If
        Return checkBitByte
        Return checkUserSpeed
    End Function

    Function Calculate(ByVal checkUserSpeed, ByVal checkUserSize)
        checkForBit(checkUserSize)

        Return Answer
    End Function

    Private Sub FitContents()
        tSize = TextRenderer.MeasureText(TextBox3.Text, TextBox3.Font)
        TextBox3.Width = tSize.Width + 10
        TextBox3.Height = tSize.Height
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Calculate(Convert.ToInt32(TextBox3.Text), ComboBox3.Text)
        Answer = checkBitByte * ((1024 ^ setSize) / checkUserSpeed)
        TextBox1.Text = Answer
    End Sub

    Private Sub TextBox3_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox3.TextChanged
        Call FitContents()
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Form2.Show()
    End Sub

    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
        Form3.Show()
    End Sub
End Class

Help would be greatly appreciated.

A: You never assign any value to intOne, so it starts with value 0.  So this:
intOne = intOne / 1024 ^ 3

is the same as this:
intOne = 0 / 1024 ^ 3

which is of course this:
intOne = 0

As an aside:

*

*Don't use Dim at the class/form level, use Private.

*Always use As <ReturnType> when decalring you functions

*Turn on Option Strict in your language settings.

*Dim intTwo As Integer = Nothing doesn't do anything useful.  Use
Dim intTwo As Integer = 0 instead.

*Always declare your variables as a type as well (Dim tSize is missing its type)

Followup to your edits:
This:
Function checkForByte(ByVal checkUserSize)

Should be this:
Function checkForByte(ByVal checkUserSize As Long)

Fix this in all places in your code.  Everything should have an As DataType.  If you turned on Option Explict and Option Strict like was suggested the compiler will locate these problems for you.
Next, do not name local variables and/or parameters the same as your class/form level private variables.  I personally prefix my instance variables like this:
Private _checkUserSpeed As Long = 0

Note the underscore.  Some people use a lowercase m instead:
Private mCheckUserSpeed As Long = 0

Pick something and be consistent.  This makes it clear the scope of a variable.
Also this code is bad, the second Return will never be hit:
Return checkBitByte
Return checkUserSpeed

Finally, assuming you are trying to populate the variable _checkUserSpeed with a value, you are still not ever doing it.  Search your code and look for any place you are doing this:
_checkUserSpeed = something

You won't find it.  So that variable will always be 0.
None of these are really VB.NET specific issues.  All of these best-practices would apply equally to C# or any other langue.

A: You should look into cleaning up your code first, to improve readability. Avoid code repetition at all costs. If you think you cannot do otherwise, lean towards data repetition instead, i.e. create an XML file to store your values, but keep the code clean. Any errors you find later will then stand out like white crows.
For example, something like this:
Function checkDownloadSize(ByVal strOne As String)
  Dim suffixes As New List(Of String)({"b", "k", "m", "g", "t", "p", "e", "z"})
  Dim index As Long = suffixes.IndexOf(strOne.Substring(0, 1).ToLower) > -1
  If index > -1 Then
    Return intOne / 1024 ^ index
  Else
    Return False
  End If
End Function

roughly replaces your two pages of checkDownloadSize and checkSize.
Notice how every function here is called only once. If you later decide to swap ToLower with your custom implementation, it needs to be done only once. Not only a performance improvement, it also makes your code more maintainable in the long run.
Another point is that I am not using Microsoft.VisualBasic namespace in the above code, and switched to Substring instead. This will ease your burden with migration to C#, and also make native C# devs understand your code better.


text:
Q: Google Script in Sheets, Reference last row, to find Ticket number and customer number, then use it to find a folder to add a child folder I hope I can explain this clearly.
I have a Googlesheet with a "Ticket" Sheet and a "Customner Data" Sheet.
Ticket sheet has Column A as "Ticket Number", Column B as "Customer Name"
Customer Data Sheet has column A Customer number, Column C "First Name", Column D "Last Name".
I have a script that as each customer is added to a new row it creates a folder in a folder in drive in the format "Lastname Firstname - Customernumber"
What I am trying to do is as a new row is added to the "Ticket" sheet the script can find the customer folder then add child folder named "TicketNumber".
Here is the code I have been trying so you can see where I am stuck. Thank you
    //Global

var googleFolderID = ('DRIVE FOLDER ID');
var ss = SpreadsheetApp.getActive();

function createTicketFolder() {

// identify the sheet where the data resides
var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheetByName("Tickets");

//Select the column we will check for the first blank cell
var columnToCheck = sheet.getRange("A:B").getValues();

// Get the last row based on the data range of a single column.
var lastRow = getLastRowSpecial(columnToCheck);

  //identify the cell that will be used to name the folder
 var ticketNumber = sheet.getRange(lastRow,1,1,1);
  var customerNumber = sheet.getRange(lastRow,2,1,1);

//identify the parent folder the new folder will be in
var parentFolder=DriveApp.getFolderById(googleFolderID);

// Find Customer folder within parentFolder, formatted as "Lastname Firstname - CustomerNumber"
//Need Help here

//create the new folder
var newFolder=customerFolder.createFolder(ticketNumber);

};

function getLastRowSpecial(range){
  var rowNum = 0;
  var blank = false;
  for(var row = 0; row < range.length; row++){

    if(range[row][0] === "" && !blank){
      rowNum = row;
      blank = true;
    }else if(range[row][0] !== ""){
      blank = false;
    };
  };
  return rowNum;
};

The Google sheets
The "Ticket" Sheet

The "Customer Data" Sheet

Google Drive Folder
This is how the google drive folders are formatted.

So from the sheets above I need to find the customer folder and add a subfolder with ticket number as folder name.

A: You need to implement the following steps

*

*Retrieve the customer number from the last entry on Tickets sheet

*Find the row containing this number in the Customer Data sheet with indexOf()

*Retrieve First Name and Last Name in order to reconstruct the name of the customer folder

*Find the folder by name

Sample:
...
//IMPORTANT: retrieve the value!
  var ticketNumber = sheet.getRange(lastRow,1).getValue();
  var customerNumber = sheet.getRange(lastRow,2).getValue();
  //identify the parent folder the new folder will be in
  var parentFolder=DriveApp.getFolderById(googleFolderID);
  var customerSheet = ss.getSheetByName("Customer Data");
  var data = customerSheet.getDataRange().getValues();
  // the following line retrieves all customerIds from the 2-D value range and saves them in the 1-D array "customerIds" - necessary for using indexOf()
  var customerIds = data.map(function(e){return e[0];});
  var index = customerIds.indexOf(customerNumber);
  // if the customer number has been found
  if(index >= 0){
    // Lastname Firstname - Customernumber"
    var folderName = data[index][3] + " " + data[index][2] + " - " + data[index][0];
    //  retrieve the first folder with this name - important: avoid duplicates!
    var customerFolder = parentFolder.getFoldersByName(folderName);//.getFoldersByName(folderName);
    if(customerFolder.hasNext()){
      customerFolder = customerFolder.next();
      //check if ticket folder exists
      var ticketFolder=customerFolder.getFoldersByName(ticketNumber);
      if(ticketFolder.hasNext()){
        var newFolder = ticketFolder.next();
       } else {
        // if it does not exist, create the new folder
        var newFolder=customerFolder.createFolder(ticketNumber);
       }
    }
  }


text:
Q: How do you beat the rocky boss guy? There is a boss battle that I tried a while ago. you had to beat this guy who was in a rock-like track. I was dealing damage, but he seems to regen it back. I was using a Supermonkey. Is my strategy not a good one?

A: The boss in question is Dreadbloon: Armored Behemoth. It starts with a ceramic layer that will 'regrow' three times (each time its HP meter reaches one of the skull indicators). At higher levels it will regain some ceramic armor even between the regrowth points.
Once the ceramic layer is breached, Dreadbloon has the properties of a Lead Bloon, meaning it cannot normally be damaged by sharp projectiles, or even a Super Monkey's laser blasts (the plasma vision and Sun God upgrades should allow a Super Monkey to damage it). Use of a Monkey Village with the X/3 upgrade (Monkey Intelligence Bureau) would also allow all towers within the Village's range to damage Dreadbloon in it's lead state.

A: When I battled it, I used a 2-2 dartling gun (you need depleted bloontonium darts to damage it in its lead form) you should be able to beat him, even on l.v. 2, you should only need to battle him twice.


text:
Q: Looking up values from one dataframe in specific row of another dataframe I'm struggling with a bit of a complex (to me) lookup-type problem.
I have a dataframe df1 that looks like this:
    Grade  Value
0     A     16
1     B     12
2     C      5

And another dataframe (df2) where the values in one of the columns('Grade') from df1 forms the index:
     Tier 1  Tier 2  Tier 3
A      20      17      10
B      16      11       3
C       7       6       2

I've been trying to write a bit of code that for each row in df1, look ups the row corresponding with 'Grade' in df2, finds the smallest value in df2 greater than 'Value', and returns the name of that column.
E.g. for the second row of df1, it looks up the row with index 'B' in df2: 16 is the smallest value greater than 12, so it returns 'Tier 1'. Ideal output would be:
    Grade  Value  Tier
0     A     16    Tier 2
1     B     12    Tier 1
2     C      5    Tier 2

My novice, downloaded-Python-last-week attempt so far has been as follows, which is throwing up all manner of errors and doesn't even try returning the column name. Sorry also about the micro-ness of the question: any help appreciated!
for i, row in input_df1.iterrows():
    Tier = np.argmin(df1['Value']<df2.loc[row,0:df2.shape[1]])

A: df2.loc[df1.Grade].eq(df1.Value, 0).idxmax(1)


text:
Q: How to select recursively from query results? How one can reuse query results in the most efficient manner?
I have two tables: items and relations. Item can be lonely item or it can be a child of another item. The relationships are maintained in relations table. Item is uniquely identified by depNo, itemNo columns. Here is the sample dataset:
create table items
(
itemId int identity (1,1) not null ,
depNo int not null,
itemNo int not null,
name varchar(50),
class int not null, -- 0 - unknown class, 1 - child item
constraint pk_depNo_itemNo primary key (depNo, itemNo)
);

create table relations
(
relId int identity (1,1) not null,
pDepNo int not null,
pItemNo int not null,
cDepNo int not null,
cItemNo int not null,
constraint pk_parent_child primary key (pDepNo, pItemNo, cDepNo, cItemNo)
);

insert into items values (1, 1, 'M1CItem1', 1);
insert into items values (1, 2, 'M1CItem2', 1);
insert into items values (1, 3, 'M1CItem3', 1);
insert into items values (2, 1, 'Master1', 0);
insert into items values (2, 2, 'LItem1', 0);
insert into items values (2, 3, 'LItem2', 0);
insert into items values (2, 4, 'LItem3', 0);
insert into items values (2, 5, 'Master2', 0);
insert into items values (2, 6, 'M2CItem1', 1);
insert into items values (2, 7, 'M2CItem1', 1);

insert into relations values (2, 1, 1, 1);
insert into relations values (2, 1, 1, 2);
insert into relations values (2, 1, 1, 3);
insert into relations values (2, 5, 2, 6);
insert into relations values (2, 5, 2, 7);

The following query selects all items satisfying query criteria or its parents if item is a child:
with qRes as (
select depNo, itemNo, name, class, pDepNo, pItemNo from items
left outer join relations
on depNo = cDepNo
and itemNo = cItemNo
where name like '%Item1'
)
-- select all results where item is not a child
select depNo, itemNo, name, class from qRes where class <> 1
union
-- select all parents of the children
select B.depNo, B.itemNo, B.name, B.class from qRes A
inner join items B
on A.pDepNo = B.depNo
and A.pItemNo = B.itemNo;

Executed query would return:
depNo   itemNo  name    class
2           1   Master1 0
2           2   LItem1  0
2           5   Master2 0

Are there any better ways to approach such a problem?

A: If you only have one level of recursion then your approach is fine, if you will have many levels in the hierarchy then you may want to consider using a recursive approach.
e.g. if I change one of your relationships:
UPDATE  Relations
SET     pItemNo = 6
WHERE   cItemNo = 7

It then makes this row {DepNo: 2, ItemNo: 7, name: M2CItem1} a child of {DepNo: 2, ItemNo: 6, name: M2CItem1}, which in turn is a child of {DepNo: 2, ItemNo: 5, name: Master2}
The following will return both M2CItem1 and Master2
;WITH CTE AS
(   SELECT  depNo, itemNo, name, class, pDepNo, pItemNo, 1 [RecursionLevel]
    FROM    items
            LEFT JOIN relations
                ON DepNo = cDepNo
                AND ItemNo = cItemNo
    WHERE   name like '%Item1'
    UNION ALL
    SELECT  i.depNo, i.itemNo, i.name, i.class, r.pDepNo, r.pItemNo, RecursionLevel + 1
    FROM    CTE i
            INNER JOIN relations r
                ON i.pDepNo = r.cDepNo
                AND i.pItemNo = r.cItemNo
)
SELECT  DISTINCT c.DepNo, c.ItemNo, i.Name, i.Class
FROM    CTE c
        INNER JOIN Items i
            ON COALESCE(c.pDepNo, c.DepNo) = i.DepNo
            AND COALESCE(c.pItemNo, c.ItemNo) = i.ItemNo

However if you only want to return the top most parent you can use:
;WITH CTE AS
(   SELECT  depNo, itemNo, name, class, pDepNo, pItemNo, 1 [RecursionLevel]
    FROM    items
            LEFT JOIN relations
                ON DepNo = cDepNo
                AND ItemNo = cItemNo
    WHERE   name like '%Item1'
    UNION ALL
    SELECT  i.depNo, i.itemNo, i.name, i.class, r.pDepNo, r.pItemNo, RecursionLevel + 1
    FROM    CTE i
            INNER JOIN relations r
                ON i.pDepNo = r.cDepNo
                AND i.pItemNo = r.cItemNo
), CTE2 AS
(   SELECT  c.DepNo, c.ItemNo, i.Name, i.Class, RecursionLevel, MAX(RecursionLevel) OVER(PARTITION BY c.DepNo, c.ItemNo) [MaxRecursionLevel]
    FROM    CTE c
            INNER JOIN Items i
                ON COALESCE(c.pDepNo, c.DepNo) = i.DepNo
                AND COALESCE(c.pItemNo, c.ItemNo) = i.ItemNo
)
SELECT  DepNo, ItemNo, Name, Class
FROM    CTE2
WHERE   Recursionlevel = maxRecursionLevel

This would only return {DepNo: 2, ItemNo: 5, name: Master2} for the row {DepNo: 2, ItemNo: 7, name: M2CItem1} as this is the parent of its parent.
Working Examples on SQL Fiddle
As an aside, I think you should reconsider your schema? What is your identity column for if you are making ItemNo and DepNo a compound primary key? You should probably choose one or the other, not both.

A: You can do the child-parent recursion in the common table expression itself, with a UNION ALL statement, but your approach is pretty much there.
You may want to look at the Hierarchy datatype if you have the option of changing the tables.


text:
Q: LinkedIn Scraping Multiple Pages I know there's dicussions whether scraping LinkedIn is allowed or not; but from following article:
https://www.forbes.com/sites/emmawoollacott/2019/09/10/linkedin-data-scraping-ruled-legal/#787286c31b54
I think it is safe to say that scraping publicly available data from LinkedIn is legal.
Now, I am trying to scrape job searches for a specific job title in a specific region.
So far so good, everything works, except for the limit of the amount of scraped jobs to be 25.
I am trying to use following trick:
Inside the URL I pass a keyword &start=X
with X going from 0, to 25, 50, and so on.
In browser, this allows me to go to the next page view and extract jobs from there.
However, using scrapy this method doesn't work.
The code is as follows:
res = requests.get('https://www.linkedin.com/jobs/search/?keywords={}&location={}&start=25'.format(job, location))

response = TextResponse(res.url, body=res.text, encoding='utf-8')

print("processing:" + response.url)

Output:

processing:https://www.linkedin.com/jobs/search/?keywords=Data+Scientist&location=Brussels&start=0

Even if I hardcode it to 25 (page 2), it sets it to 0.
Any idea on how to solve this?

A: Just disable RedirectMiddleware with a REDIRECT_ENABLED=0 setting on the scrapy shell.
scrapy shell -s REDIRECT_ENABLED=0 "https://www.linkedin.com/jobs/search/?keywords=Data+Scientist&location=Brussels&start=75"

_
2019-10-24 21:50:09 [scrapy.core.engine] DEBUG: Crawled (303) <GET https://www.linkedin.com/jobs/search/?keywords=Data+Scientist&location=Brussels&start=75> (referer: None)
[s] Available Scrapy objects:
[s]   scrapy     scrapy module (contains scrapy.Request, scrapy.Selector, etc)
[s]   crawler    <scrapy.crawler.Crawler object at 0x0684AB30>
[s]   item       {}
[s]   request    <GET https://www.linkedin.com/jobs/search/?keywords=Data+Scientist&location=Brussels&start=75>

In [2]: fetch('https://www.linkedin.com/jobs/search/?keywords=Data+Scientist&location=Brussels&start=50')
2019-10-24 21:56:39 [scrapy.core.engine] DEBUG: Crawled (303) <GET https://www.linkedin.com/jobs/search/?keywords=Data+Scientist&location=Brussels&start=50> (referer: None)

In [3]: fetch('https://www.linkedin.com/jobs/search/?keywords=Data+Scientist&location=Brussels&start=100')
2019-10-24 21:56:49 [scrapy.core.engine] DEBUG: Crawled (303) <GET https://www.linkedin.com/jobs/search/?keywords=Data+Scientist&location=Brussels&start=100> (referer: None)

For example, if you want the redirect middleware to ignore 301 and 302 responses (and pass them through to your spider) you can do this:
class MySpider(CrawlSpider):
    handle_httpstatus_list = [301, 302]

This middleware handles redirection of requests based on response status.
https://docs.scrapy.org/en/latest/topics/downloader-middleware.html#module-scrapy.downloadermiddlewares.redirect


text:
Q: Using an alternative sidebar when creating a Wordpress theme I'm trying to figure out how to load an alternative sidebar in a Wordpress theme I'm creating (I'm a novice, by the way). A very old answer on stackoverflow suggests creating a new sidebar and calling it something like sidebar_alt.php and altering the code as follows:
<?php get_sidebar('alt'); ?>

But that doesn't work for me, it just keeps loading the original sidebar. I read a different answer that said you have to register the alternative sidebar in the functions.php file. Do any of you very nice, smart and helpful people out there know if this is true? If so, what code would I have to add? Or is there another alternative (that doesn't include plugins)?
Many thanks in advance.

A: https://codex.wordpress.org/Function_Reference/get_sidebar
You have created sidebar file with name "sidebar_alt.php" which is wrong you should create it like "sidebar-{name}.php" eg. "sidebar-alt.php".


text:
Q: iPad Multiple Detail Views & Model Tutorial/Example Does anyone know of any sample code or tutorials that implement an iPad split view application that has more than one Detail View in addition to the detail views interacting with a separate model? I ask this because the only examples I have found are of iPad applications that implement multiple detail views but do not interact with any sort of model. Any help is greatly appreciated!

A: Have you seen the MultipleDetailViews Sample code ?


text:
Q: Mailer sólo me manda correo al úlitmo usuario del bucle each Tengo en el método create el código para llamar a competition_mailer, concretamente al método del  cual pongo aquí el código:
def startCompetitionPlaoff(competition)
 @competition = Competition.find(competition.id)
 @competition.users.each do |i|
  @user = User.find(i)
  mail( :to => @user.email, :subject => "Start Competition") do |format|
        format.html
  end
 end
end

Bien, pues en este código, @competition.users es igual a 4. De hecho he comprobado, poniendo puts @user.name despues de la declaración de la instancia del @user, que recorre los 4, pero el mail sólo lo ejecuta en el último de ellos. ¿Alguien podría ayudarme?
Pd: sé que puedo cambiar find por where, pero si lo hago así no funciona.
Gracias!

A: Se envía un solo correo debido a que únicamente estás generando el objeto para enviar el correo, pero no lo estás enviando; para enviarlo debes utilizar deliver, deliver_now o deliver_later, lo cual seguramente lo haces desde donde llamas a competition_mailer (probablemente tu controlador) y, por ende, solo envía el último objeto creado.
Te recomiendo crear un método donde llames competition_mailer por cada usuario en lugar de iterar dentro del mailer. Este método lo puedes agregar en tu controlador o directamente en tu clase Mailer (como método de clase).
En particular mi inclino por la segunda opción (prefiero evitar incluir en el controlador lógica ajena a él); por ejemplo, asumiendo que tu clase Mailer se llame CompetitionMailer y envíes el correo desde la acción create del controlador, podrías hacer lo siguiente:
competition_mailer.rb
class CompetitionMailer < ApplicationMailer
  def self.send_start_competition_email(users)
    users.each do |user|
      startCompetitionPlaoff(user).deliver
    end
  end

  def startCompetitionPlaoff(user)
    @user = user

    mail( :to => @user.email, :subject => "Start Competition") do |format|
      format.html
    end
  end
end

competitions_controller.rb
def create
  # Código para crear el objeto
  CompetitionMailer.send_start_competition_email(@competition.users)
end


text:
Q: How do I draw multiple circles without making them touch in forest? How could I draw two circles in the following tree without making them touch?
I need one circle from State to AspP, and the other only around Mood and the lowest MoodP.
Here is the code for the syntactic tree.
\documentclass[a4paper,12pt, twoside]{report}
\usepackage{tikz-cd}
\usepackage[linguistics]{forest}
\begin{document}
   \begin{forest}
for tree={s sep=10mm, inner sep=0, l=0}
[MoodP
[AspP
[Asp]
[InitP
[Init]
[ProcP
[Proc] [State]]]]
[MoodP
[Mood][,phantom]
]
]
\end{forest}
\end{document}

The result should be like this one, without the two circles touching.

A: You can use fit. Just name the nodes you want to enclose. You can adjust rotate, xscale, yscale and shift for a more precise fit.

\documentclass[a4paper,12pt, twoside]{report}
\usepackage{tikz-cd}
\usepackage[linguistics]{forest}
\begin{document}
   \begin{forest}
for tree={s sep=10mm, inner sep=0, l=0}
[MoodP
[AspP, name=C
[Asp, name=E]
[InitP
[Init]
[ProcP
[Proc, name=F] [State, name=D]]]]
[MoodP, name=A
[Mood, name=B][,phantom]
]
]
\node[draw, ellipse, rotate=-50, xscale=.5, fit = {(A) (B)}]{};
\node[draw, ellipse, rotate=47, xscale=.4, yscale=1.2, fit = {(C) (D) (E) (F)}, shift={(-.7,-.1)}]{};
\end{forest}
\end{document}

If you want true circles, you'll have to change the geometry of your tree a bit. For example:

\documentclass[a4paper,12pt, twoside]{report}
\usepackage{tikz-cd}
\usepackage[linguistics]{forest}
\begin{document}
   \begin{forest}
for tree={s sep=2cm, inner sep=0, l sep=1cm}
[MoodP, s sep=4cm
[AspP
[Asp, name=E]
[InitP
[Init]
[ProcP
[Proc, name=F] [State, name=D]]]]
[MoodP, name=A
[Mood, name=B][,phantom]
]
]
\node[draw, circle, fit = {(A) (B)}]{};
\node[draw, circle, fit = {(D) (E) (F)}]{};
\end{forest}
\end{document}

A: Here's an approach with circles.  I had to include some more phantoms to move the right hand part of the tree to the right.
\documentclass[tikz]{standalone}
\usepackage{tikz-cd}
\usepackage[linguistics]{forest}
\begin{document}
   \begin{forest}
for tree={s sep=10mm, inner sep=0, l=0}
[MoodP
[AspP
[Asp]
[InitP
[Init]
[ProcP
[Proc] [State]]]]
[MoodP
[Mood [,phantom [,phantom][,phantom]]][,phantom]
]
]
\draw (1.9,-1.1) circle [radius=12mm];
\draw (-1.5,-2.7) circle [radius=25mm];
\end{forest}
\end{document}

The location of the circles and the radiuses were just trial-and-error.


text:
Q: How to link to same page and add a GET parameter? Additive GET parameters? I have a page with a table and pagination.
I can flick through the pages with

Now I want to add ordering to the tables.
Date

In the given example, I lose either the pagination or the ordering upon clicking one of the hyperlinks. I need to find a way to make the GET parameters additive. So when I am on page 2, the latter should show
Date

I hope there is a built-in solution for that. I am on Django 1.10, but wouldn't mind upgrading to 1.11 if necessary.

A: The easiest way to that is cath in the urls.py the param of the page and use it in the Paginator object.
p = Paginator(your queryset, N°of record per page)

in the P variable will find the pages of the queryset.
Assign the value to anoter variable
page1 = p.page(1)

and in the template use:
page1.object_list

if you desire you can use https://datatables.net/
for manage all the pages and the order.
for big data see https://datatables.net/examples/data_sources/server_side.html

A: I suggest you to generate the string that you want to append on all links in your view first, and then add them to the links.
Here is an example of how you can use urlencode (Docs) to generate a string of GET parameters.
from urllib import urlencode, quote
from collections import OrderedDict

page_value = 2
sort_value = "date"
order_value = "asc"
query_string = urlencode(OrderedDict(page=page_value, sort=sort_value, order=order_value))

# outputs page=2&sort=date&order=asc


text: Q: Redirect multiple print output to single file in json format using python I have used boto3 to read and print metadata from s3 bucket. As a next step i want to redirect the printed output in a json file and write the json file to s3 bucket. The printed output has 2 fields author and timestamp. I need to append both the printed outputs in 1 file in json format.


text:
Q: How To create a Dialog from clicking a button on a custom dialog? For part of the app I am making. I have a button being selected in an options menu. When that button is clicked, It opens a custom dialog. I need buttons on that custom dialog to open a new Dialog, but for some reason my methodology causes the app to crash. Any assistance would be much appreciated.
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_client_app);

    //Copy and paste this line to onClick methods regarding the edit text dialog
   // textentry = (EditText)findViewById(R.id.entrybox);

  //  Button year = (Button)findViewById(R.id.Year);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.options, menu);
    return true;
}

//Dialog Box for selecting View books in Options Menu
public Dialog ViewBookOptions() {
    AlertDialog.Builder builder =
            new AlertDialog.Builder(this);
    LayoutInflater inflater = this.getLayoutInflater();
    View v = inflater.inflate(R.layout.view_books, null);
    builder.setView(v);
    final AlertDialog dialog = builder.create();
    return dialog;

}

//Dialog boxes for selecting Year, Author, or Title in the ViewBook Dialog Box

public Dialog ViewByYear(){
    AlertDialog.Builder builder =
            new AlertDialog.Builder(this);
    LayoutInflater inflater = this.getLayoutInflater();
    View v = inflater.inflate(R.layout.text_entry, null);
    builder.setView(v);
    final EditText entrybox = (EditText) v.findViewById(R.id.entrybox);
    builder.setPositiveButton("Ok",
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    String entry = entrybox.getText().toString().toLowerCase();
                    //This is Where You Will Populate The ListView With Database Stuff
                }
            });
    builder.setNegativeButton(
            "Cancel",
            new DialogInterface.OnClickListener() {
                        public void onClick(
                                DialogInterface dialog, int id) {
                            dialog.cancel();
                        }
                    });
     AlertDialog dialog = builder.create();
    return dialog;

}

             //Quick Toast for checking stuff
               public void toast(String string){
                 Toast.makeText(this, string, Toast.LENGTH_SHORT).show();
       }
       //All of my button OnClick Methods
         public void allbooks(View view){
      toast("You clicked All books");
       }
           public void year(View view){
     toast("Dialog should open and EditText should change hint text");
     EditText textentry = (EditText)findViewById(R.id.entrybox);
      textentry.setHint("Enter the Year of the Book(s)");
      Dialog dialog = ViewByYear();
     dialog.show();
       }

        // The Options Menu
       @Override
       public boolean
         onOptionsItemSelected
         (MenuItem item) {
            switch (item.getItemId()) {
         case R.id.option1:
            //Change to View Book Options
            Dialog dialog = ViewBookOptions();
            dialog.show();
            return true;
        case R.id.option2:

            return true;
        case R.id.option3:

            return true;
        case R.id.option4:

            return true;
        case R.id.option5:

            return true;
        default:
            return super.onOptionsItemSelected(item);
          }
       }

That is my activity code. I believe the error has something to do with the first dialog not being dismissed before the second dialog is created, but I am unsure how to correct this, because my dialogs are called by different buttons at different instances.

A: Why don't you try out Sweet Alert Dialog Android Library? It supports the use of nested dialogs in code. Here's the link: https://github.com/pedant/sweet-alert-dialog


text:
Q: execute a jsp program on background of a running java program I just want execute my jsp program when a button on my running java program is clicked, it doesn't need to be visible, the jsp program i am saying is for printing and once it is loaded in the browser it will just pop up the print dialog confirm box, so again it doesn't need to be visible, once the button in my java program is clicked the print dialog will just pop up and that's it. By the way i am new here in this site, and also know only basics of java, so i do not have any idea how to do it, but i like to do it that way and with just a link of the jsp page from the localhost, something like that,
Thanks in advance buddies! Hope you will help me!...

A: this should be working , cant be sure if it serves properly , please assure me the outcome
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

    public class callURL {
    public static void main(String[] args)
    {
        String url = "http://localhost:8080/OpenID/asd.html";
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        HttpResponse response;
        StringBuilder builder= new StringBuilder();
        try
        {
            response = httpClient.execute(httpPost);
            BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
            char[] buf = new char[8000];
            int l = 0;
                while (l >= 0)
                {
                    builder.append(buf, 0, l);
                    l = in.read(buf);
                }

        }
        catch (ClientProtocolException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}

for this java program to ececute your jsp
you have to add this line in your jsp page
<script>
window.location.href="http://localhost:8080/OpenID/asd.html"
</script>

where OpenId : Application Name
asd.html is your jsp page , the same jsp which you are calling from java program


text:
Q: Why HttpPost was causing a /undefine redirect in some browsers Backstory:
I recently had a problem where when I clicked my delete button on my MVC page to delete a record it would remove the record but instantly redirect to localhost/undefined at no call to any redirects. I was using a JQuery AJAX call on button click to post with the delete action returning a Json(new { Success = true });. This worked perfectly in FireFox and IE (both 32bit and 64bit versions), however; it caused the redirect to localhost/undefined in Chrome, Opera, and Safari browsers.
I solved this problem by removing the [HttpPost] attribute on my delete action on my controller.
Code: (HTML/Razor)
<button name="Estimate" type="submit" class="deleteEntity" tabindex="-1" data-bind="attr: { href: '/Estimate/Select?EntityID=' + ko.utils.unwrapObservable($data.ID) }" style="padding: 0px 0px 0px 0px;background-color: #FFFFFF;border-color: #FFFFFF;margin-bottom: 0px;">
    <img src="/Content/Images/red-x.png" />
</button>

Code: (AJAX)
// Delete button clicked
function deleteEntity(e) {
    e.preventDefault();

    var name = $(this).attr("name");
    var index = $(".deleteEntity[name=" + name + "]").index($(this));
    var entityId = ko.utils.unwrapObservable(viewModel.model.peek()[index].ID);
    var data = { EntityID: entityId };

    viewModel.model.remove(viewModel.model.peek()[index]);

    if (entityId > 0) {
        $.ajax({
            url: "/" + name + "/Delete",
            type: "POST",
            data: data,
            dataType: 'json',
            async: true,
            success: function (data, textStatus, xhr) {
                alert(data);
            },
            error: function (xhr, textStatus, errorThrown) {
                // Decide later.
            }
        });
    }
}

$(document).on("click", ".deleteEntity", deleteEntity);

Code: Action (Before fixing the problem)
/// <summary>
/// POST: Deletes the specified entity from the database.
/// </summary>
[HttpPost]
public ActionResult Delete(Int32? EntityID )
{
    // Delete the estimate given its ID.
    if ((EntityID ?? 0) > 0)
    {
        Db.DeleteEntity(EntityID ?? 0);

        if (EntityID == this.ActiveSelection.EstimateID)
        {
            this.ActiveSelection = null;
        }
    }

    return Json(new { Success = true });
}

Question(s):

*

*Why was I getting a random redirect to localhost/undefined (in select browsers) from it solely being (what I assume as) mislabeled (i.e. [HttpPost] instead of [HttpGet])?

*Shouldn't it be an [HttpPost] request? Would delete not be a Post? I'm guessing that I was doing something wrong on this? Might someone have an explanation?

*If so, Was I simply just performing the HttpPost wrong? How would I go about doing the HttpPost so that it doesn't cause the random redirect?

I have my suspicions of where I went wrong, but am not certain for sure and still don't fully understand why it caused the error or what about that part was wrong.
Network Tab Header for Delete:
This is while stopped on a breakpoint at the AJAX Success function alert(data);.
Remote Address:127.0.0.1:59635
Request URL:http://localhost:59635/Estimate/Delete
Request Method:POST
Status Code:200 OK
Request Headersview source
Accept:application/json, text/javascript, */*; q=0.01
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:11
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Cookie:ASP.NET_SessionId=xwxxnwy3ke2zvtztnnsngz3a
Host:localhost:59635
Origin:http://localhost:59635
Referer:http://localhost:59635/
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.114 Safari/537.36
X-Requested-With:XMLHttpRequest
Form Dataview sourceview URL encoded
EntityID:25
Response Headersview source
Cache-Control:private
Connection:Close
Content-Length:16
Content-Type:application/json; charset=utf-8
Date:Mon, 09 Jun 2014 17:53:37 GMT
Server:ASP.NET Development Server/10.0.0.0
X-AspNet-Version:4.0.30319
X-AspNetMvc-Version:4.0

A: ugh. I had this little baby I forgot about....
/* Entity Selection */
function onImageClick(e) {
var image = $(this);
var link = $(image).attr("href");

window.location.href = link;
}

// Enabled onClick events.
$(document).on("click", "tbody tr td img", onImageClick); // Solved the problem by adding ".selectEntity" to the selector.

I think it kind of explains itself why I was having issues. cough cough. Sorry about that. Thank you for all that commented trying to help.


text:
Q: AngularJS: Directive unable to use function for templateUrl Thanks in advance for helping out a newbie to the world of angular.
Using angularjs 1.2.23 it seems that within a directive it should be able to set the templateUrl using a function.
Currently the following code works fine using a simple string as the template URL:
'use strict';

define(['angular'], function (angular) {

var myModule = angular.module('myModule',[]);

myModule.directive("myDirective", function() {
return {
    restrict : "A",
    templateUrl: '/app/some/directory/template.html',
    link: function(scope, elem, attrs, ctrl) {

        elem.find('a.modal-trigger').bind('click', function(e) {
            elem.find('div.modal').modal('show');
            e.preventDefault();
        });

        elem.find('a.modal-close').bind('click', function(e) {
            elem.find('div.modal').modal('hide');
            e.preventDefault();
        });

    }
};
});

return myModule;

});

However when a function is put in place of the string (following the documentation and examples others have provided in other places on the web), then the function code itself is returned.
  templateUrl: function(elem, attr){
    return '/app/some/directory/template.html';
  }

For example, thus is what the request URL shows when the templte is called in:
http://myserver.com/function%20()%7Breturn%20'/app/some/directory/template.html'%7D

I've tried quite a few things, including playing with compile, but can't seem to get it to work.
Does this work in 1.2.23 (people say it was since 1.1.4)? I assume it does, and that I'm just doing it wrong.


text:
Q: Open files from Linux bash shell on Windows 10 Using Windows 10 and I have the Linux Bash Shell to use with Jekyll.
All I am looking to do is open the explorer or filesystem to copy some files. Does anyone know how you browse the file explorer with the shell or achieve what I want in another way?
I am looking to open a path which lives on
/var/lib/gems/2.3.0/gems/minima-2.5.0

Essentially I want to do the Linux Bash Shell (Windows 10) equivalent of
explorer /var/lib/gems/2.3.0/gems/minima-2.5.0

I installed nautilus
str@DESKTOP-SMMADM5:/mnt/c/WorkingProjects/personal$ sudo apt install nautilus
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following additional packages will be installed:
  adwaita-icon-theme at-spi2-core colord colord-data dbus-x11 dconf-gsettings-backend dconf-service desktop-file-utils
  fontconfig gcr glib-networking glib-networking-common glib-networking-services gnome-desktop3-data gnome-keyring
  gsettings-desktop-schemas gvfs gvfs-backends gvfs-common gvfs-daemons gvfs-libs hicolor-icon-theme
  humanity-icon-theme hwdata libarchive13 libassuan0 libatasmart4 libatk-bridge2.0-0 libatk1.0-0 libatk1.0-data
  libatspi2.0-0 libavahi-client3 libavahi-common-data libavahi-common3 libavahi-glib1 libboost-filesystem1.58.0
  libboost-system1.58.0 libcairo-gobject2 libcairo2 libcapnp-0.5.3 libcdio-cdda1 libcdio-paranoia1 libcdio13
  libcolord2 libcolorhug2 libcups2 libdatrie1 libdbusmenu-glib4 libdconf1 libdee-1.0-4 libegl1-mesa libepoxy0
  libexempi3 libexif12 libgail-3-0 libgbm1 libgck-1-0 libgcr-3-common libgcr-base-3-1 libgcr-ui-3-1 libgd3
  libgdata-common libgdata22 libgdk-pixbuf2.0-0 libgdk-pixbuf2.0-common libgnome-desktop-3-12 libgoa-1.0-0b
  libgoa-1.0-common libgphoto2-6 libgphoto2-l10n libgphoto2-port12 libgraphite2-3 libgtk-3-0 libgtk-3-bin
  libgtk-3-common libgudev-1.0-0 libgusb2 libharfbuzz0b libieee1284-3 libimobiledevice6 libjbig0 libjpeg-turbo8
  libjpeg8 libjson-glib-1.0-0 libjson-glib-1.0-common liblcms2-2 libldb1 libmediaart-2.0-0 libmirclient9 libmircommon7
  libmircore1 libmirprotobuf3 libmtp-common libmtp-runtime libmtp9 libnautilus-extension1a libnotify4 libnspr4 libnss3
  libnss3-nssdb liboauth0 libp11-kit-gnome-keyring libpam-gnome-keyring libpango-1.0-0 libpangocairo-1.0-0
  libpangoft2-1.0-0 libpixman-1-0 libplist3 libprotobuf-lite9v5 libproxy1v5 libpython2.7 librest-0.7-0 librsvg2-2
  librsvg2-common libsane libsane-common libsecret-1-0 libsecret-common libsmbclient libsoup-gnome2.4-1 libsoup2.4-1
  libtalloc2 libtdb1 libtevent0 libthai-data libthai0 libtiff5 libtracker-sparql-1.0-0 libudisks2-0
  libunity-protocol-private0 libunity-scopes-json-def-desktop libunity9 libusbmuxd4 libvpx3 libwayland-client0
  libwayland-cursor0 libwayland-egl1-mesa libwayland-server0 libwbclient0 libxapian22v5 libxcb-render0 libxcb-shm0
  libxcb-xfixes0 libxkbcommon0 libzeitgeist-2.0-0 nautilus-data notification-daemon p11-kit p11-kit-modules
  pinentry-gnome3 python-talloc samba-libs session-migration ubuntu-mono udisks2 usbmuxd zeitgeist-core
Suggested packages:
  colord-sensor-argyll bluez-obexd samba-common lrzip cups-common libgd-tools gphoto2 libusbmuxd-tools liblcms2-utils
  librsvg2-bin avahi-daemon hplip libsane-extras sane-utils unity-common xapian-tools brasero eog evince | pdf-viewer
  totem | mp3-decoder tracker gnome-sushi pinentry-doc reiserfsprogs exfat-utils zeitgeist-datahub
The following NEW packages will be installed:
  adwaita-icon-theme at-spi2-core colord colord-data dbus-x11 dconf-gsettings-backend dconf-service desktop-file-utils
  fontconfig gcr glib-networking glib-networking-common glib-networking-services gnome-desktop3-data gnome-keyring
  gsettings-desktop-schemas gvfs gvfs-backends gvfs-common gvfs-daemons gvfs-libs hicolor-icon-theme
  humanity-icon-theme hwdata libarchive13 libassuan0 libatasmart4 libatk-bridge2.0-0 libatk1.0-0 libatk1.0-data
  libatspi2.0-0 libavahi-client3 libavahi-common-data libavahi-common3 libavahi-glib1 libboost-filesystem1.58.0
  libboost-system1.58.0 libcairo-gobject2 libcairo2 libcapnp-0.5.3 libcdio-cdda1 libcdio-paranoia1 libcdio13
  libcolord2 libcolorhug2 libcups2 libdatrie1 libdbusmenu-glib4 libdconf1 libdee-1.0-4 libegl1-mesa libepoxy0
  libexempi3 libexif12 libgail-3-0 libgbm1 libgck-1-0 libgcr-3-common libgcr-base-3-1 libgcr-ui-3-1 libgd3
Setting up libgoa-1.0-0b:amd64 (3.18.3-1ubuntu2) ...
Setting up libnspr4:amd64 (2:4.13.1-0ubuntu0.16.04.1) ...
Setting up libgdata-common (0.17.4-1) ...
Setting up libplist3:amd64 (1.12-3.1ubuntu0.16.04.1) ...
Setting up libusbmuxd4:amd64 (1.0.10-2ubuntu0.1) ...
Setting up libimobiledevice6:amd64 (1.2.0+dfsg-3~ubuntu0.2) ...
Setting up hwdata (0.267-1) ...
Setting up libdbusmenu-glib4:amd64 (16.04.1+16.04.20160927-0ubuntu1) ...
Setting up libgphoto2-l10n (2.5.9-3) ...
Setting up libmediaart-2.0-0:amd64 (1.9.0-2) ...
Setting up libmtp-runtime (1.1.10-2ubuntu1) ...
Setting up libtracker-sparql-1.0-0:amd64 (1.6.2-0ubuntu1.1) ...
Setting up libunity-protocol-private0:amd64 (7.1.4+16.04.20180209.1-0ubuntu1) ...
Setting up libunity-scopes-json-def-desktop (7.1.4+16.04.20180209.1-0ubuntu1) ...
Setting up libunity9:amd64 (7.1.4+16.04.20180209.1-0ubuntu1) ...
Setting up session-migration (0.2.3) ...
Setting up nautilus-data (1:3.18.4.is.3.14.3-0ubuntu6) ...
Setting up usbmuxd (1.1.0-2) ...
Warning: The home dir /var/lib/usbmux you specified can't be accessed: No such file or directory
Adding system user `usbmux' (UID 113) ...
Adding new user `usbmux' (UID 113) with group `plugdev' ...
Not creating home directory `/var/lib/usbmux'.
Setting up libgtk-3-bin (3.18.9-1ubuntu3.3) ...
Setting up adwaita-icon-theme (3.18.0-2ubuntu3.1) ...
update-alternatives: using /usr/share/icons/Adwaita/cursor.theme to provide /usr/share/icons/default/index.theme (x-curs
or-theme) in auto mode
Setting up humanity-icon-theme (0.6.10.1) ...
Setting up libnss3-nssdb (2:3.28.4-0ubuntu0.16.04.3) ...
Setting up libnss3:amd64 (2:3.28.4-0ubuntu0.16.04.3) ...
Setting up liboauth0:amd64 (1.0.3-0ubuntu2) ...
Setting up libgdata22:amd64 (0.17.4-1) ...
Setting up ubuntu-mono (14.04+16.04.20180326-0ubuntu1) ...
Setting up libgtk-3-common (3.18.9-1ubuntu3.3) ...
Setting up libgtk-3-0:amd64 (3.18.9-1ubuntu3.3) ...
Setting up libgcr-ui-3-1:amd64 (3.18.0-1ubuntu1) ...
Setting up gcr (3.18.0-1ubuntu1) ...
Setting up pinentry-gnome3 (0.9.7-3) ...
Setting up gnome-keyring (3.18.3-0ubuntu2) ...
Setting up gvfs-backends (1.28.2-1ubuntu1~16.04.2) ...
Setting up libgail-3-0:amd64 (3.18.9-1ubuntu3.3) ...
Setting up libgnome-desktop-3-12:amd64 (3.18.2-1ubuntu1) ...
Setting up libnautilus-extension1a:amd64 (1:3.18.4.is.3.14.3-0ubuntu6) ...
Setting up nautilus (1:3.18.4.is.3.14.3-0ubuntu6) ...
Setting up notification-daemon (3.18.2-1) ...
Processing triggers for libc-bin (2.23-0ubuntu10) ...
Processing triggers for libgdk-pixbuf2.0-0:amd64 (2.32.2-1ubuntu1.4) ...
Processing triggers for dbus (1.10.6-1ubuntu3.3) ...

But when I try and open the path I get
str@DESKTOP-SMMADM5:/mnt/c/WorkingProjects/personal$ nautilus /var/lib/gems/2.3.0/gems/minima-2.5.0
Failed to connect to Mir: Failed to connect to server socket: No such file or directory
Unable to init server: Could not connect: Connection refused

(nautilus:6622): Gtk-WARNING **: cannot open display:

EDIT :
Installed xdg-utils (Thanks Brydon) which did not work and gave the following output here
stradled@DESKTOP-SMMADM5:/mnt/c/WorkingProjects/personal$ xdg-open /var/lib/gems/2.3.0/gems/minima-2.5.0
Unescaped left brace in regex is deprecated, passed through in regex; marked by <-- HERE in m/%{ <-- HERE (.*?)}/ at /usr/bin/run-mailcap line 528.
Error: no "view" mailcap rules found for type "inode/directory"
/usr/bin/xdg-open: 778: /usr/bin/xdg-open: www-browser: not found
/usr/bin/xdg-open: 778: /usr/bin/xdg-open: links2: not found
/usr/bin/xdg-open: 778: /usr/bin/xdg-open: elinks: not found
/usr/bin/xdg-open: 778: /usr/bin/xdg-open: links: not found
/usr/bin/xdg-open: 778: /usr/bin/xdg-open: lynx: not found
/usr/bin/xdg-open: 778: /usr/bin/xdg-open: w3m: not found
xdg-open: no method available for opening '/var/lib/gems/2.3.0/gems/minima-2.5.0'

A: No need for anything fancy like suggested in other answers, wsl and windows has great support for opening windows files and apps from within WSL and visa versa.
Firstly remember you should not open and mess with linux files from windows (link). But for windows files and folders (for example: \mnt\c...) you can open these with start .
For this to work you will need an alias in your linux env set like this
alias start='cmd.exe /c start'

If do want to manipulate files in the linux filesystem you could use a dual pane console file manager like midnight commander

A: I ran into the same issue with Hashicorp Vault in WSL.
I created a script that basically forwards xdg-open to powershell -c start
Not tested much though.
sudo tee /usr/local/bin/xdg-open <<EOF
#!/bin/sh

powershell.exe -c start "'\$@'"
EOF
sudo chmod +x /usr/local/bin/xdg-open

Then xdg-open https://google.com should work.

A: Edit: I didn't realize this was on WSL, this will not work unless there is a display server
xdg-open does seem to work on a directory (if you don't know what your default file explorer is).
xdg-open /var/lib/gems/2.3.0/gems/minima-2.5.0

The only input I have in the nautilus issue is to ensure that you're spelling it correctly and the install is actually working (not throwing an error). Read carefully through the output of apt-get install nautilus or post it here.


text:
Q: AWS Lambda Json Serializer is removing trailing zeros from milliseconds in a date time input I have created an AWS lambda with C# .net core 3.1. This lambda takes a json object as input and one of the property names of the json object is a datetime. Look below for example input
{
    "datetime": "2022-05-10T11:49:21.120Z",
    "context": {
        "user": "{\"Id\": \"user_id\"}"
    }
}

C# lambda handler:
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))]
namespace LambdaFunction
{
    public class Function
    {
        public async Task<JObject> FunctionHandler(JObject event, ILambdaContext context)
        {
            context.Logger.LogLine("Event Details: " + JsonConvert.SerializeObject(event));
            string dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'";
            var dateString = JToken.ReadFrom(jr)["AsOfDatetime"].ToString();
            if (!DateTime.TryParseExact(dateString, dateFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime dateValue))
            {
                throw new Exceptopm("datetime is not in UTC format");
            }
        }
    }
}

I logged the input event inside the lambda and it printed the below value
{
    "datetime": "2022-05-10T11:49:21.12Z",
    "context": {
        "user": "{\"Id\": \"user_id\"}"
    }
}

The trailing 0 in datetime key's milliseconds before Z (representing UTC) got removed 2022-05-10T11:49:21.120Z to 2022-05-10T11:49:21.12Z. I am trying to validate the input date time using DateTime.TryParse as in the above code. But because the serializer is removing the trailing zeros and I'm using .fff in the format, it's throwing error even when I give correct input if the input datetime has trailing zeros. I am going to later on store this date time in database and I want to store milliseconds to exactly 3 decimals. So, how can I prevent the serializer from removing the trailing zeros?
I'm sure we can write some code to add zeros at the end and achieve what we want but it just seems like extra work. Why do the trailing zeros even get removed by the serializer?


text:
Q: Five exponentials theorem The six exponentials theorem is proved in most textbooks on transcendental number theory, and the four exponent conjecture is an open problem.
Is there any good/accessible exposition of the five exponentials theorem?

A: Waldschmidt, M.: On the transcendence methods of Gel'fond and Schneider in several variables. New advances in transcendence theory
(Durham, 1986), 375-398, Cambridge Univ. Press, Cambridge-New York,
1988
Waldschmidt, M.: Diophantine Approximation on Linear Algebraic Groups. Transcendence Properties of the Exponential Function in Several Variables. Springer, Berlin/Heidelberg, 2000
https://webusers.imj-prg.fr/~michel.waldschmidt/texts.html


text:
Q: sql netezza case when, how to use a temporal variable? How can i make this kind of CASE WHEN in Netezza:
select
  case A+B+C
  when 0 then 1
  else A+B+C
end
FROM X

the idea is not to write again A+B+C like this
select
  case 's' = A+B+C
  when 0 then 1
  else 's'
end
FROM X

is it possible?

A: In Netezza, you can use the following syntax to avoid repeating the expression A+B+C in your CASE statement:
SELECT CASE WHEN A+B+C = 0 THEN 1 ELSE A+B+C END FROM X;

This will check if the sum of A, B, and C is equal to 0. If it is, then it will return 1. Otherwise, it will return the sum of A, B, and C.
You can also use a subquery to calculate the sum of A, B, and C and then use it in the CASE statement:
SELECT CASE WHEN sum_abc = 0 THEN 1 ELSE sum_abc END
FROM (
  SELECT A+B+C as sum_abc
  FROM X
) subquery;

This will first calculate the sum of A, B, and C in the subquery and then use it in the outer query's CASE statement.