text:
Q: How do I keep syntax highlighting for a buffer for the duration of a vim session When I open a file
 :e x

and change its filetype
 :set ft=plsql

I can see the effect of setting the filetype because the keywords in the buffer are highlighted according to the filetype (syntax) that I just set.
Then, I open another file
 :e y

and switch back to the file where I set the filetype
 :e #

the keyword-highlightening is lost, although the filetype is still in effect.
 :set ft?

confirms the file type is plsql.
So, how can I make vim so that it keeps the highlighting when I switch back to the file?

A: I assume you have set nohidden (or rather, don't have set hidden). This means, any buffer that is not displayed somewhere is unloaded. Thus, :e y will make Vim completely forget about x. When you do :e #, you don't return to x: you reload it. Since it's a completely new buffer, your filetype is, of course, not there.
If you did have set hidden, opening y would not unload x even if it is not being displayed anywhere, and :e # would simply display the buffer containing x (which already has the filetype set). This also has the benefit of making Vim much less annoying, since you can load other files without having to write the current changes to disk (and without the constant pestering from Vim if loading another file when you have unsaved changes is something you really wanted to do).
EDIT: The explanation seems to be bogus. The fix is still set hidden. Go figure.


text:
Q: AJAX received datas size (responseText.length) is smaller than the original file size? I would like to check received datas via an AJAX request in javascript.
To do that I need to check the size of the received datas and compare it with the original file size on the server.
var xhr_object = new XMLHttpRequest();
... // Send AJAX request
var RetAjax = xhr_object.responseText;
console.log(RetAjax.length);

I have tested with different type of files.

*

*With images files as jpeg, the AJAX received datas size is about 70% of the original size.

*With a Text file, this is about 96%.
But there is an interesting thing I can see with the following test :

I have tried to encode first the Text file in ANSI format and then in UTF-8 without BOM. Please see results on the table below.
Encodage --- ORG File Size --- AJAX Datas Size
ANSI ---------- 4,792 Bytes ------ 4,506 Bytes
UTF-8 --------- 4,986 Bytes ------ 4,792 Bytes
As we can see, the file size is the same between the ANSI ORG file and the UTF-8 AJAX received datas.
So my questions are :

*

*What is the relationship between the original file size and the AJAX received datas ?

*Is there an encoding problem with TEXT files between client and server ?

*What about with other types of files as image files ? Is there a way to check the right file size ?

Thanks in advance for your answers.
Regards

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to make a variable in a struct variable that is not inputted but set based on previous variables' values I am making a program which inputs fractions and puts them in order. I used struct to define a fraction type. I think I am making a type that initializing 2 variables(the numerator and the denominator of the fraction) and initializing the double type variable called value to a / b in this code:
struct fraction {
    int a; // numerator
    int b; // denominator
    double value = a / b; // floating point value of fraction
    bool operator > (const fraction &a) {
        fraction ans;
        return ans.value > a.value;
    }
    bool operator < (const fraction &a) {
        fraction ans;
        return ans.value < a.value;
    }

};

int main() {
//---------logging-------
    fraction ratio = {1,2};
    cout << ratio.value;
//-----------------------
    // outputs 0
    // other things down here that is not included
}

but apparently, that is not the case because I also need to initialize value. I figured out why, but the problem is, how can I make the variable without initializing it at the creation of the fraction? Thanks!

A:
How can I make the variable without initializing it at the creation of the fraction?

One could just write a member function double value() calculating and returning the floating-point value of the fraction, but first there are some issues in the posted code that need to be addressed (and may actually solve OP's problem).

*

*The only in-class member variable initialization shown isn't correct.
double value = a / b; // floating point value of fraction

Beeing both a and b variables of type int, a / b is an integer division, yielding an int result that is only after assigned to a double variable. In OP's example, int(1)/int(2) == int(0).
To produce the expected value, we need to explicitly convert at least one of the terms into a double:
double value = static_cast<double>(a) / b;

*Both the comparison operators are wrong.
bool operator > (const fraction &a) {
      fraction ans;                // This is a LOCAL, UNINITIALIZED varible.
      return ans.value > a.value;  // The result is meaningless.
}

The following snippet shows a possible implementation where value is calculated and not stored (which isn't necessary a good idea).
#include <iostream>
#include <numeric>

class fraction
{
    int numerator_{};
    int denominator_{1};

public:
    fraction() = default;
    fraction(int num, int den)
        : numerator_{num}, denominator_{den}
    {
        if (auto divisor = std::gcd(num, den); divisor != 1)
        {
            numerator_ /= divisor;
            denominator_ /= divisor;
        }
    }

    bool operator > (fraction const& a) const noexcept {
        return value() > a.value();
    }

    bool operator < (fraction const& a) const noexcept {
        return value() < a.value();
    }

    auto numerator() const noexcept {
        return numerator_;
    }

    auto denominator() const noexcept {
        return denominator_;
    }

    double value() const noexcept {
        return static_cast<double>(numerator_) / denominator_;
    }
};

A: I think there are two solutions, either you initialize a and b with 0, or you compute a/b each time you need it.
...or you could write an exception like:
int a;
int b;
double val;

try() { val = a/b; }
catch(...){ val = 0; }

I don't think that's good tho because it's always gong to catch.


text:
Q: Ruby on Rails - rails server exits immediately after starting (SystemStackError) I have set up Ruby on Rails using Windows 10 bash in C drive. I've used rbenv to set it up and updated my ruby version to 2.4.0. Then, I updated the rails version to 4.2.6 and ran bundle update to update my gem, and I ran rails server, but it's not starting the server. Instead, it exits the server immediately and it shows me the following error:

/home/yschang/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/thread_safe-0.3.5/lib/thread_safe/cache.rb:155: warning: constant ::Fixnum is deprecated
  /home/yschang/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/thread_safe-0.3.5/lib/thread_safe/cache.rb:155: warning: constant ::Fixnum is deprecated
  /home/yschang/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/fspath-3.0.1/lib/fspath.rb:154: warning: constant ::Fixnum is deprecated
  => Booting Thin
  => Rails 4.2.7.1 application starting in development on http://localhost:3000
  => Run rails server -h for more startup options
  => Ctrl-C to shutdown server
  /home/yschang/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/thread_safe-0.3.5/lib/thread_safe/cache.rb:155: warning: constant ::Fixnum is deprecated
  /home/yschang/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/activesupport-4.2.7.1/lib/active_support/core_ext/numeric/conversions.rb:121: warning: constant ::Fixnum is deprecated
  /home/yschang/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/activesupport-4.2.7.1/lib/active_support/core_ext/numeric/conversions.rb:121: warning: constant ::Bignum is deprecated
  Exiting
  /home/yschang/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/activesupport-4.2.7.1/lib/active_support/core_ext/numeric/conversions.rb:124:in block (2 levels) in <class:Numeric>': stack level too deep (SystemStackError)
          from /home/yschang/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/activesupport-4.2.7.1/lib/active_support/core_ext/numeric/conversions.rb:131:inblock (2 levels) in '
          from /home/yschang/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/activesupport-4.2.7.1/lib/active_support/core_ext/numeric/conversions.rb:131:in block (2 levels) in <class:Numeric>'
          from /home/yschang/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/activesupport-4.2.7.1/lib/active_support/core_ext/numeric/conversions.rb:131:inblock (2 levels) in '
          from /home/yschang/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/activesupport-4.2.7.1/lib/active_support/core_ext/numeric/conversions.rb:131:in block (2 levels) in <class:Numeric>'
          from /home/yschang/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/activesupport-4.2.7.1/lib/active_support/core_ext/numeric/conversions.rb:131:inblock (2 levels) in '
          from /home/yschang/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/activesupport-4.2.7.1/lib/active_support/core_ext/numeric/conversions.rb:131:in block (2 levels) in <class:Numeric>'
          from /home/yschang/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/activesupport-4.2.7.1/lib/active_support/core_ext/numeric/conversions.rb:131:inblock (2 levels) in '
          from /home/yschang/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/activesupport-4.2.7.1/lib/active_support/core_ext/numeric/conversions.rb:131:in block (2 levels) in <class:Numeric>'
           ... 5011 levels...
          from /home/yschang/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/railties-4.2.7.1/lib/rails/commands/commands_tasks.rb:39:inrun_command!'
          from /home/yschang/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/railties-4.2.7.1/lib/rails/commands.rb:17:in <top (required)>'
          from bin/rails:4:inrequire'
          from bin/rails:4:in `'

Any help is greatly appreciated. Thanks.

A: In Ruby 2.3.x or earlier, there's a base class Integer which you don't instantiate or address directly. Instead, you address the supposed-fast Fixnum with limited precision or the supposed-slower Bignum which can handle very large numbers.
In Ruby 2.4.0, the maintainers made the genuinely astonishing decision to 'deprecate' Fixnum and Bignum, rolling them both into Integer. Any code using Fixnum or Bignum will get a warning. Any tests or other code introspecting on for example the class of 42 will get the answer Integer instead of Fixnum.
This is a very, very difficult change to handle in real world code (e.g. a gem) that wants to run on both Ruby 2.3.x or earlier, or 2.4.0 or later.
Rails 4.2 predates Ruby 2.4 and I don't know if it is fully compatible. My guess is that downgrading your system's Ruby to 2.3.3 will clear your issues. It'll certainly get rid of all the warnings polluting your console and, if the crash still happens, give a better chance of seeing a relevant message giving away the root cause.


text:
Q: Use dedicated gpu only on laptop running Ubuntu 20.04 I'm working on an Acer Nitro 5 515-43 with a dedicated NVIDIA GTX 1650 and an integrated AMD GPU.
I want to use the dedicated GPU all the time. However the system uses the integrated one instead. What can I do to change this?
Since the integrated GPU is an AMD one, the optimus/prime solution shouldn't work.
Here is some additional information about the GPUs:
$ lspci -nn | grep -E 'VGA|Display'
05:00.0 VGA compatible controller [0300]: Advanced Micro Devices, Inc. [AMD/ATI] Picasso [1002:15d8] (rev c2)

$ glxinfo -B
name of display: :1
display: :1  screen: 0
direct rendering: Yes
Extended renderer info (GLX_MESA_query_renderer):
    Vendor: X.Org (0x1002)
    Device: AMD RAVEN (DRM 3.35.0, 5.4.0-39-generic, LLVM 9.0.1) (0x15d8)
    Version: 20.0.4
    Accelerated: yes
    Video memory: 2048MB
    Unified memory: no
    Preferred profile: core (0x1)
    Max core profile version: 4.6
    Max compat profile version: 4.6
    Max GLES1 profile version: 1.1
    Max GLES[23] profile version: 3.2
Memory info (GL_ATI_meminfo):
    VBO free memory - total: 1756 MB, largest block: 1756 MB
    VBO free aux. memory - total: 3016 MB, largest block: 3016 MB
    Texture free memory - total: 1756 MB, largest block: 1756 MB
    Texture free aux. memory - total: 3016 MB, largest block: 3016 MB
    Renderbuffer free memory - total: 1756 MB, largest block: 1756 MB
    Renderbuffer free aux. memory - total: 3016 MB, largest block: 3016 MB
Memory info (GL_NVX_gpu_memory_info):
    Dedicated video memory: 2048 MB
    Total available memory: 5120 MB
    Currently available dedicated video memory: 1756 MB
OpenGL vendor string: X.Org
OpenGL renderer string: AMD RAVEN (DRM 3.35.0, 5.4.0-39-generic, LLVM 9.0.1)
OpenGL core profile version string: 4.6 (Core Profile) Mesa 20.0.4
OpenGL core profile shading language version string: 4.60
OpenGL core profile context flags: (none)
OpenGL core profile profile mask: core profile

OpenGL version string: 4.6 (Compatibility Profile) Mesa 20.0.4
OpenGL shading language version string: 4.60
OpenGL context flags: (none)
OpenGL profile mask: compatibility profile

OpenGL ES profile version string: OpenGL ES 3.2 Mesa 20.0.4
OpenGL ES profile shading language version string: OpenGL ES GLSL ES 3.20

$ lshw -short | grep -i  display
/0/100/1.1/0            display     TU117M [GeForce GTX 1650 Mobile / Max-Q]
/0/100/8.1/0            display     Picasso

The driver of the NVIDIA GPU is:
$ nvidia-detector
nvidia-driver-440

The OS:
$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 20.04 LTS
Release:    20.04
Codename:   focal

The kernel:
$ uname -rm
5.4.0-39-generic x86_64

When i run nvidia-xconfig with root privileges and reboot afterwards, I can't get past the initial logo. Only rebooting in recovery mode and deleting /etc/X11/xorg.conf with a subsequent reboot allows me to use the PC again.

A: After installing the graphics drivers from Nvidia, there will be an app installed called NVIDIA X server Settings. There is a section called as Prime-Profiles. Under that you can select performance mode (NVIDIA Graphics card only), On-Demand mode (like Windows, for basic task only integrated gpu, heavy task dedicated gpu), or powersaving mode(integrated gpu only).
Alternately you can run sudo prime-select nvidia which will select the dedicated NVIDIA card only.
Note: You will need a reboot to apply the changes.


text:
Q: $f \in C^{\infty} \Longleftrightarrow (g \circ f) \in C^{\infty} \; \forall \, g \in C^{\infty}$ Let $M \subseteq \mathbb{R}^m$ and $N \subseteq \mathbb{R}^n$ be two embedded manifolds and let $f : M \longrightarrow N$. Show that $f$ is smooth if and only if the composition $(g \circ f)$ is smooth for every smooth map $g : V \longrightarrow \mathbb{R}$, where $V \subseteq N$ is open.
$\bullet \;$ The direction $f \in C^{\infty} \Longrightarrow (g \circ f) \in C^{\infty}$ is easy, using the proposition that the composition of smooth maps is smooth again.
$\bullet \;$ The direction $(g \circ f) \in C^{\infty} \Longrightarrow f \in C^{\infty}$ however gives me some troubles. I have the feeling that the proof is actually quite easy - yet I am unable to conclude it. If I could assume that there always exists some diffeomorphism $\varphi$ between $V$ and $\mathbb{R}$, then I could simply set $g = \varphi$ and I would be done, wouldn't I? Unfortunately, this assumption is rather bold, I suppose, and so I am stuck at this point.
${}$
The definition for smoothness granted is the following one:
Definition: A map $f : M \longrightarrow N$ between manifolds is called smooth if for all $p \in M$ there exists an open neighbourhood $U_p \in \mathbb{R}^m$ of $p$ and some smooth map $F : U_p \longrightarrow \mathbb{R}^n$ such that $F \, |_{U_p \cap M} = f \, |_{U_p \cap M}$.

A: As $N$ is a manifold, there exists a smooth chart $(V, \varphi)$ such that $\varphi : V \to \mathbb{R}^{\dim{N}}$ is a diffeomorphism. Consider the components of $\varphi \circ f|_{f^{-1}(V)}$ and continue from there.

A: Assume that for any locally defined smooth map $g:N\to \mathbb R$, $g\circ f$ is smooth. And let us show that $f$ is $C^1$ at some point $p \in M$.
Let $U,V$ be open subsets of $M,N$ respectively, such that $p \in U$, $f(U)\subset V$ and let $ \phi= (x^\mu)_{\mu = 1}^{\dim N}$ be a set of local coordinates on $V$.
Then, each $x^\mu \circ f$ is $C^\infty$. Therefore, $\phi\circ f: U\to \mathbb R^n$ is $C^\infty$. $\phi $ being a (local) diffeomorphism, we conclude that $f$ is $C^\infty$ on a neighborhood of $p$, and therefore on $M$.


text:
Q: Command file 'nagios.cmd#015' does not exist issue if passivecheck is sent to NSCA daemon Introduction
As /usr/local/nagios/etc/nsca.cfg is replaced by the default config if opsview has been restarted the reference to this file that resides in /etc/init.d/opsview was changed to /usr/local/nagios/etc/nsca_puppet.cfg and the latter is deployed using a Puppet ERB template.
Aim
The aim is to send passive checks using nsca to Opsview.
The hypothesis was that executing:
echo -e "HOST\tService\t0\tRemote File does not exist" | \
sudo /usr/local/nagios/bin/send_nsca -H host -c \
/usr/local/nagios/etc/send_nsca.cfg

would update the (passive) check that reside in Opsview.
Result
Tailing the /var/log/messages indicates the following:
Jan 24 14:27:37 host nsca[X]:
Handling the connection for <ip>...
Jan 24 14:27:37 host nsca[X]:
Command file '/usr/local/nagios/var/rw/nagios.cmd#015'
does not exist, attempting to use alternate dump file
'/dev/null' for output
Jan 24 14:27:37 host nsca[X]:
SERVICE CHECK -> Host Name: 'HOST', Service Description:
'Service', Return Code: '0', Output: 'Remote File does
not exist' client <ip>
Jan 24 14:27:37 host nsca[X]: End of connection for <ip>...

Attempts to solve the issue
1) Perhaps the nsca command should be issued as the nagios user
sudo -u nagios /usr/local/nagios/bin/send_nsca

Does not solve the issue
2) does ncsa run?
Yes
user@host:~$ ps -ef | grep nsca
nagios   PID     1  0 13:38 ?        00:00:00
/usr/local/nagios/bin/nsca -c
/usr/local/nagios/etc/nsca.cfg --single

3) does it work to send ncsa commands from localhost
No, does not work either
4) Incorrect permissions nagios.cmd?
Seems to be ok
user@host:~$ ls -ltr /usr/local/nagios/var/rw/
total 4
-rw-rw-r--. 1 nagios nagios 1321 Jan 23 22:13 config_output.last_okay
srw-rw----. 1 nagios nagcmd    0 Jan 24 13:38 nagios.qh
prw-rw----. 1 nagios nagcmd    0 Jan 24 13:38 nagios.cmd
srw-rw----. 1 nagios nagcmd    0 Jan 24 13:38 opsviewd.cmd

5) Does it work to send other checks then the passive ones to Opsview using nsca
The issue occurs for all kind of checks
6) nagios.cmd#015 does not exist...? nagios.cmd was configured? Or not?
Yes this is correct
7) related bugs to this version of NSCA?
user@host:~$ sudo /usr/local/nagios/bin/nsca --version

NSCA - Nagios Service Check Acceptor
Copyright (c) 2000-2007 Ethan Galstad (www.nagios.org)
Version: 2.7.2
Last Modified: 07-03-2007
License: GPL v2
Encryption Routines: AVAILABLE

Seems to be ok as no issues were found on the internet.
8) Who is allowed to write to nagios.cmd?
User is not allowed to write:
user@host:~$ echo hello >> /usr/local/nagios/var/rw/nagios.cmd
-bash: /usr/local/nagios/var/rw/nagios.cmd: Permission denied

while nagios is:
user@host:~$ sudo su - nagios
nagios@host:~$ echo hello >> /usr/local/nagios/var/rw/nagios.cmd
nagios@host:~$

/usr/local/nagios/etc/nsca.cfg
command_file=/usr/local/nagios/var/rw/nagios.cmd

Questions
Several questions could be asked but the assumption at the moment is that the checks could not be processed as these are not written to nagios.cmd.

*

*Where does the #015 come from?

A: According to this Q&A a #015 in the syslog corresponds to a \r.
The issue was caused because CRs were added by Puppet ERB templates.
Executing the following command:
sudo sed -i 's/\r//' /usr/local/nagios/etc/nsca.cfg

and restarting opsview solved the issue.
In order to solve the CR template erb issue in Puppet, use content => regsubst(template("opsview/nsca.cfg.erb"), '\r', '', 'G'),.

A: You don't mention running the nsca server. This is the most important piece.
Send_nsca needs data. Here your test is invalid:
1) Perhaps the nsca command should be issued as the nagios user

sudo -u nagios /usr/local/nagios/bin/send_nsca
Rather, you need to echo first and pipe the data in to send_nsca. Your nsca daemon on the server side is what needs to run as the nagios/nagcmd user/group.
Consult the following guide for more details on how to setup nsca:
http://munin.readthedocs.org/en/latest/tutorial/nagios.html


text:
Q: how to do taxonomy on metadata stored in mongodb i have extracted metadata for some files(pdf,html,txt,doc) and stroed in mongodb in json format.
sample documents in my mongodb collection is as follows
{"Author: ":null,"Title: ":"java Syllabus","File name: ":"sample.htm"}
{"Author: ":null,"Title: ":"php Syllabus","File name: ":"sample1.htm"}
{"Author: ":null,"Title: ":null,"File name: ":"sample2.pdf"}

My requirement is to do taxonomy on above fields in documents.Is this possible?If its possible please suggest me .
Thanks

A: By "taxonomy", are you hoping to store arbitrary key/value pairs for each document and later query by those values? You may find MongoDB Content Taxonomy Schema a useful resource.
The gist is that top-level document will have a field containing an array of zero or more objects. Each of those objects will contain the key and value in their own fields. You can then create a compound, multi-key index on the key/value fields within the array. Although compound, multi-key indexes cannot include multiple array fields (things could quickly get out of hand with indexing the Cartesian product of elements from each array), in this case we're indexing two fields within the same array.
To use your example data, you might have the following:
> db.foo.insert({
  filename: "sample.htm",
  taxonomy: [
    { k: "author", v: "Bob Smith" },
    { k: "title", v: "Java Syllabus" }
  ]
});
> db.foo.ensureIndex({ "taxonomy.k": 1, "taxonomy.v": 1 });

Per the examples in the linked blog post, you could query by key/value criteria, using $elemMatch to ensure the key/value are both contained in the same array element.


text:
Q: How to redirect any folders within a subdirectory to a specific file using htaccess? I want to redirect any folder to a specific php file with the folder name as variable using htaccess, for example:
www.domain.com/subdirectory/folder1 redirects to www.domain.com/subdirectory/file.php?id=folder1
www.domain.com/subdirectory/folder2 redirects to www.domain.com/subdirectory/file.php?id=folder2
This should work if the folders have "/" at their end, for example,
www.domain.com/subdirectory/folder3/ redirects to www.domain.com/subdirectory/file.php?id=folder3
It will be better if I can put the .htaccess file in the subdirectory and get redirect rule according to it.
I created a .htaccess file with the following code while putting the file in the subdirectory:
Options +FollowSymLinks
RewriteEngine on
RewriteRule (.*)$ file.php?id=$1
but it does not work.

A: RewriteRule ^folder(.*)$ file.php?id=$1
use these i am not tested but it will be work.


text:
Q: Extending $Z_p$ to $Z_p[\alpha]$ and Showing $|Z_p[\alpha]| = p^2$ Let $i(x) = x^2 - [b]$ be an irreducible 2nd degree polynomial in $Z_p[x]$ for $p$ a prime integer and $[b] \in Z_p$. (The fact that $i(x)$ exists has been shown elsewhere).  Then $i(x)$ doesn't have any roots in $Z_p$.  So let us extend $Z_p$ to $Z_p[\alpha]$ s.t. $\alpha$ is a root of $i(x)$.
Goal: Show that $|Z_p[\alpha]| = p^2$.
Attempt: Below I show that there are at least $p$ new elements in $Z_p[\alpha]$.

*

*Let $[k],[j] \in Z_p$ then we have that $[k] + \alpha = [j] + \alpha$ implies that $[k] = [j]$. Furthermore, we have that each $[k] + \alpha$ is not in $Z_p$, for otherwise $([k] + \alpha) - [k] = \alpha$ would imply that $\alpha \in Z_p$, a contradiction.

*So there are at least $p$ new elements in $Z_p[\alpha]$.  Namely, $\alpha, [1] + \alpha, [2] + \alpha, \ldots , [p-1] + \alpha$.  Call these $p$ new elements $a_1, \ldots , a_p$.
Now I could continue to multiply and add $Z_p \cup \{a_i\}$ to try to generate the rest of the $p^2 - 2p$ elements, but I'm not sure this is the right approach.  How do I show that $|Z_p[\alpha]| = p^2$?

A: It's not clear (to me, at least) how you construct the extension $\;\Bbb Z_p[\alpha]\;$ but it seems to be you use the quotient ring
$$\Bbb Z_p[\alpha]\cong\Bbb Z_p[x]/\langle x^2-b\rangle$$
Now, show that every element in the extension can be represented as $\;cx+d+\langle b\rangle\;$ in the quotient, and that two different elements like this one are different in the quotient, which already gives you $\;p\cdot p=p^2\;$ elements.
Another approach: we know every field is a linear space over any subfield, and since the quotient above is a field (why?), it is a linear space over $\;\Bbb Z_p\;$ . Now show that $\;\left\{1+\langle b\rangle\;,\;x+\langle b\rangle\right\}\;$ is a basis for our space and, again but this time by basic combinatorics, we get $\;p^2\;$ elements .
Note that in fact we can put $\;\alpha=x+\langle b\rangle\;$ ...


text:
Q: Prove $M,n,p,q>0$, if $\frac{m}{n}\lt\frac{p}{q},$ show $\frac{m}{n}\lt\frac{m+p}{n+q}\lt\frac{p}{q},$ Prove the following inequality
Given :$M,n,p,q>0$,

$$\frac{m}{n}\lt\frac{p}{q},$$

To show:

$$\frac{m}{n}\lt\frac{m+p}{n+q}\lt\frac{p}{q},$$

I would like to solve it myself so maybe a hint would help. I am working ahead of class so I am not sure what I am doing ;)  I've tried to manipulate the inequality in different ways but did not get anywhere...
I am sure the solution is quite simple, and maybe with a hint, I can figure it out myself

A: The left inequality is true because
$$\frac{m+p}{n+q}-\frac{m}{n}=\frac{np-mq}{n(n+q)}>0$$
and $\frac{m}{n}<\frac{p}{q}$ gives $mq<np$.
A proof of the right inequality we can get by the same way.

A: Hint:
Since all numbers are positive, you simply have to use this rule:

Let $a,b,c,d\:$ be positive numbers. Then
  $$\frac ab<\frac cd\iff ad<bc.$$

Indeed, your left inequality, for instance, reduces to
$$m(n+q)<n(m+p)\iff  mq<np, $$
which is another form of the hypothesis.


text:
Q: Can someone tell what's wrong with that code? this button is to check if there is an empty cells in the last row .
if there is filled cell the button (confirmer) will be enabled .. the application crashes when i debug
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click

        DataGridView1.AllowUserToAddRows = "true"
        DataGridView1.ClearSelection()
        DataGridView1.Rows(DataGridView1.NewRowIndex).Selected = True
        Dim c As Boolean
        Dim D As String
        Dim nbrcell As Integer = DataGridView1.CurrentRow.Cells.Count - 1

        c = Confirmer.Enabled
        Do
            For i As Integer = 0 To nbrcell - 1
                D = DataGridView1.SelectedRows(0).Cells(i).Value
                If D <> "" Then

                    c = True
                End If
            Next
        Loop Until c = True
    End Sub

A: You are trying to read the number of cells from the CurrentRow property.
But if there is no CurrentRow set when you run this code then the code crashes with a Null Reference Exception. (A.K.A. Object Reference not set to an instance of an object)
Instead you should use the row at NewRowIndex.
Dim nbrcell As Integer = DataGridView1.Rows(DataGridView1.NewRowIndex).Cells.Count

and don't subtract 1 from the count of cells. You are doing this two times. One when you get the Count and one more time when you loop over that count (So the last cell is not  checked)
Now the loop: You never exit from that loop if the cells are all filled
Dim D as Object
Dim allFilled = True
For i As Integer = 0 To nbrcell - 1
    D = DataGridView1.SelectedRows(0).Cells(i).Value
    If D Is Nothing OrElse
        Convert.IsDBNull(D) OrElse
        String.IsNullOrWitheSpace(D.ToString()) Then
        allFilled = False
              Exit For ' no need to continue the loop
    End If
Next
Confirmer.Enabled = allFilled

I have removed the external while, the the loop is executed only using the for and it is stopped as soon as a cell with Nothing, DBNull or empty string value is found. At that point a boolean variable is set to false and applied to the Enabled property of the button. If no cells are found to be invalid then the boolen variable remains set to true and the button will be enabled.
Probably it is possible to change something in the evaluation code of the cell, but this depends on how do you fill the grid (manually or through a database data)

A: I have changed your code like this:
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click

    DataGridView1.AllowUserToAddRows = "true"
    DataGridView1.ClearSelection()
    DataGridView1.Rows(DataGridView1.NewRowIndex).Selected = True
    Dim c As Boolean
    Dim D As Object
    Dim nbrcell As Integer = DataGridView1.CurrentRow.Cells.Count - 1

    c = Confirmer.Enabled
    Do
        For i As Integer = 0 To nbrcell - 1
            D = DataGridView1.SelectedRows(0).Cells(i).Value
            If Not IsDBNull(D) Then

                c = True
            End If
        Next
    Loop Until c = True
End Sub

Hope it helps

A: Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Confirmer.Visible = True
Confirmer.Enabled = False

DataGridView1.AllowUserToAddRows = "true"
DataGridView1.ClearSelection()

DataGridView1.Rows(DataGridView1.NewRowIndex).Selected = True

Dim c As Boolean = False
Dim D As Object
Dim nbrcell As Integer = DataGridView1.CurrentRow.Cells.Count
Do
    For i As Integer = 0 To nbrcell - 1
        D = DataGridView1.Rows(DataGridView1.NewRowIndex).Cells(i).Value
        If Not IsDBNull(D) Then
            Confirmer.Enabled = True
            c = True
        End If
    Next
Loop Until c = True

 End Sub

The Problem now is that the button(confirmer) is always enabled even is the cell is empty


text:
Q: How to persist keyboard across several composable screens? Hello!
I have an issue with TextField in Jetpack Compose, Android.
We have a sequence of screens where each screen has TextField, and I want to keep the keyboard open when the screen is changed to the next or previous one. But now when I change the screen, the keyboard is closed and opens what looks terribly bad to the user.
Video: https://youtube.com/shorts/RmSPGT2Rteo

Example
In original, I have separate ViewModels connected to these screens, a lot of other components on them and navigation library to make the navigation concise.
This is a very simplified sample of the issue I suffer from:
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    setContent {
        var screenIndex by remember { mutableStateOf(0) }

        when (screenIndex) {
            0 -> Screen(0) { screenIndex = 1 }
            1 -> Screen(1) { screenIndex = 0 }
        }
    }
}

@Composable
fun Screen(
    index: Int,
    onButtonClick: () -> Unit,
) {
    Column(
        modifier = Modifier.fillMaxSize().imePadding(),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center,
    ) {
        val focusRequester = remember { FocusRequester() }

        LaunchedEffect(Unit) {
            focusRequester.requestFocus()
        }

        var value by remember { mutableStateOf("$index") }
        TextField(
            modifier = Modifier.focusRequester(focusRequester),
            value = value,
            onValueChange = { value = it },
        )

        Button(onClick = onButtonClick) {
            Text("Change screen")
        }
    }
}

What I've tried to do
I've read the source code of the CoreTextField and learnt the following:
There are special function which disposes the TextInputSession when TextField is removed from the composition.
Source from CoreTextField.kt, line 316. Compose Foundation version is 1.3.1
// Hide the keyboard if made disabled or read-only while focused (b/237308379).
if (enabled && !readOnly) {
    // TODO(b/230536793) This is a workaround since we don't get an explicit focus blur event
    //  when the text field is removed from the composition entirely.
    DisposableEffect(state) {
        onDispose {
            if (state.hasFocus) {
                onBlur(state)
            }
        }
    }
}

Also, I've tried the following things:

*

*Add the delay before opening the keyboard

*Disable TextField before changing the screen (partially works but in my project screen navigation happens in the ViewModel level and it's impossible to synchronize that processes)

*Use InputMethodManager to open the keyboard, especially it's toggleSoftInput method but it's deprecated.

How can I keep the keyboard opened and move focus to the new TextField when the screen is changed?

A: You can trick the IME by starting an input session as soon as the screen is displayed. Doing this, the IME will not have the time to close and will stay opened.
Starting an input session
Starting an input session is achieved by using LocalTextInputService.current which retained a reference of the following class TextInputService.
Using the TextInputService.startInput(...) method will launch the session.
The following code will launch it :
 val textInputService = LocalTextInputService.current

 textInputService?.startInput(
    value = TextFieldValue(""),
    imeOptions = ImeOptions.Default,
    onEditCommand = {},
    onImeActionPerformed = {}
 )

Wrapping inside a modifier extension
To have a cleaner code, we can wrap this piece of code inside a modifier extension to allow reusability.
fun Modifier.startInputSession() = composed {
    val textInputService = LocalTextInputService.current

    textInputService?.startInput(
        value = TextFieldValue(""),
        imeOptions = ImeOptions.Default,
        onEditCommand = {},
        onImeActionPerformed = {}
    )

    this
}

Use of composed {} is mandatory because we need to access LocalTextInputService.current
Example
Using it is simple, you just need to wrap your screens inside a box who use the Modifier.startInputSession() extension method
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    setContent {
         Box(
                modifier = Modifier.startKeyboardSession()
            ) {
                var screenIndex by remember { mutableStateOf(0) }

                when (screenIndex) {
                    0 -> Screen(0) { screenIndex = 1 }
                    1 -> Screen(1) { screenIndex = 0 }
                }
            }
    }
}

Issues
Don't forget that we are faking an input session EACH time the screen is recomposed. So be sure that each time you are navigating you are calling the startInputSession() method again, otherwise it will not work.


text:
Q: Accessing a single virtual volume on DELL ME4012 from multiple hosts I have one DELL Powervault ME4012 connected to two host servers (DELL PowerEdge R740 on Ubuntu 18.04) using 12 Gbps SAS HBAs. The ME4012 storage is configured as one virtual volume with RAID type ADAPT. The volume is mounted on both host servers (EXT4). When i write a file on the mounted volume from Host A, the file does not appear on the volume mounted on Host B. The file shows up on Host B Only after I un-mount and then re-mount the volume on Host B.
I have tried changing the virtual volume cache setting using ME4012 management interface from default "Write-back" to "Write-through" to no effect. So what else can i try to make the files written from Host A visible on Host B immediately.
Like if we open the same directory in two separate windows and create a new folder in window A, the same folder appears instantly on window B as well, because it is the same directory open in two separate windows. I expect the same to work across two servers because the underlaying directory/volume is still the same.

A: You should never mount a simple EXT volume on two different hosts. You are going to cause all kinds of issues. If you need access to those files from multiple machines, connect them to a host and share them using SMB/NFS.

A: You must not mount an ext4 volume concurrently on two machines. Not seeing data written on one host on the other host is one of the more harmless results. You will also see data corruption, one host overwriting data the other host has written, and worse.
If you want to access files concurrently from several hosts you need a network filesystem like NFS or SMB.


text:
Q: Sanitize a $_REQUEST[object] to satisfy the phpcs standards for WordPress? Is there a way to sanitize a $_REQUEST[object] to satisfy the phpcs standards for WordPress? Below is what I have so far but phpcs still errors on the earliest assignment of the request and I cannot figure out how to sanitize without first assigning.
if ( ( isset( $_REQUEST['action'] ) && 'delete' === $_REQUEST['action'] ) || ( isset( $_REQUEST['action2'] ) && 'delete' === $_REQUEST['action2'] ) ) {
    $nonce = isset( $_REQUEST['delete_bulk'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['delete_bulk'] ) ) : '';

    if ( wp_verify_nonce( $nonce, 'delete_bulk' ) ) {
        if ( isset( $_REQUEST['bulkcheck'] ) ) {
            $checks    = $_REQUEST['bulkcheck']; // This generates phpcs errors.
            $bulkcheck = array();
            foreach ( $checks as $key => $val ) {
                $bulkcheck[ $key ] = ( isset( $checks[ $key ] ) ) ? sanitize_text_field( wp_unslash( $val ) ) : '';
            }
        }
        $this->quotes_delete_bulk( $bulkcheck );
        header( 'Location: ' . get_bloginfo( 'wpurl' ) . '/wp-admin/admin.php?page=My-Plugin' );
    } else {
        $this->msg = $this->nonce_error();
    }
}

A: See sanitize_key()
if ( ( isset( $_REQUEST['action'] ) && 'delete' === $_REQUEST['action'] ) || ( isset( $_REQUEST['action2'] ) && 'delete' === $_REQUEST['action2'] ) ) {
    $nonce = isset( $_REQUEST['delete_bulk'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['delete_bulk'] ) ) : '';

    if ( wp_verify_nonce( $nonce, 'delete_bulk' ) ) {
        if ( isset( $_REQUEST['bulkcheck'] ) ) {
            $checks    = sanitize_key( $_REQUEST['bulkcheck'] ); // This generates phpcs errors.
            $bulkcheck = array();
            foreach ( $checks as $key => $val ) {
                $bulkcheck[ $key ] = ( isset( $checks[ $key ] ) ) ? sanitize_text_field( wp_unslash( $val ) ) : '';
            }
        }
        $this->quotes_delete_bulk( $bulkcheck );
        header( 'Location: ' . get_bloginfo( 'wpurl' ) . '/wp-admin/admin.php?page=My-Plugin' );
    } else {
        $this->msg = $this->nonce_error();
    }
}


text:
Q: How to extract text as well as hyperlink text in scrapy? I want to extract from following html code:

    Click Here
    "for further reference"

I'm trying to do with following extract command
response.css("article div#section-2 li::text").extract()

But it is giving only "for further reference" line
And Expected output is "Click Here for further reference" as a one string.
How to do this?
How to modify this to do the same if following patterns are there:

*

*Text Hyperlink Text

*Hyperlink Text

*Text Hyperlink

A: There are at least a couple of ways to do that:
Let's first build a test selector that mimics your response:
>>> response = scrapy.Selector(text="""

...     Click Here
...     "for further reference"
...
""")

First option, with a minor change to your CSS selector.
Look at all text descendants, not only text children (notice the space between li and ::text pseudo element):
# this is your CSS select,
# which only gives direct children text of your selected LI
>>> response.css("li::text").extract()
[u'\n    ', u'\n    "for further reference"\n']

# notice the extra space
#                 here
#                   |
#                   v
>>> response.css("li ::text").extract()
[u'\n    ', u'Click Here', u'\n    "for further reference"\n']

# using Python's join() to concatenate and build the full sentence
>>> ''.join(response.css("li ::text").extract())
u'\n    Click Here\n    "for further reference"\n'

Another option is to chain your .css() call with XPath 1.0 string() or normalize-space() inside a subsequent .xpath() call:
>>> response.css("li").xpath('string()').extract()
[u'\n    Click Here\n    "for further reference"\n']
>>> response.css("li").xpath('normalize-space()').extract()
[u'Click Here "for further reference"']

# calling `.extract_first()` gives you a string directly, not a list of 1 string
>>> response.css("li").xpath('normalize-space()').extract_first()
u'Click Here "for further reference"'

A: I use xpath if that is the case the selector will be:
response.xpath('//article/div[@id="section-2"]/li/a/text()').extract()#this will give you text of mentioned hyper link >> "Click Here"
response.xpath('//article/div[@id="section-2"]/li/a/@href').extract()#this will give you link of mentioned hyper link >> "abc.html"
response.xpath('//article/div[@id="section-2"]/li/text()').extract()#this will give you text of li >> "for further reference"


text:
Q: How can I show multiple plots within one panel in R? I have the following plots and I want to show all of them within one panel! How can I do it using a matrix? Also I would like to know if there are other methods rather than using matrix and layout.
> plot(density(Boston$tax))
> rug(Boston$tax, col=2, lwd=3.5)
> hist(Boston$tax)
> rug(Boston$tax, col=2, lwd=3.5)
> table(Boston$chas)
Off  On
471  35
> barplot(table(Boston$chas))

> f1<-layout(matrix(c(0, 1,1,1,0,2,2,2,0,3,3,3) ,nrow = 4, ncol = 4, byrow = TRUE))
> layout.show(f1)

I want to have a structure like this for my plot 1, 2 and 3:
##      [,1] [,2] [,3] [,4]
## [1,]    0    1    1   1
## [2,]    0    2    2   2
## [3,]    0    3    3   3
## [4,]    blank0    0   0

However the output of my code shows something different:

Can someone explain to me how is the following figure c(...) has been constructed?

A: From ?layout
Description:

     'layout' divides the device up into as many rows and columns as
     there are in matrix 'mat', with the column-widths and the
     row-heights specified in the respective arguments.

So if our matrix is
matrix(1:4, 2, 2, byrow = TRUE)
##      [,1] [,2]
## [1,]    1    2
## [2,]    3    4

our lay out is like so

if we only want 1 plot on the top row we can specify our matrix as
matrix(c(1, 1, 2, 3), 2, 2, byrow = TRUE)
##      [,1] [,2]
## [1,]    1    1
## [2,]    2    3

and the layout will be

mat <- matrix(1:3, 3, 3)
mat <- rbind(cbind(0, mat), 0)
##      [,1] [,2] [,3] [,4]
## [1,]    0    1    1    1
## [2,]    0    2    2    2
## [3,]    0    3    3    3
## [4,]    0    0    0    0

layout(mat)

plot(density(Boston$tax))
rug(Boston$tax, col=2, lwd=3.5)
hist(Boston$tax)
rug(Boston$tax, col=2, lwd=3.5)
barplot(table(Boston$chas))


text:
Q: nginx: [emerg] unknown directive "match", why does it appear? this is my config
enter image description here
log_format mqtt '$remote_addr [$time_local] $protocol $status $bytes_received '
                '$bytes_sent $upstream_addr';

upstream hive_mq {
    server 192.168.11.200:1883; #node1
    server 127.0.0.1:1883; #node2
    zone tcp_mem 64k;
}

match mqtt_conn {
        # Send CONNECT packet with client ID "nginx health check"
        send   \x10\x20\x00\x06\x4d\x51\x49\x73\x64\x70\x03\x02\x00\x3c\x00\x12\x6e\x67\x69\x6e\x78\x20\x68\x65\x61\x6c\x74\x68\x20\x63\x68\x65\x63\x6b;
        expect \x20\x02\x00\x00; # Entire payload of CONNACK packet
}

server {
    listen 8081;
    proxy_pass hive_mq;
    proxy_connect_timeout 1s;
    health_check match=mqtt_conn;

    access_log /var/log/nginx/mqtt_access.log mqtt;
    error_log  /var/log/nginx/mqtt_error.log; # Health check notifications
}

but when I reload the setting and it return failed as following
enter image description here
 nginx.service - The nginx HTTP and reverse proxy server
   Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; vendor preset: disabled)
  Drop-In: /usr/lib/systemd/system/nginx.service.d
           └─php-fpm.conf
   Active: failed (Result: exit-code) since Fri 2022-12-02 03:20:49 UTC; 2s ago
  Process: 51793 ExecStart=/usr/sbin/nginx (code=exited, status=0/SUCCESS)
  Process: 51821 ExecStartPre=/usr/sbin/nginx -t (code=exited, status=1/FAILURE)
  Process: 51819 ExecStartPre=/usr/bin/rm -f /run/nginx.pid (code=exited, status=0/SUCCESS)
 Main PID: 51794 (code=killed, signal=KILL)

Dec 02 03:20:49 localhost systemd[1]: Starting The nginx HTTP and reverse proxy server...
Dec 02 03:20:49 localhost nginx[51821]: nginx: [emerg] unknown directive "match" in /etc/nginx/nginx.conf:171
Dec 02 03:20:49 localhost nginx[51821]: nginx: configuration file /etc/nginx/nginx.conf test failed
Dec 02 03:20:49 localhost systemd[1]: nginx.service: Control process exited, code=exited status=1
Dec 02 03:20:49 localhost systemd[1]: nginx.service: Failed with result 'exit-code'.
Dec 02 03:20:49 localhost systemd[1]: Failed to start The nginx HTTP and reverse proxy server.

noted I have include modules/*.conf and the modules are
enter image description here
Do I miss someting?
How to address the config problem in Nginx?


text:
Q: Connecting Android causes Client Service Runtime Process to severely slow down PC This issue has been bothering me for a long while, very weird and couldn't solve it.
When I connect my Nexus 4 Android to the PC, suddenly the Client Service Runtime Process CPU consumption jumps high and my PC slows down dramatically. Please see the screenshot.

The temporary solution was to restart the PC keeping Android connected, the PC would work fine at normal speed.
Cam someone please guide me how to fix this Client Services Runtime Process issue? It's really weird.


text:
Q: Extraer datos de un EditText y agregarlos a objeto Tengo el siguiente código:
      ArrayList<Lista_entrada> llibres = new ArrayList<Lista_entrada>();

    // Afegim uns llibres d'exemple.
    llibres.add(new Lista_entrada( "BUHO", "Búho es el nombre común d."));
    llibres.add(new Lista_entrada( "COLIBRÍ", "Los troquilinos"));

La duda que tengo es ahora mismo la introduzco directamente.  Pero me gustaría poder extraer los datos de dos EditText.
El problema lo tengo porque :
llibres.add(new Lista_entrada( String, String );
( Espera 2 strings )
¿Podéis ponerme un ejemplo de como rellenarlo con el contenido de 2 EditText?

A: no entiendo muy bien tu pregunta.
pero imagino que quieres obtener los valores de dos EditText ..  y agregarlos al listado.
supongo que solo debes de hacer esto.
define los EditText
EditText EditText1= findViewById(R.id.EditText1);
EditText EditText2 = findViewById(R.id.EditText2);

obtienes los valores de cada EditText
String text1 = EditText1.getText();
String text2 = EditText2.getText();

llenar la lista
llibres.add(new Lista_entrada( text1 , text2 );

A: llibres es una lista de objetos Lista_entrada
 ArrayList<Lista_entrada> llibres = new ArrayList<Lista_entrada>();

Si quieres insertar valores de dos EditText hacia cada objeto  Lista_entrada, obtén los textos de los TextView (obviamente debes obtener las referencias de los EditText en tu layout mediante findViewById(R.id.<id EditText>) )
   //Obtiene datos de los EditText.
   String texto1 = EditText1.getText();
   String texto2 = EditText2.getText();
   //Crea objeto con valores de los EditText.
   Lista_entrada elementoLista = new Lista_entrada( texto1 , texto2 );
   //Agrega elemento a lista.
   llibres.add(elementoLista);

o simplemente agregar los valores directamente
   //Crea objeto con valores de los EditText.
   Lista_entrada elementoLista = new Lista_entrada( EditText1.getText(), EditText2.getText());
   //Agrega elemento a lista.
   llibres.add(elementoLista);


text:
Q: C# checking what button was pressed I know about this question but it does not addres my issue.
Suppose we have two buttons that do the very same thing (load csv file and feed the data in two variables) but on two different sets of variables. I can write two functions dedicated to both functions, but they will share too much common code.
How can I detect what button called the callback function to decide what set of variables to work on?

A: You can access the Button by casting the sender argument.
You should use an explicit cast instead of (the often seen) as operator, because it would correctly result in an InvalidCastException when the sender is unexpectedly not a Button.
private void button_Click(object sender, EventArgs e)
{
    var button = (Button)sender;
    // Use button properties to differentiate and load to your variables accordingly
}


text:
Q: Unable to load CSV in neo4j due to periodic commit error This is the error I am getting while loading a CSV file:

Neo.ClientError.Statement.SemanticError: Executing queries that use
periodic commit in an open transaction is not possible.

This is the code that I am using:
USING PERIODIC COMMIT
LOAD CSV WITH HEADERS FROM 'file:///bs140513_032310.csv' AS line
WITH line,
  SPLIT(line.customer, "'") AS customerID,
  SPLIT(line.age, "'") AS customerAge,
  SPLIT(line.gender, "'") AS customerGender,
  SPLIT(line.zipcodeOri, "'") AS customerZip,
  SPLIT(line.merchant, "'") AS merchantID,
  SPLIT(line.zipMerchant, "'") AS merchantZip,
  SPLIT(line.category, "'") AS transCategory

A: Recent versions of the neo4j browser require that you use the :auto browser command to initiate the USING PERIODIC COMMIT option.
For example:
:auto USING PERIODIC COMMIT
LOAD CSV WITH HEADERS FROM 'file:///bs140513_032310.csv' AS line
WITH line,
  SPLIT(line.customer, "'") AS customerID,
  SPLIT(line.age, "'") AS customerAge,
  SPLIT(line.gender, "'") AS customerGender,
  SPLIT(line.zipcodeOri, "'") AS customerZip,
  SPLIT(line.merchant, "'") AS merchantID,
  SPLIT(line.zipMerchant, "'") AS merchantZip,
  SPLIT(line.category, "'") AS transCategory

You can get a little more info on :auto in the browser by entering this browser command:
:help auto


text:
Q: Creating a chart from a integer field I'm not sure how i can achieve this , but i have the following data imported to elasticsearch:
{
  "_index": "logstash-2014.09.18",
  "_type": "profiler",
  "_id": "Wp6zn3CSQ9qhdt8cfHxEgw",
  "_score": null,
  "_source": {
    "message": ["wm.server.query:getClusterError,2"],
    "@version": "1",
    "@timestamp": "2014-09-18T15:49:26.287Z",
    "type": "svc-profiler",
    "host": "pc.local",
    "path": "/Users/myuser/profiler.csv",
    "Service Name": "wm.server.query:getClusterError",
    "Call Count": "2"
  },
  "sort": [
    1411055366287,
    1411055366287
  ]
}

And i'm not sure how could i create a chart ( bar or pie ) using the call count field.
I'm sorry if i'm not clear, but english isn't my native language...
So, Anyone have any tip about how could i achieve create a chart using that field?
Thanks in advance.

A: Your example record shows that it's in your ES cluster as a string.  You need to load it as a number to be able to make charts against it.  You'll need to use something like this in your logstash config to turn the field into a number:
filter {
  mutate {
    convert => { "Call Count" => "integer" }
  }
}

Since you can't change an existing mapping, you'll need to reload your data to be able to do anything useful.
Once you do, you can just use a histogram panel with Call Count as the field and do either total or average on it.


text:
Q: Python27 - on windows 8.1 or 10 not showing the printers I have 32-bit Python and win32print of 32bit installed. When i execute the following code on windows 8 or 10 i do not get any printers output list. only its printing: ()

Why its not working?
import win32print
printers = win32print.EnumPrinters(5)
print printers

Expected output:

Try 1: When i tried this code, the printer wake up but nothing gets printed no papers gets out, no printing happens at all.
import os, sys
import win32print
p = win32print.OpenPrinter('RICOH Aficio SP 4310N')
job = win32print.StartDocPrinter (p, 1, ("test of raw data", None, "RAW"))
win32print.StartPagePrinter (p)
win32print.WritePrinter (p, "data to print")
win32print.EndPagePrinter (p)

Try 2: this is printing to the printer with A4 paper

import win32ui
X=50; Y=50
input_string = "COPY PASTE COPY PASTE COPY PASTE LINE"
multi_line_string = input_string.split()
hDC = win32ui.CreateDC ()
hDC.CreatePrinterDC ('RICOH Aficio SP 4310N')
hDC.StartDoc ('FILE NAME FILE NAME')
hDC.StartPage ()
for line in multi_line_string:
     hDC.TextOut(X,Y,line)
     Y += 100
hDC.EndPage ()
hDC.EndDoc ()

A: Try the following
printers = win32print.EnumPrinters(win32print.PRINTER_ENUM_LOCAL, None, 1)
print (printers)

In Windows 8 and 10 "Microsoft Print to PDF" should be listed. And you can use
hDC.CreatePrinterDC ('Microsoft Print to PDF')

See also documentation for (EnumPrinters/Python) and (EnumPrinters/WinAPI)

Example, this code will print PDF file directly to "c:\\test\\_python.pdf". If StartDoc does not include file name then print dialog box will ask for pdf output file name.
import win32print, win32ui

X=50; Y=50
input_string = "COPY PASTE COPY PASTE COPY PASTE LINE"
multi_line_string = input_string.split()
hDC = win32ui.CreateDC ()
hDC.CreatePrinterDC ('Microsoft Print to PDF')
hDC.StartDoc('PrintJobName','c:\\test\\_python.pdf')
hDC.StartPage ()
for line in multi_line_string:
     hDC.TextOut(X,Y,line)
     Y += 100
hDC.EndPage ()
hDC.EndDoc ()


text:
Q: How to keep random.choice() from rechecking itself Today I was writing a code in which it would give you addition or subtraction of integer problems. For example:
from random import randint, choice
while True:
        value_1 = randint(-9,9)
        value_2 = randint(-9,9)
        lol = choice(['+', '-'])
        number = input("What is %s %s %s" % (value_1, lol, value_2))
        if lol == "+":
            try:
                number_x = int(number)
            except ValueError:
                 print("You did not enter a number silly goose")
            else:
                if number_x == value_1 + value_2:
                    print("You got the answer right. Good job!!")
                else:
                    print("Incorrecto my padwan. You still have much to learn")
        elif lol == "-":
            try:
                number_x = int(number)
            except ValueError:
                print("You did not enter a number silly goose")
            else:
                if number_x == value_1 - value_2:
                    print("You got the answer right. Good job!!")
                else:
                    print("Incorrecto my padwan. You still have much to learn")
        else:
            print("How did u even do this")

The issue is that when the choice() function chooses "+" or "-", instead of adding or subtracting like I want it when checking if the person got the answer correct, it rechecks the choice function. This means that even if the computer asks the person "what is 9 - 8", it rechecks lol. So instead of checking to see if the person got the answer to 9-8, the computer sometimes checks to see if the person got the right answer to 9+8. What I want to do here is after the choice() function is checked the first time, it keeps the output, so it does not recheck choice after the computer asks the question to person originally. Or is there an easier way to write this that outputs the same thing I am asking? By the way sorry for the question being written so confusedly and if the answer is obvious(I'm new to programming)

A: I think you can try a different approach. Here is mine for your reference:
import random

op1, op2 = ['', '-'], ['+', '-']
nums = list('0123456789')

if __name__ == '__main__':
    while True:
        question = ''.join([ random.choice(i) for i in (op1, nums, op2, nums) ])
        print 'Q: ' +  question + ' =',
        answer = raw_input()
        if answer == 'q':
            print 'Bye'
            break
        elif not answer.lstrip('-').isdigit():
            print '%s is not a valid answer\n' % (answer)
        elif int(answer) == eval(question):
            print 'Good Job\n'
        else: print 'Try again\n'

Sample output:
Q: -9+6 = 3
Try again

Q: 0-6 = -6
Good Job

Q: -3+3 = E
E is not a valid answer

Q: 1-2 = q
Bye


text:
Q: How to identity recordtype? In our organization we have created several record types for case object, identifying particular record type of case record belongs to is getting very difficult (have to check the profile etc).. Is their any way to easily identify the record type of a case record or in general for any object record.

A: You can add the Record Type field to the page layout, and make it read-only if you don't want users changing it. You'll need to add this field to each page layout it should be visible on.

A: We have a practice of creating a formula field called "record type name" on every object that uses record types.
This lets you query by name instead of hard-coding ids or doing relationship queries, and also helps in certain situations where the relationship isn't available.
It doesn't give you the selectivity of record type, but saves a lot of other work.


text:
Q: Targeting  with specific attribute using BeautifulSoup I'm attempting to scrape a page that has a section like this:

        Store City</strong

Event listing

Event listing2

Event listing3

        Stuff about contact info

The page is a list of sections like that and the only way to differentiate them is by the name attribute in the  tag.
So I'm thinking I want to target that then go to the next_sibling to get the
 then again to the next sibling to get the
 section. All I want is the info in that div tag.
I'm not sure how to target that  tag to move down two siblings though. When I try print(soup.find_all('a', {"name":"id_631"})) that just gives me what's in the tag, which is nothing.
Here's my script:
import requests
from bs4 import BeautifulSoup

r = requests.get("http://www.tandyleather.com/en/leathercraft-classes")

soup = soup = BeautifulSoup(r.text, 'html.parser')

print(soup.find("a", id="id_631").find_next_sibling("div", class_="store-class"))

But I get the error:
Traceback (most recent call last):
File "tandy.py", line 8, in <module>
print(soup.find("a", id="id_631").find_next_sibling("div", class_="store-class"))
AttributeError: 'NoneType' object has no attribute 'find_next_sibling'

A: find_next_sibling() to the rescue:
soup.find("a", attrs={"name": "id_631"}).find_next_sibling("div", class_="store-class")

Also, html.parser has to replaced with either lxml or html5lib.
See also:

*

*Differences between parsers


text:
Q: Lot of empty space between anchor tags Hi am having a annoying issue.Look at the following code, In the code I have 2 links which appear based on conditions checked by the custom tag . The issue is when I see the HTML source of this page,the second anchor appears 700 lines(empty lines) after the first. Anyone pls help me solve this.Thanks in advance..
 rts
<s:userHasAccess functionId="<%=ReportsConstants.CFS_LOAD_PLANNING_FNCT_ID%>">
<jsp:attribute name="yes">
lprt

The custom tag does a privilege check and return true or false.
update:
HTML Source:
 rts //700 blank lines
lprt

A: This worked after adding the trim white space direcitve in the web.xml.
<jsp-property-group>
<url-pattern>*.do</url-pattern>
<trim-directive-whitespaces>true</trim-directive-whitespaces>
</jsp-property-group>


text:
Q: I'm try to get my time to display from javascript and continue to count up ( ie 2:30:45 then 2:30:46) and I'm having a hard time here' my current code var d = new Date();
var time = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate() + " " + d.getHours() + ":" + d.getMinutes();
document.getElementById("currentDay").innerHTML = time;

A: Try putting your code in an interval. That way, it will be called every second.
setInterval(() => {

    //Your code here

},1000);


text:
Q: Textmate's Ruby on Rails 3 bundle? I couldn't find Rails3 bundle for Textmate.
I looked at their website (as well as their github).
I couldn't find any!!
THanks!
Adam

A: The Ruby on Rails bundle (http://github.com/drnic/ruby-on-rails-tmbundle) supports Rails 2 & 3


text:
Q: How to get selected values of checkboxes in DataTable of different pagination pages PHP and javascript? Basically I have a dataTable that displays all the records from the database, and a checkbox for each row within the table. My table has multiple pages. The problem was that I can only get the checkbox values of the current page selected because the system can only see checkboxes that are visible. I want to get specific checked values or all checked values from different pages and push them to the array. How can I achieve this? I can only get the checked value of current selected page in datatable atm. I have searched and tried similar problem, but it's still not working.
Below is my code
PHP code to display checkboxes
foreach($stmt as $row){echo "<tr><td>"."<input type='checkbox' name='check_list' id='checklist' value='$row['id']' style='width:20px; height: 20px'/>"}

Javascript code
function getCheckboxVals(){

    var check = $('input[name="check_list"]:checked').length;
    var mycheckboxes = new Array();

    //IF NO CHECKBOX CHECKS
    if(check == 0){
        eModal.alert('PLEASE SELECT ISSUES BEFORE YOU EXPORT CONTENTS!!!');
        return false;
    }

    //IF ONE OR MORE CHECKBOXES CHECK
    if(check == 1){
        $('input[name="check_list"]:checked', table.fnGetNodes()).serialize().each(function(){

        mycheckboxes.push(this.value);

    });
}else{
    $('input[name="check_list"]:checked').each(function(){

        mycheckboxes.push(this.value);

    });
}

}

A: The issue with only being able to get the values of the check boxes on the current page comes from the use of DOM methods or querying without using the DataTables' API directly. For efficiency, the DataTable only stores the values on the current page. In order to access other values you must use access the table using:
dataTable.rows().nodes().to$().find('input[type="checkbox"]').each(function(){}

The datatable in this instance being your defined datatable.
Additionally, here is a working version of checkbox values being stored and sent to the server
For more info see the DataTable FAQs and topics on DOM.


text:
Q: Sending keydown to Angular directive with jQuery .trigger() I've created an edit directive to wrap an html input in a fancy frame.
Now I'm creating a unit test to check that once I type in the input the dirty state of the form controller is set.
I'm using jQuery.trigger() to simulate this, but I get nothing...
var input = $('input');
var e = $.Event('keydown');
e.which = 'x'.charCodeAt(0);
e.keyCode = 'x'.charCodeAt(0);
input[0].focus();
input.trigger(e);

I have a plunker here
What am I doing wrong?
Thanks!

A: From an answer to a similar question:

The mistake you're making is what you're expecting the jQuery's
  trigger method to do. If you check out the code you'll see that what
  it is doing is actually executing the jQuery registered event handlers
  not the DOM Level 3 events. Because it's only executing jQuery
  handlers you wont be causing the change event which is what you need
  to be triggered to update the value property of the textbox.

Instead you can update the input's value and trigger the change or the input event:
input.val('x').trigger('input');

When doing this inside a controller in a live application however (as opposed to in the unit test environment), you need to break out of the $digest cycle, or you will get the $apply already in progress error.
You can do this by for example using setTimeout:
$scope.trigger = function() {
  setTimeout(function() {
    $('input').val('x').trigger('input');
  });
};

You also need to make sure that you are loading jQuery before AngularJS. If you don't, Angular will use jqLite instead. jqLite uses addEventHandler to register event handlers, and handlers registered this way don't get triggered by jQuery's trigger function.
Demo of your code updated: http://plnkr.co/edit/u3ZWXWLvOjbKWlY8JEM5?p=preview
When unit testing:
it('should work', function() {

  var element = $compile('<form name="form"><edit ng-model="name"></edit></form>')($scope);
  $rootScope.$digest();

  var scope = element.scope(),
    form = scope.form,
    input = element.find('input');

  expect(form.$dirty).toBe(false);

  input.val('x').trigger('input');

  expect(form.$dirty).toBe(true);
});

Demo of the unit test: http://plnkr.co/edit/Emc3dIlDaxXyE9U6dEG6?p=preview


text:
Q: Can a relation has a relation with another relation can we have some thing like following ER?
Is it a technical fault or not?

A: To define a relationship there should be entity by the help of them you can show relation. so it is impossible to make relation without entity.
In your case if you want to use 2 relationship there should be 1 entity between them.
Example of real life
suppose you have two relation teacher and student. you can not say like i am teacher and student of XYZ.
But you can say like i am teacher of Xyz and student of abc.
Typr of relationship
One-to-many relationships
The most common relationship used when creating relational databases.  A row in a table in a database can be associated with one or (likely) more rows in another table.  An example of a one-to-many relationship is a single order has many items on that order.  And since relationships work both ways it is not uncommon to hear reference to many-to-one-relationships as well.
One-to-one relationship
A row in a table is associated to one and only one row in another table.  An example of a one-to-one relationship is a person can have one social security number and a social security number can only be assigned to one person.
In most cases there is no need for a one-to-one relationship as the contents of the two tables can be combined into one table.
Many-to-many relationships
When one or more rows in a table are associated with one or more rows in another table.  An example of a many-to-many relationship is a table of customers who can purchase many different products and a table of products that can be purchased by many different customers.


text:
Q: Mechanize: too many values to unpack (expected 2) I have tried to write the following code, I am trying to write a code in Python 3.7 that just opens a web browser and the website fed to it in the Command Line:
Example.py
import sys

from mechanize import Browser
browser = Browser()

browser.set_handle_equiv(True)
browser.set_handle_gzip(True)
browser.set_handle_redirect(True)
browser.set_handle_referer(True)
browser.set_handle_robots(False)

# pretend you are a real browser
browser.addheaders = [('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36')]

listOfSites = sys.argv[1:]
for i in listOfSites:
    browser.open(i)

I have entered the following command in the cmd:
python Example.py https://www.google.com

And I have the following traceback:
Traceback (most recent call last):
  File "Example.py", line 19, in <module>
    browser.open(i)
  File "C:\Python37\lib\site-packages\mechanize\_mechanize.py", line 253, in open
    return self._mech_open(url_or_request, data, timeout=timeout)
  File "C:\Python37\lib\site-packages\mechanize\_mechanize.py", line 283, in _mech_open
    response = UserAgentBase.open(self, request, data)
  File "C:\Python37\lib\site-packages\mechanize\_opener.py", line 188, in open
    req = meth(req)
  File "C:\Python37\lib\site-packages\mechanize\_urllib2_fork.py", line 1104, in do_request_
    for name, value in self.parent.addheaders:
ValueError: too many values to unpack (expected 2)

I am very new to Python. This is my first code here. I am stuck with the above traceback but haven't found the solution yet. I have searched for a lot of questions on SO community as well but they didn't seem to help. What should I do next?
UPDATE:
As suggested by @Jean-François-Fabre, in his answer, I have added 'User-agent' to the header, now there is no traceback, but still there is an issue where my link cannot be opened in the browser.
Here is how the addheader looks like now:
browser.addheaders = [('User-agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36')]

A: I have just found out a way around to this issue even if the above issue still exists. I am posting this only to let the readers know that we can do it this way too:
Instead of using the mechanize package, we can use the webbrowser package and write the following python code in the Example.py:
import webbrowser
import sys

#This is an upgrade suggested by @Jean-François Fabre
listOfSites = sys.argv[1:]

for i in listOfSites:
    webbrowser.open_new_tab(i)

Then we can run this python code by executing the following command in the terminal/command prompt:
python Example.py https://www.google.com https://www.bing.com

This command mentioned above in the example will open two sites at a time. One is Google and the other is Bing

A: I don't know mechanize at all, but the traceback and variable names (and some googling) can help.
You're initializing addheaders with a list of strings. Some other examples (ex: Mechanize Python and addheader method - how do I know the newest headers?) show a list of tuples, which seem to match the traceback. Ex:
browser.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]

so it unpacks properly into name and value in loop
for name, value in whatever.addheaders:

You have to add the 'User-agent' property name (you can pass other less common parameters than the browser name)

A: Let me try to answer your question in parts:

*

*You're correct in adding "Browser Headers". Many servers might outright drop your connection as it's a definite sign of being crawled by a bot.

*mechanize as stated by the docs "is a tool for programmatic web browsing".
This means it is primarily used to crawl webpages, parse their contents, fill forms, click on things, send requests, but not using a "real" web browser, with parts such as CSS rendering. For example you cannot open a page and take a screenshot, as there's not something "rendered", and to achieve this you would need to save the page, and render it using another solution.

*If this suits you needs, check headless browsers as a technology, there are a lot of them. In the Python ecosystem, other than mechanize, I'd check "headless chromium", as "phantomjs" is unfortunately discontinued.
But if I understand correctly, you need the actual web browser to open up with the webpage, right? For this reason, you actually need, well, a browser in your system to take care of that!
Case 1 : Use your native system's browser
Find out where your browser's executable lies in your system. For example, my Firefox executable lies in "C:\Program Files\Mozilla Firefox\firefox.exe" and add it to your PATH.
As you're using Windows, use the start menu to navigate to Advanced System Settings --> Advanced --> Environment Variables, and add the path above to your PATH variable.
If you're using Linux export PATH=$PATH:"/path/to/your/browser" will take care of things.
Then, your code can run as simply as
import subprocess
import sys

listOfSites = sys.argv[1:]
links = ""
for i in listOfSites:
    links += "-new-tab " + i
print(links)
subprocess.run(["firefox", links])

Firefox will open new windows, one for each of the links you have provided.
Case 2 : Use selenium
Then comes Selenium, which in my opinion is the most mature solution to browser-related problems, and what most people use. I've used it in a production setting with very good results. It provides both the UI/frontend of a browser that renders the webpages, but also allows you to programmatically work with these webpages.
It needs some setup, (for example, if you're using Firefox, you'll need to download the geckodriver executable from their releases page, and then add it your PATH variable again.
Then you define your webdriver, spawn one for each of the websites you need to visit, and get the webpage. You can also take screenshot, as a proof that the page has been rendered correctly.
from selenium import webdriver
import sys

listOfSites = sys.argv[1:]
for i in listOfSites:
    driver = webdriver.Firefox()
    driver.get('http://'+i)
    driver.save_screenshot(i+'-screenshot.png')

# When you're finished
# driver.quit()

I've tested both of these code snippets, and they work as expected. Please let me know how all these sound, and if you need any more additional information..! ^^

A: Here you go :)
import sys
from mechanize import Browser, Request

browser = Browser()

browser.set_handle_equiv(True)
browser.set_handle_gzip(True)
browser.set_handle_redirect(True)
browser.set_handle_referer(True)
browser.set_handle_robots(False)

# setup your header, add anything you want
header = {'User-Agent': 'Mozilla/5.0 (Windows NT 5.1; rv:14.0) Gecko/20100101 Firefox/14.0.1', 'Referer': 'http://whateveritis.com'}

url_list = sys.argv[1:]
for url in url_list:
    request = Request(url=url, data=None, headers=header)
    response = browser.open(request)
    print(response.read())
    response.close()

A: Same as above. Guess I didn't read all the answers before digging in. LOL
import sys
import webbrowser

from mechanize import Browser
browser = Browser()

browser.set_handle_equiv(True)
browser.set_handle_gzip(True)
browser.set_handle_redirect(True)
browser.set_handle_referer(True)
browser.set_handle_robots(False)

# pretend you are a real browser
browser.addheaders = [('User-agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36')]

listOfSites = sys.argv[1:]
for i in listOfSites:
    webbrowser.open(i)


text:
Q: How to automatically select a file to FileUpload on page load? I want to automatically select a file on page load to my FileUpload1. I tried searching but I cant find any related instances. I want to do somethhing like this.
Private Sub WebForm1_Load(sender As Object, e As EventArgs) Handles Me.Load
    FileUpload1.setfile("D:\file\Test.Wav")
End Sub

Because my program is to record a sound (wav file) and it saves to a specific folder. And afterwards, I can select the recorded file and upload/save the file to the database.
When you click button_1, it records a sound using the mic. Then you will button_2 to stop and save the recorded sound.
But what i wanted to do is after clicking the button_2, it will stop and save the recording AND asynchronously it uploads the file to the database.
Here is the code: .VB file
Imports System.Data.SqlClient
Imports System.IO
Imports Microsoft.VisualBasic.Devices
Imports Microsoft.VisualBasic
Imports System.Runtime.InteropServices
Imports System.Text

Partial Class Default2
Inherits System.Web.UI.Page
Protected Sub btnUpload_Click(sender As Object, e As EventArgs) Handles btnUpload.Click
    Using br As New BinaryReader(FileUpload1.PostedFile.InputStream)

        Dim bytes As Byte() = br.ReadBytes(CInt(FileUpload1.PostedFile.InputStream.Length))
        Dim strConnString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
        Using con As New SqlConnection(strConnString)
            Using cmd As New SqlCommand()
                cmd.CommandText = "insert into tblFiles(Name, ContentType, Data) values (@Name, @ContentType, @Data)"
                cmd.Parameters.AddWithValue("@Name", Path.GetFileName(FileUpload1.PostedFile.FileName))
                cmd.Parameters.AddWithValue("@ContentType", "audio/mpeg3")
                cmd.Parameters.AddWithValue("@Data", bytes)
                cmd.Connection = con
                con.Open()
                cmd.ExecuteNonQuery()
                con.Close()
            End Using
        End Using
    End Using
    Response.Redirect(Request.Url.AbsoluteUri)
End Sub

Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
    If Not IsPostBack Then
        BindGrid()
    End If
End Sub

Private Sub BindGrid()
    Dim strConnString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Using con As New SqlConnection(strConnString)
        Using cmd As New SqlCommand()
            cmd.CommandText = "select Id, Name from tblFiles"
            cmd.Connection = con
            con.Open()
            GridView1.DataSource = cmd.ExecuteReader()
            GridView1.DataBind()
            con.Close()
        End Using
    End Using
End Sub
<DllImport("winmm.dll")> _
Private Shared Function mciSendString(ByVal command As String, ByVal buffer As StringBuilder, ByVal bufferSize As Integer, ByVal hwndCallback As IntPtr) As Integer
End Function

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Try
        Dim i As Integer
        i = mciSendString("open new type waveaudio alias capture", Nothing, 0, 0)
        i = mciSendString("record capture", Nothing, 0, 0)
        Label1.Text = "Recording"
        Label1.BackColor = Drawing.Color.Green
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try
End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
    Try
        Dim i As Integer
        i = mciSendString("save capture " & "D:\file\Test.Wav", Nothing, 0, 0)
        i = mciSendString("close capture", Nothing, 0, 0)
        Label1.Text = "Idle"
        Label1.BackColor = Drawing.Color.Yellow
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try

End Sub

Private Sub WebForm1_Load(sender As Object, e As EventArgs) Handles Me.Load
End Sub

End Class

aspx.file
<form runat="server">
    <asp:Button ID="Button1" runat="server" Text="Record" />
    <asp:Button ID="Button2" runat="server" Text="Save" />
    <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

    <asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload"
onclick="btnUpload_Click" />

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" RowStyle-      BackColor="#A1DCF2" Font-Names = "Arial" Font-Size = "10pt"
HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White">

    <Columns>
    <asp:BoundField DataField="Name" HeaderText="FileName" />
    <asp:TemplateField>
        <ItemTemplate>
            <object type="application/x-shockwave-flash" data='dewplayer-vol.swf?mp3=File.ashx?Id=<%# Eval("Id") %>'
                width="240" height="20" id="dewplayer">
                <param name="wmode" value="transparent" />
                <param name="movie" value='dewplayer-vol.swf?mp3=File.ashx?Id=<%# Eval("Id") %>'/>
            <object>
        </ItemTemplate>
    </asp:TemplateField>
    <asp:HyperLinkField DataNavigateUrlFields="Id" Text = "Download" DataNavigateUrlFormatString = "~/File.ashx?Id={0}" HeaderText="Download" />
</Columns>
</asp:GridView>

A: I don't think it is possible due to security reasons. Imagine you visit a random site and it automatically starts uploading files from your local file system without your knowledge/permission.
The input type file control requires the user to select a file to upload, so there is no way you can do it programmatically.


text:
Q: Why textmate not using a typical Xcode project? I've clone a Textmate source code, and build it.
When I read some code of Textmate, I found that it's not using a typical Xcode project.
So, why is that? The cocoa framework of Apple seems not convenient for developing-not-using-Xcode.
I wonder is there some good work flow for develop cocoa apps on OS X?
Or they did it just want to let us know they're cool?

A: Odgaard blogged about this in two parts:
http://sigpipe.macromates.com/2010/01/15/build-automation-part-1/
http://sigpipe.macromates.com/2010/01/23/build-automation-part-2/


text:
Q: Passing parameters between nested includes I want to be able to pass parameters from one include to another. However, Jekyll doesn't seem to like this.
index.md
{% include test-wrapper.html test-var='Foo' %}

test-wrapper.html
{% include test.html test-var={{ include.test-var }} %}

test.html
Got {{ test-var }}

Terminal output
$ bundle exec jekyll build --incremental --trace
Configuration file: /Path/to/project/_config.yml
            Source: /Path/to/project
       Destination: /Path/to/project/_site
 Incremental build: disabled. Enable with --incremental
      Generating...
       Jekyll Feed: Generating feed for posts
  Liquid Exception: Invalid syntax for include tag. File contains invalid characters or sequences: test.html test-var=Foo Valid syntax: {% include file.ext param='value' param2='value' %} in index.md
bundler: failed to load command: jekyll (/usr/local/bin/jekyll)
ArgumentError: Invalid syntax for include tag. File contains invalid characters or sequences:

  test.html test-var=Foo

Valid syntax:

  {% include file.ext param='value' param2='value' %}

  /Library/Ruby/Gems/2.3.0/gems/jekyll-3.8.5/lib/jekyll/tags/include.rb:67:in `validate_file_name'
  /Library/Ruby/Gems/2.3.0/gems/jekyll-3.8.5/lib/jekyll/tags/include.rb:128:in `render'
  /Library/Ruby/Gems/2.3.0/gems/liquid-4.0.3/lib/liquid/block_body.rb:103:in `render_node_to_output'
  /Library/Ruby/Gems/2.3.0/gems/liquid-4.0.3/lib/liquid/block_body.rb:91:in `render'
  /Library/Ruby/Gems/2.3.0/gems/liquid-4.0.3/lib/liquid/template.rb:208:in `block in render'
  /Library/Ruby/Gems/2.3.0/gems/liquid-4.0.3/lib/liquid/template.rb:242:in `with_profiling'
  /Library/Ruby/Gems/2.3.0/gems/liquid-4.0.3/lib/liquid/template.rb:207:in `render'
  /Library/Ruby/Gems/2.3.0/gems/liquid-4.0.3/lib/liquid/template.rb:220:in `render!'
  /Library/Ruby/Gems/2.3.0/gems/jekyll-3.8.5/lib/jekyll/liquid_renderer/file.rb:30:in `block (2 levels) in render!'
  /Library/Ruby/Gems/2.3.0/gems/jekyll-3.8.5/lib/jekyll/liquid_renderer/file.rb:42:in `measure_bytes'
  /Library/Ruby/Gems/2.3.0/gems/jekyll-3.8.5/lib/jekyll/liquid_renderer/file.rb:29:in `block in render!'
  /Library/Ruby/Gems/2.3.0/gems/jekyll-3.8.5/lib/jekyll/liquid_renderer/file.rb:49:in `measure_time'
  /Library/Ruby/Gems/2.3.0/gems/jekyll-3.8.5/lib/jekyll/liquid_renderer/file.rb:28:in `render!'
  /Library/Ruby/Gems/2.3.0/gems/jekyll-3.8.5/lib/jekyll/tags/include.rb:140:in `block in render'
  /Library/Ruby/Gems/2.3.0/gems/liquid-4.0.3/lib/liquid/context.rb:123:in `stack'
  /Library/Ruby/Gems/2.3.0/gems/jekyll-3.8.5/lib/jekyll/tags/include.rb:137:in `render'
  /Library/Ruby/Gems/2.3.0/gems/liquid-4.0.3/lib/liquid/block_body.rb:103:in `render_node_to_output'
  /Library/Ruby/Gems/2.3.0/gems/liquid-4.0.3/lib/liquid/block_body.rb:91:in `render'
  /Library/Ruby/Gems/2.3.0/gems/liquid-4.0.3/lib/liquid/template.rb:208:in `block in render'
  /Library/Ruby/Gems/2.3.0/gems/liquid-4.0.3/lib/liquid/template.rb:242:in `with_profiling'
  /Library/Ruby/Gems/2.3.0/gems/liquid-4.0.3/lib/liquid/template.rb:207:in `render'
  /Library/Ruby/Gems/2.3.0/gems/liquid-4.0.3/lib/liquid/template.rb:220:in `render!'
  /Library/Ruby/Gems/2.3.0/gems/jekyll-3.8.5/lib/jekyll/liquid_renderer/file.rb:30:in `block (2 levels) in render!'
  /Library/Ruby/Gems/2.3.0/gems/jekyll-3.8.5/lib/jekyll/liquid_renderer/file.rb:42:in `measure_bytes'
  /Library/Ruby/Gems/2.3.0/gems/jekyll-3.8.5/lib/jekyll/liquid_renderer/file.rb:29:in `block in render!'
  /Library/Ruby/Gems/2.3.0/gems/jekyll-3.8.5/lib/jekyll/liquid_renderer/file.rb:49:in `measure_time'
  /Library/Ruby/Gems/2.3.0/gems/jekyll-3.8.5/lib/jekyll/liquid_renderer/file.rb:28:in `render!'
  /Library/Ruby/Gems/2.3.0/gems/jekyll-3.8.5/lib/jekyll/renderer.rb:126:in `render_liquid'
  /Library/Ruby/Gems/2.3.0/gems/jekyll-3.8.5/lib/jekyll/renderer.rb:79:in `render_document'
  /Library/Ruby/Gems/2.3.0/gems/jekyll-3.8.5/lib/jekyll/renderer.rb:62:in `run'
  /Library/Ruby/Gems/2.3.0/gems/jekyll-3.8.5/lib/jekyll/site.rb:479:in `render_regenerated'
  /Library/Ruby/Gems/2.3.0/gems/jekyll-3.8.5/lib/jekyll/site.rb:472:in `block in render_pages'
  /Library/Ruby/Gems/2.3.0/gems/jekyll-3.8.5/lib/jekyll/site.rb:471:in `each'
  /Library/Ruby/Gems/2.3.0/gems/jekyll-3.8.5/lib/jekyll/site.rb:471:in `render_pages'
  /Library/Ruby/Gems/2.3.0/gems/jekyll-3.8.5/lib/jekyll/site.rb:192:in `render'
  /Library/Ruby/Gems/2.3.0/gems/jekyll-3.8.5/lib/jekyll/site.rb:71:in `process'
  /Library/Ruby/Gems/2.3.0/gems/jekyll-3.8.5/lib/jekyll/command.rb:28:in `process_site'
  /Library/Ruby/Gems/2.3.0/gems/jekyll-3.8.5/lib/jekyll/commands/build.rb:65:in `build'
  /Library/Ruby/Gems/2.3.0/gems/jekyll-3.8.5/lib/jekyll/commands/build.rb:36:in `process'
  /Library/Ruby/Gems/2.3.0/gems/jekyll-3.8.5/lib/jekyll/commands/build.rb:18:in `block (2 levels) in init_with_program'
  /Library/Ruby/Gems/2.3.0/gems/mercenary-0.3.6/lib/mercenary/command.rb:220:in `block in execute'
  /Library/Ruby/Gems/2.3.0/gems/mercenary-0.3.6/lib/mercenary/command.rb:220:in `each'
  /Library/Ruby/Gems/2.3.0/gems/mercenary-0.3.6/lib/mercenary/command.rb:220:in `execute'
  /Library/Ruby/Gems/2.3.0/gems/mercenary-0.3.6/lib/mercenary/program.rb:42:in `go'
  /Library/Ruby/Gems/2.3.0/gems/mercenary-0.3.6/lib/mercenary.rb:19:in `program'
  /Library/Ruby/Gems/2.3.0/gems/jekyll-3.8.5/exe/jekyll:15:in `<top (required)>'
  /usr/local/bin/jekyll:22:in `load'
  /usr/local/bin/jekyll:22:in `<top (required)>'

A: test-wrapper.html
{% include test.html test-var=include.test-var %}

test.html
Got {{ include.test-var }}


text:
Q: RabbitMQ exchange bind replicating messages published to one exchange across two other exchanges I have 3 different exchanges in my rabbitMQ i am trying to route all the messages sent to mainex across the other two exchanges dmyex and monex i tried to use the channel.exchngeBind method to bind the exchanges.
I am still not able to see the messages published to mainex going to dmyex and monex.
Is this possible in RabbitMq?
Is there any mistake in what i am doing here?
ch.exchangeDeclare("mainex", DIRECT_EXCHANGE_TYPE, true, false, null);
ch.exchangeDeclare("dmyex", CONSISTENT_HASH_EXCHANGE_TYPE, true, false, null);
ch.exchangeDeclare("monex", CONSISTENT_HASH_EXCHANGE_TYPE, true, false, null);
ch.exchangeBind("dmyex","mainex","abcd_KEY");
ch.exchangeBind("monex","mainex","abcd_KEY");

A: I think that the exchange mainex will need to be a Topic exchange in order for wildcard routing to work, as Direct exchanges do their routing based on exact matching of the routing key. Per this CloudAMQP blog post on exchange types and routing:

A direct exchange delivers messages to queues based on a message routing key. The routing key is a message attribute added to the message header by the producer. Think of the routing key as an "address" that the exchange is using to decide how to route the message. A message goes to the queue(s) with the binding key that exactly matches the routing key of the message.

(This is also touched on in this answer to a question about wildcard routing keys on SO)
That should be enough to get your routing working. Perhaps even more simply, if you are going to match any routing key for all of your exchanges that are bound to mainex, you could just make mainex a Fanout exchange.

A: Just figured out the below model is working.
   ch.exchangeDeclare("mainex", DIRECT_EXCHANGE_TYPE, true, false, null);
   ch.exchangeDeclare("dmyex", CONSISTENT_HASH_EXCHANGE_TYPE, true, false, null);
   ch.exchangeDeclare("mongoex", CONSISTENT_HASH_EXCHANGE_TYPE, true, false, null);

   ch.exchangeBind("dmyex","mainex", "abcd_KEY");
   ch.exchangeBind("monex","mainex", "abcd_KEY");

   for (String q : Arrays.asList("sharding: dmyex - rabbit@node1 - 0", "sharding: dmyex - rabbit@node2 - 0","sharding: dmyex - rabbit@node3 - 0","sharding: dmyex - rabbit@node4 - 0","sharding: dmyex - rabbit@node5 - 0","sharding: dmyex - rabbit@node6 - 0")) {
       ch.queueBind(q, "dmyex", "1");
   }

   for (String q : Arrays.asList("sharding: mongoex - rabbit@node1 - 0", "sharding: mongoex - rabbit@node2 - 0","sharding: mongoex - rabbit@node3 - 0","sharding: mongoex - rabbit@node4- 0","sharding: mongoex - rabbit@node5 - 0","sharding: mongoex - rabbit@node6 - 0")) {
       ch.queueBind(q, "mongoex", "1");
   }

     AMQP.BasicProperties.Builder bldr = new AMQP.BasicProperties.Builder();
     for (int i = 0; i < 10; i++) {
     ch.basicPublish("mainex", "abcd_KEY", bldr.build(), "TestMessage".getBytes("UTF-8"));````


text:
Q: Selective group by, np.where Pandas/Python query df_have
A  B C
1  1  10
1  1  10
1  2  5
1  3  6
1  4  7

df_want
A  B C    D
1  1  10  20
1  1  10  20
1  2  5   5
1  3  6   6
1  4  7   7

Trying to group by column A, B only if column B is 1 or 2. If B is 1 or 2 then output column D as the SUM of column C. Else keep set column D = column C.
Sample code gives error:
df_want['D']=np.where((df_want['B'].isin([1,2]),
             df_want['A','B'].map(df_want.groupby(['A','B'])['C'].sum()),
             df_want['C'])

The issue is occuring here: df_want['A','B'].map.. if I only put df_want.A.map then the code runs but the output is wrong. I need it to only map the sum if col B is 1 or 2

A: Change the sum to transform('sum')
np.where(df_want['B'].isin([1,2]),
             df_want.groupby(['A','B'])['C'].transform('sum'), df_want['C'])

A: You can use loc
df['D'] = df['C'].copy()
df.loc[df['B'].isin([1,2]), 'D'] = df.loc[df['B'].isin([1,2])].groupby(['A', 'B']).C.transform('sum')

    A   B   C   D
0   1   1   10  20
1   1   1   10  20
2   1   2   5   5
3   1   3   6   6
4   1   4   7   7


text:
Q: How to encrypt a string in Java by just using a password? I'm developing an application where I need to encrypt text using a user-entered password (as a key) and store it. User can decrypt his data whenever he wants by entering the password. The security of the data should depend upon the complexity and length of the password.
I have used AES before but here I can't use it as the encryption key in AES has to be of a specific length. I want something where the encryption key could be of any length.
I just can't figure out which encryption method or algorithm to use.

A: Search for PBKDF - password based key derivation function. Please note - passwords are not keys (passwords are having different length and usually less entropy).
Though you may derive a key from the password. Commonly used password-based key derivation functions used today are PBKDF2, Argon2, BCrypt or SCrypt. Just search for them.
You may check some examples
IvParameterSpec ivParamSpec = new IvParameterSpec(iv);

PBEParameterSpec pbeParamSpec = new PBEParameterSpec(psswdSalt, PBKDF_INTERATIONS, ivParamSpec);
PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray());
SecretKeyFactory pbeKeyFactory =
SecretKeyFactory.getInstance("PBEWithHmacSHA256AndAES_128");
SecretKey pbeKey = pbeKeyFactory.generateSecret(pbeKeySpec);

Cipher cipher = Cipher.getInstance(PBE_CIPHER_NAME);
cipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);

In theory - you may use a simple hash (e.g. sha-256) and take only necessary number of bits to derive a key. The issue is that the password are usually not that random if it is easy for a human to remember; this means that they are vulnerable to brute-force attacks or dictionary attacks.


text:
Q: ValueError: invalid literal for float(): 17/08/2015 I'm getting this error "ValueError: invalid literal for float(): 17/08/2015". This is the last row in the file I'm reading and it follows the same format as the others. The code for the script is below.
I'm wondering. Is the error actually occurring throughout the file but it's being flagged as the only error because it's the last of the errors, if that makes sense to anyone.
    import numpy as np
    import pandas as pd
    import matplotlib.pyplot as plt

    rankings = pd.read_csv('data/rankingunitsdata.csv', parse_dates='date')
    rankings.plot('date','rankingpos')

    x = rankings.date.values
    y = rankings.rankingpos.values

    plt.plot(x,y, 'o')
    plt.xlabel('Ranking Position')
    plt.ylabel('Date')
    plt.show()

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-15-b6d9eb0809d3> in <module>()
----> 1 plt.plot(x,y, 'o')
      2 plt.xlabel('Ranking Position')
      3 plt.ylabel('Date')
      4 plt.show()

C:\Anaconda3\lib\site-packages\matplotlib\pyplot.py in plot(*args, **kwargs)
   3097         ax.hold(hold)
   3098     try:
-> 3099         ret = ax.plot(*args, **kwargs)
   3100         draw_if_interactive()
   3101     finally:

C:\Anaconda3\lib\site-packages\matplotlib\axes\_axes.py in plot(self, *args, **kwargs)
   1372
   1373         for line in self._get_lines(*args, **kwargs):
-> 1374             self.add_line(line)
   1375             lines.append(line)
   1376

C:\Anaconda3\lib\site-packages\matplotlib\axes\_base.py in add_line(self, line)
   1502             line.set_clip_path(self.patch)
   1503
-> 1504         self._update_line_limits(line)
   1505         if not line.get_label():
   1506             line.set_label('_line%d' % len(self.lines))

C:\Anaconda3\lib\site-packages\matplotlib\axes\_base.py in _update_line_limits(self, line)
   1513         Figures out the data limit of the given line, updating self.dataLim.
   1514         """
-> 1515         path = line.get_path()
   1516         if path.vertices.size == 0:
   1517             return

C:\Anaconda3\lib\site-packages\matplotlib\lines.py in get_path(self)
    872         """
    873         if self._invalidy or self._invalidx:
--> 874             self.recache()
    875         return self._path
    876

C:\Anaconda3\lib\site-packages\matplotlib\lines.py in recache(self, always)
    573                 x = ma.asarray(xconv, np.float_)
    574             else:
--> 575                 x = np.asarray(xconv, np.float_)
    576             x = x.ravel()
    577         else:

C:\Anaconda3\lib\site-packages\numpy\core\numeric.py in asarray(a, dtype, order)
    472
    473     """
--> 474     return array(a, dtype, copy=False, order=order)
    475
    476 def asanyarray(a, dtype=None, order=None):

ValueError: could not convert string to float: '17/08/2015'

A: The error occurs because you are trying to plot some stuff with dates as strings on the x-axis while plt.plot() expects numerical values. Hence it fails when it tries to convert '17/08/2015' to a float, which cannot work.
You need to convert your x-values to datetime objects and then use plt.plot_date, which is for example demonstrated here.


text:
Q: Printing unexpanded recursive variables in gnu make Is there a way to print the unexpanded definition of a recursive variable?  I have a complicated build system, and a user can set some values.  I'd like to echo the user definition to another file, for later use.
For example,
externals = $(HOME)/externals

all:
    echo $(externals)

doesn't work, because it echos using the current definition of HOME.  I'd like it to echo
the literal string $(HOME)/externals without expanding $(HOME).

A: The value function is probably what you want here.

8.8 The value Function
The value function provides a way for you to use the value of a variable without having it expanded. Please note that this does not undo expansions which have already occurred; for example if you create a simply expanded variable its value is expanded during the definition; in that case the value function will return the same result as using the variable directly.
The syntax of the value function is:
    $(value variable)

Note that variable is the name of a variable, not a reference to that variable. Therefore you would not normally use a '$' or parentheses when writing it. (You can, however, use a variable reference in the name if you want the name not to be a constant.)
The result of this function is a string containing the value of variable, without any expansion occurring. For example, in this makefile:
    FOO = $PATH

    all:
            @echo $(FOO)
            @echo $(value FOO)

The first output line would be ATH, since the "$P" would be expanded as a make variable, while the second output line would be the current value of your $PATH environment variable, since the value function avoided the expansion.
The value function is most often used in conjunction with the eval function (see Eval Function).

Though in addition to this you are going to need to use single quotes on that echo line or the shell will expand things on you.
$ cat Makefile
externals = $(HOME)/externals

all:
        echo $(externals)

allv:
        echo $(value externals)

allvq:
        echo '$(value externals)'
$ make all
echo /home/user/externals
/home/user/externals
$ make allv
echo $(HOME)/externals
/bin/sh: HOME: command not found
/externals
$ make allvq
echo '$(HOME)/externals'
$(HOME)/externals