text:
Q: Derivation of Maxima & Minima of functions having two variables
For two variables i.e $\quad u=f(x,y)$:
Condition for Maxima and Minima is given by:
$$\frac{\partial f}{\partial x}=0 \quad , \quad \frac{\partial f}{\partial y}=0 \quad \implies \text{Critical points}$$
$$H(x,y)= f_{xx}f_{yy} \, - \, (fxy)^2 \quad \implies \text{Checking function}$$
$$\text{For Maxima:} \quad f_{xx}<0 \, , \,  H(x,y)>0 \quad |_{\text{(x,y)=Critical points}}$$
$$\text{For Minima:} \quad f_{xx}>0 \, , \,  H(x,y)>0 \quad |_{\text{(x,y)=Critical points}}$$

My Thoughts:
For one variable i.e $\quad u=f(x)$
Condition for Maxima and Minima is given by:
$$\frac{d f}{d x}=0 \quad \quad \implies \text{Critical points}$$
$$\text{For Maxima:} \quad f_{x}<0 \,  \quad |_{\text{x=Critical points}}$$
$$\text{For Minima:} \quad f_{xx}>0 \,  \quad |_{\text{x=Critical points}}$$
Extending this concept:
$$du= \frac{\partial f}{\partial x}dx \, + \, \frac{\partial f}{\partial y}dy \quad  [\because u=f(x,y)]$$
For Critical Points:  $\quad du=0$
$$\implies \frac{\partial f}{\partial x}dx \, + \, \frac{\partial f}{\partial y}dy =0 $$
$$\implies \frac{\partial f}{\partial x} =0 \quad \& \quad  \frac{\partial f}{\partial y} =0 \quad \dots(1)$$
For Maxima : $\quad d^2u <0 \, $ &
For Minima : $\quad d^2u >0 \, $
$$\therefore d^2u=d(du)$$
$$=d(\frac{\partial f}{\partial x}dx \, + \, \frac{\partial f}{\partial y}dy)$$
$$\implies d^2u=d(\frac{\partial f}{\partial x}dx)\, + \, d(\frac{\partial f}{\partial y}dy) \quad \dots (2)$$
let $M(x,y)=\frac{\partial f}{\partial x}dx $, then
$$d(M)=\frac{\partial M}{\partial x}dx \, + \, \frac{\partial M}{\partial y}dy \quad \dots (3)$$
$$\frac{\partial M}{\partial x}=\frac{\partial }{\partial x} (\frac{\partial f}{\partial x}dx)$$
$$=\frac{\partial ^2 f}{\partial x^2}dx \, + \, \frac{\partial f}{\partial x}\frac{d }{d x} dx $$
$$\implies \frac{\partial M}{\partial x}=\frac{\partial ^2 f}{\partial x^2}dx \, + \, \frac{\partial f}{\partial x}\frac{d^2 x }{d x} \quad \dots (4) $$
$$\text{similarly,} \quad \frac{\partial M}{\partial y}=\frac{\partial ^2 f}{\partial y \, \partial x}dx \, + \, \frac{\partial f}{\partial x}\frac{d }{d y} dx $$
$$=\frac{\partial ^2 f}{\partial y \, \partial x}dx \, + \, \frac{\partial f}{\partial x}\cdot 0 $$
$$\implies \frac{\partial M}{\partial y}=\frac{\partial ^2 f}{\partial y \, \partial x}dx  \quad \dots (5) $$
$$\implies dM= (\frac{\partial ^2 f}{\partial x^2}dx \, + \, \frac{\partial f}{\partial x}\frac{d^2 x }{d x})dx \, + \, (\frac{\partial ^2 f}{\partial y \, \partial x}dx)dy   $$
$$\implies dM=\frac{\partial ^2 f}{\partial x^2}(dx)^2 \, + \, \frac{\partial f}{\partial x}d^2 x  \, + \, \frac{\partial ^2 f}{\partial y \, \partial x}dxdy \quad \dots (6)$$
similarly let $N(x,y)=\frac{\partial f}{\partial y}dy $, then
$$d(N)=\frac{\partial N}{\partial x}dx \, + \, \frac{\partial N}{\partial y}dy \quad \dots (7)$$
$$\frac{\partial N}{\partial x}=\frac{\partial }{\partial x} (\frac{\partial f}{\partial y}dy)$$
$$=\frac{\partial ^2 f}{\partial x \, \partial y}dy  $$
$$\text{and,} \quad \frac{\partial N}{\partial y}=\frac{\partial ^2 f}{\partial y^2}dy \, + \, \frac{\partial f}{\partial y}\frac{d^2 y }{d y}  $$
$$\implies dN=\frac{\partial ^2 f}{\partial x \, \partial y}dy\, dx \, + \, \frac{\partial ^2 f}{\partial y^2}(dy)^2 \, + \, \frac{\partial f}{\partial y}d^2 y  \, + \,  \quad \dots (8)$$
$$\implies d^2 u=\frac{\partial ^2 f}{\partial x^2}(dx)^2 +\frac{\partial f}{\partial x}d^2 x +\frac{\partial ^2 f}{\partial y \partial x}dx \, dy  +\frac{\partial ^2 f}{\partial x \partial y}dy \, dx \, + \frac{\partial ^2 f}{\partial y^2}(dy)^2 +\frac{\partial f}{\partial y}d^2 y   \quad \dots (9)$$
let us assume $f(x,y)$ to be a continuous function
,then according to Schwarz's Theorem: $$\frac{\partial ^2 f}{\partial y \partial x}=\frac{\partial ^2 f}{\partial x \partial y}$$
$$\therefore d^2u=\frac{\partial ^2 f}{\partial x^2}(dx)^2 +\frac{\partial f}{\partial x}d^2 x +2 \cdot \frac{\partial ^2 f}{\partial y \partial x}dx \, dy   \, + \frac{\partial ^2 f}{\partial y^2}(dy)^2 +\frac{\partial f}{\partial y}d^2 y  \quad \dots (10) $$
so, for maxima:
$$\frac{\partial ^2 f}{\partial x^2}(dx)^2 +\frac{\partial f}{\partial x}d^2 x +2 \cdot \frac{\partial ^2 f}{\partial y \partial x}dx \, dy   \, + \frac{\partial ^2 f}{\partial y^2}(dy)^2 +\frac{\partial f}{\partial y}d^2 y <0 \quad |_{\text{(x,y)=Critical points}}$$
$$\implies \frac{\partial ^2 f}{\partial x^2}(dx)^2 + \frac{\partial ^2 f}{\partial y^2}(dy)^2 +  2 \frac{\partial ^2 f}{\partial y \partial x}dx \, dy <0 \quad |_{\text{(x,y)=Critical points}}$$
$$[\because \frac{\partial f}{\partial x}=0 \quad , \quad \frac{\partial f}{\partial y}=0 \quad |_{(x,y)= \text{Critical points}}]$$
$$\implies (f_{xx})\cdot(dx)^2 + (f_{yy})\cdot(dy)^2 +  2 (f_{xy})\cdot dx \, dy <0 \,|_{\text{(x,y)=Critical points}}$$
similarly, for minima:
$$ \frac{\partial ^2 f}{\partial x^2}(dx)^2 + \frac{\partial ^2 f}{\partial y^2}(dy)^2 +  2 \frac{\partial ^2 f}{\partial y \partial x}dx \, dy >0 \quad |_{\text{(x,y)=Critical points}}$$
$$\implies (f_{xx})\cdot(dx)^2 + (f_{yy})\cdot(dy)^2 +  2 (f_{xy})\cdot dx \, dy >0 \,|_{\text{(x,y)=Critical points}}$$
Now how to proceed to derive the condition,please help...


text:
Q: How to transpose cell data by section in Open Refine? I have a data table that looks like this:
Name | Date-Freq | Date-Amount | Date-Freq | Date-Amount
A    |      4    |    3000     |     8     |   9000
B    |      5    |    4000     |     9     |   7000
C    |      6    |    5000     |     10    |   8000

and I want it to look like this:
Name |     Date    |  Freq | Amount
A    |  July 2014  |   4   | 3000
A    |  Aug 2014   |   8   | 9000
B    |  July 2014  |   5   | 4000
B    |  Aug 2014   |   9   | 7000
C    |  July 2014  |   6   | 5000
C    |  Aug 2014   |   10  | 3000

What is the best way to do something like this? Should I just create two new columns?

A: What you want to accomplish will require lots of steps and faceting and adding new columns, etc.  But you can accomplish this with OpenRefine, YES.
You will need to use a combination of:

*

*Always work in Records mode (not row mode) for any kind of Merging work.

*Transpose Cells across columns into rows (into one MERGE column with prepend)

*Moving your Name column to beginning column.

*Fill down on your Name column (because it is now blank on some cells after the Transpose. and later you might need to fill down again after any particular Transpose or Merging.)

*Use Custom Text Faceting with value.startsWith("Amount") etc.

*Use Add new column based on to create new columns based on the MERGE column

*Move Columns as necessary to do Step 2 again.

*Repeat steps as necessary.

Here is an example OpenRefine project showing the beginning of what happens after the 1st set of the above steps (Use Undo/Redo to see, doesn't show Facets though):
OpenRefine Project with Transpose across cells into one column

redpajama_set_name: RedPajamaStackExchange


text:
Q: Problem in enabling APC on PHP 5.3.6 I am having a problem in enabling the APC Cache. Here is my configuration.
PHP 5.3.6
Apache 2.2.19
Windows 7

I have downloaded the php_apc.dll from below URl:
http://downloads.php.net/pierre/php_apc-20110109-5.3-nts-vc9-x86.zip
I have placed that dll in php's extension folder and placed the below code in php.ini
extension=php_apc.dll

Next anything remain to be enable the APC cache? Because when I place above line in PHP.ini then apache is not restarting.
Any help much appreciated.
Edit:
[Tue Sep 06 14:22:28 2011] [notice] Parent: Received restart signal -- Restarting the server.
[Tue Sep 06 14:22:33 2011] [warn] NameVirtualHost *:80 has no VirtualHosts
rocess is ending.
[Tue Sep 06 14:22:29 2011] [notice] Child 4212: Released the start mutex
[Tue Sep 06 14:23:00 2011] [notice] Child 4212: Waiting 270 more seconds for 1 worker threads to finish.
[Tue Sep 06 14:23:04 2011] [notice] Child 4212: All worker threads have exited.
[Tue Sep 06 14:23:04 2011] [notice] Child 4212: Child process is exiting

A: What happens in Apache's main error.log when you restart it? This should give you a clue what is wrong...
Also since you are running PHP under Apache, I'm guessing you are probably running the Thread-Safe version (Non Thread-Safe versions are mainly for running PHP as an ISAPI module under IIS), and the file you have downloaded seems to be Non Thread-Safe (it has nts in the file name). You should be using the Thread-Safe build with Apache - try using this file instead.
Also, make sure you are using a VC9 build of PHP distributed from php.net - the DLL will have been built against these releases and is not guaranteed to work with anyone else's distributions. It is certainly not guaranteed to work with a VC6 build, if for some reason this is what you are using.
Where is your Apache build from?


text:
Q: PainterSVG can not load .svgz file, how can I convert it to .svg file to load? I need to edit the svg pictures with PainterSVG, but it only loads .svg file, and some of the files I received are .svgz
Question: how can I convert those .svgz files into .svg files?

A: svgz is a g-zipped svg file. Try to rename xyfile.svgz into xyfile.svg.gzip and extract the file (or, if you have a tool to unzip gzip with whatever ending, just use it).
note: use gzip, not zip.


text:
Q: What's the significance of weird phrases? In Pokémon: Detective Pikachu (2019), when Tim and his Pokémon partner Pikachu are about to meet Mime, there is a following discussion:

Tim: We're not cops.
Pikachu: Grow some berries. You're bigger, tougher-looking.

Which sounds close to Grow some balls.

In another scene, Pikachu speaks to Tim near Magikarp:

Pikachu: Magikarp can evolve into Gyarados. All it needs is a little kick. Water in the hole! In my head, I saw that differently.

Which sounds close to Fire in the hole.

What's the significance of these weird phrases?

A: In the Pokémon games (and anime), Pokémon use berries to cure status effects and restore HP. This is just a little nod towards it and a more kid-friendly way of saying it.
"Water in the hole" is probably just a little reference to the fact that Magikarp is a water Pokémon.


text:
Q: How to check for an empty entry box in Tkinter and assign the value 0 to it? I have 3 labels and entry boxes, one is Sandwich, the other is drinks and the third one for showing their calculated costs.
There, I expect the user to enter the number of sandwiches and drinks they've had and calculate their price and show it in the third box by using this formula:
totalCost = (cod*30)+(cos*100)
costtotal.set(totalCost)

And it does so perfectly.
However, the problem is, that for example a user doesn't enter anything in the drinks field, I want the interpreter to interpret that empty field as 0 and calculate the sum. But, my program doesn't calculate it if any of the two fields (Drinks and Sandwiches) are empty. So, to counter this I tried:
if not drinks.get():
   yourVar = "0"
   cod=float(yourVar)

This is the error message I get:
File "C:/Users/Dell E6430/Desktop/trying.py", line 18, in Ref
    cod=float(drinks.get())
ValueError: could not convert string to float:
I don't get this error message when I input both fields.
However, it isn't working and the result is same. So, how do I solve that? Thanks.
Here's the full code:
from tkinter import*

root=Tk()
root.geometry("1600x800+0+0")

#------- convert to string
drinks=StringVar()
costtotal=StringVar()
sandwich=StringVar()

#----Frame
f1=Frame(root,width=800, height=700,relief=SUNKEN)
f1.pack(side=LEFT)

def Ref():
    cos=float(sandwich.get())
    cod=float(drinks.get())

    if not drinks.get():
        yourVar = "0"
        cod=float(yourVar)

    totalCost = (cod*30)+(cos*100)
    costtotal.set(totalCost)

lblSandwich=Label(f1,font=('arial',16,'bold'),text="Sandwich" , bd=16, anchor='w')
lblSandwich.grid(row=0,column=0)
txtSandwich=Entry(f1,font=('arial',16,'bold'),textvariable=sandwich,bd=10,insertwidth=4,bg="powder blue",justify='right')
txtSandwich.grid(row=0,column=1)

lblDrinks=Label(f1,font=('arial',16,'bold'),text="Drinks" , bd=16, anchor='w')
lblDrinks.grid(row=1,column=0)
txtDrinks=Entry(f1,font=('arial',16,'bold'),textvariable=drinks,bd=10,insertwidth=4,bg="powder blue",justify='right')
txtDrinks.grid(row=1,column=1)

lblcostTotal=Label(f1,font=('arial',16,'bold'),text="Cost of Drinks" , bd=16, anchor='w')
lblcostTotal.grid(row=2,column=0)
txtcostTotal=Entry(f1,font=('arial',16,'bold'),textvariable=costtotal,bd=10,insertwidth=4,bg="powder blue",justify='right')
txtcostTotal.grid(row=2,column=1)

btnTotal=Button(f1,padx=16,pady=8,bd=16,fg="black",font=('arial',16,'bold'),width=10,text="Total", bg="Powder Blue"\
,command=Ref).grid(row=7,column=1)

root.mainloop()

EDIT: By doing
cod=drinks.get()
if not drinks.get():
    yourVar = "0"
    cod=float(yourVar)
else:
    cod=float(drinks.get())

the program runs fine now.

A: You cannot run float() over anything that is not a valid number. You should probably first check if your get() is returning a number with isnumeric() then if true run float if not set value to zero. That will handle anything not a number and even if it is a letter.
Note I have cleaned up your code a bit to more closely follow PEP8 standards as well as updated your import to help prevent overwriting. import tkinter as tk is always preferred over *.
Try this:
import tkinter as tk

root = tk.Tk()
root.geometry("1600x800+0+0")
cost_total = tk.StringVar()
sandwich = tk.StringVar()
drinks = tk.StringVar()

f1 = tk.Frame(root, width=800, height=700, relief='sunken')
f1.pack(side='left')

def ref():
    d = drinks.get()
    s = sandwich.get()
    if d.isnumeric():
        cod = float(d)
    else:
        cod = 0

    if s.isnumeric():
        cos = float(s)
    else:
        cos = 0

    total_cost = (cod * 30) + (cos * 100)
    cost_total.set(total_cost)

tk.Label(f1, font=('arial', 16, 'bold'), text="Sandwich", bd=16, anchor='w').grid(row=0, column=0)
tk.Entry(f1, font=('arial', 16, 'bold'), textvariable=sandwich, bd=10, insertwidth=4,
         bg="powder blue", justify='right').grid(row=0, column=1)

tk.Label(f1, font=('arial', 16, 'bold'), text="Drinks", bd=16, anchor='w').grid(row=1, column=0)
tk.Entry(f1, font=('arial', 16, 'bold'), textvariable=drinks, bd=10, insertwidth=4,
         bg="powder blue", justify='right').grid(row=1, column=1)

tk.Label(f1, font=('arial', 16, 'bold'), text="Cost of Drinks", bd=16, anchor='w').grid(row=2, column=0)
tk.Entry(f1, font=('arial', 16, 'bold'), textvariable=cost_total, bd=10, insertwidth=4,
         bg="powder blue", justify='right').grid(row=2, column=1)

tk.Button(f1, padx=16, pady=8, bd=16, fg="black", font=('arial', 16, 'bold'), width=10,
          text="Total", bg="Powder Blue", command=ref).grid(row=7, column=1)

root.mainloop()

Results:

To answer you question in the comments you can use a list or a couple list to manage large amounts of fields. Consider the below and let me know if you have any questions.
Code:
import tkinter as tk

list_of_foods = [['Coffie', 30], ['Tea', 20], ['Sandwich', 100], ['Apple', 50]]

def ref():
    total = 0
    for ndex, entry in enumerate(entry_list):
        value = entry.get()
        if value.isnumeric():
            total += float(value) * list_of_foods[ndex][1]
            print(total)
        else:
            total += 0
    double_var.set(total)

root = tk.Tk()
double_var = tk.DoubleVar(root, value=0)
entry_list = []

for ndex, sub_list in enumerate(list_of_foods):
    tk.Label(root, text=sub_list[0]).grid(row=ndex, column=0)
    entry_list.append(tk.Entry(root))
    entry_list[-1].grid(row=ndex, column=1)

tk.Entry(root, textvariable=double_var).grid(row=len(entry_list)+2, column=0, columnspan=2)
tk.Button(root, text='Total', command=ref).grid(row=len(entry_list)+3, column=0, columnspan=2)
root.mainloop()

Results:


text:
Q: If GPS cannot fetch location, switch to network in Android I am trying to get location based on GPS or network but the problem is that if I take based on GPS location it takes lot of time to fetch the location details. Hence I would like implement a method where if GPS signal is very low fetch location using network provider. How do I determine the GPS signal? if do there is problem with this? GPS signal is always low even in open sky and hence it would always get to network provider?
How do I fix this problem?

A: Are you polling the location with LocationManager.GetLastKnownLocation, or are you getting updates asynchronously via requestLocationUpdates?
For the first, query for the location with the GPS_PROVIDER.  If it returns null, then query for NETWORK_PROVIDER
If you're getting notifications, request both.  Then you can implement onStatusChanged to tell when the GPS is available or not, and ignore network updates if it is, or use them if not (the location object tells you what the provider was).

A: Adding lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, ll); it will start fetching the gps using networ. Using location.getProvider() you should be able to differentiate to know whether its gps or network.


text:
Q: rails 5.2.0, sass-rails 5.0.7, bootstrap 4.3.1 Can't access bootstrap variables within .scss files I was having trouble with one of my Ruby on Rails projects when I tried to upgrade from bootstrap 3. I removed the bootstrap-sass gem and followed the instructions on this github page, but whenever I requested a page from the server, I got an error about undefined variables for colors.
I made a new rails project, with the sole purpose to get bootstrap 4 working.
My Gemfile:
source 'https://rubygems.org'

gem 'rails'
gem 'puma'
gem 'sass-rails'
gem 'uglifier'
gem 'coffee-rails'
gem 'jquery-rails'
gem 'turbolinks'
gem 'jbuilder'
gem 'bootsnap'
gem 'bootstrap', '~> 4.3.1'

group :development, :test do
  gem 'sqlite3', '1.3.13'
  gem 'byebug',  '9.0.6', platform: :mri
end

group :development do
  gem 'web-console',           '3.5.1'
  gem 'listen',                '3.1.5'
  gem 'spring',                '2.0.2'
  gem 'spring-watcher-listen', '2.0.1'
end

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

application.scss
@import "bootstrap";
@import "custom";

application.js
//= require jquery3
//= require popper
//= require bootstrap
//= require_tree .

custom.scss
@import "bootstrap";

h1 {
    color: $gray;
}

When I navigate to a page with an h1 element I get the following error message
Error: Undefined variable: "$gray".
        on line 4 of app/assets/stylesheets/custom.scss
        from line 2 of app/assets/stylesheets/application.scss
>>     color: $gray;

If I change the color in custom.scss to $red then the page loads perfectly, and I only get the error above if I remove the bootstrap imports, so some color imports are happening, while others are being ignored.
What do I need to do differently with bootstrap 4?

A: Maybe variables are different in Bootstrap 3 and 4?
You can check this file:
https://github.com/twbs/bootstrap/blob/master/scss/_variables.scss . There is no $gray; color variable. There are different shades of gray:
$gray-100: #f8f9fa !default;
$gray-200: #e9ecef !default;
$gray-300: #dee2e6 !default;
$gray-400: #ced4da !default;
$gray-500: #adb5bd !default;
$gray-600: #6c757d !default;
$gray-700: #495057 !default;
$gray-800: #343a40 !default;
$gray-900: #212529 !default;


text:
Q: Difference between port mapped and memory mapped access? Can anyone explain what's the difference between port mapping and memory mapping, and what having both accomplishes? Why is there port mapped, how does it differ in structure from memory maps, and is there any reason many architectures use both? Also, what is a "port" in this sense, because port can mean different things in different contexts?
Example: Port forwarding, port as a communications endpoint, "port mapping".
Say I write OUT to port 400h (fictive; just for example) (like in x86-64, etc.).
What or where am I writing to if it's not in memory? How is a "port" mapped, and what is it in this sense?

A: Memory-mapped I/O and port-mapped I/O are two complementary methods for I/O.
Memory-Mapped I/O
In memory-mapped systems, the I/O device is accessed like it is a part of the memory. Load and Store commands are executed for reading from and writing to I/O devices, just like they are used for the memory (port-mapped has special commands for I/O). This means I/O devices use the same address bus as memory, meaning that CPU can refer to memory or the I/O device based on the value of the address. This approach requires isolation in the address space: that is, addresses reserved for I/O should not be available to physical memory.
Below is an image of a simple, basic computer system. The case is much more complicated in contemporary systems.

Port-Mapped I/O
According to Wikipedia

Port-mapped I/O often uses a special class of CPU instructions
  specifically for performing I/O. This is found on Intel
  microprocessors, with the IN and OUT instructions. These instructions
  can read and write one to four bytes (outb, outw, outl) to an I/O
  device. I/O devices have a separate address space from general memory,
  either accomplished by an extra "I/O" pin on the CPU's physical
  interface, or an entire bus dedicated to I/O. Because the address
  space for I/O is isolated from that for main memory, this is sometimes
  referred to as isolated I/O.

As for the advantages and disadvantages: since the peripheral devices are slower than the memory, sharing data and address buses may slow the memory access. On the other hand, by the I/O simplicity memory-mapped systems provide, CPU requires less internal logic and this helps for faster, cheaper, less power consuming CPUs to be implemented. The logic is similar to that of RISC systems: reduce the complexity, get a more dedicated and a robust system which comes quite handy for embedded systems, for example.
On the contrary (again from Wiki):

Port-mapped I/O instructions are often very limited, often providing
  only for simple load and store operations between CPU registers and
  I/O ports, so that, for example, to add a constant to a port-mapped
  device register would require three instructions: read the port to a
  CPU register, add the constant to the CPU register, and write the
  result back to the port.

I strongly recommend that you read that wiki article for further information.

To answer one of your questions:

What or where am I writing to if it's not in memory?

You are writing to the registers of the I/O interface through the data bus, which later (when ready) sends the data to the actual I/O device. Below is an image of an example I/O device interface.

A: In Memory-Mapped I/O (simply MMIO) , devices are accessed through instructions which are actually meant to access memory. Each device gets certain memory address(es). However when you try to read or write to this part of the memory , a certain device (likely the northbridge) just sends it to the related device instead. Even if the computer doesn't have enough memory for such an address (as MMIO addresses are usually very high), it doesnt matter as the physical memory (that is the one you see when you look at the motherboard , the one known as RAM) isn't even related. If you have enough RAM for the address , it's either mapped to a higher non-I/O one , or just lost meaning you can't read or write to there.
Port-Mapped I/O (simply PMIO) is very different. You have different instructions used to read and write to ports. There is a port address-space just like the memory address-space where addresses are either I/O addresses that actually communicate with the devices or are just invalid. PMIO can essentially be thought as a MMIO with a seperate memory address-space just for I/O.

A: With names like 'I/O signal' and 'memory mapping' everything is made far more complicated than it actually is, and hence gives the person the impression there is a lot more to it and it covers an advanced topic. The tendency now is that people view it as something new. But this is very far from the case. Even Babbage in the 1830's drove his printer, this needed an I/O signal, albeit done by an axel and cogwheel. E.g. in the machines of Hero of Alexandria  2000 years ago or in theatres right back to Greek times, they always pulled a rope from a set of different ropes to control lights or the scenery, each rope is like an input and output line, it's as simple as that, the address is 'which line' i.e. which thing, memory or device we are choosing, the data is the information you are passing to or reading back from that memory or device.
Although big mainframe computers that filled buildings with cabinets, used things like 64bit right back in the 40's, and therefore dealt with I/O mapping just the same right back then long ago, e..g Konrad Zuse and his room sized computer used floating point that had about 20 digits in decimal in the 1930's, and had to drive things like his printer and his various light bulb indicators and his switches. But on tiny microprocessors the story is different they didn't get envisioned till the 60's and built till 1971. All these techniques using 8bit logic in the 80's, were used for microprocessors in 4bits in the 70's, 2 bits in the 60's and were used in 16bit in the 90's when everybody started to get a computer and hence because it was now in front of them started to discuss this I/O and memory mapping topic for the first time, and it appeared to be something new that came with the advent of the internet; then we had 32bit in the 00's and 64bit computers in the 10's, which caused there to be endless discussions of memory down data lines. In order to answer your question I will be talking about chips that electronics hobbyists bought 30-40 years ago, such as I did at that time, since later on, things got so advanced I was unable to build with the later chips, but the principles are just the same now,  the gates are just hidden inside bigger black boxed chips that incorporate other pins that deal with these operations going on much more in parallel (e.g. enabling many octal latches, many chips enabled at once in rows) , and the data and address buses have more lines, that's the only difference.
Well, I don't know anything about all the new languages or how it is on modern pc's now but I can tell you how it was in the old days when I used to build computers with chips.
All I/O Mapping and memory mapping means in simple terms, is if you strung up a load of light bulbs example for some celebration and had wires going to each and called the bulbs Memory locations, (i.e bulbs represent memory in the RAM, either on or off, and if you select location 0 you get wire 0, location 1, wire 1, loc 2 wire 2 and so on) if you added some more wires e.g. one wire is a bell, that particular location is not a memory it is a device, that you output to, using the OUT command, to make it ring. But it is viewed as a memory location from the computer's viewpoint, because it comes in as a wire to the MPU just the same. If another wire was added which was a switch that you operated externally, this is an I/O device, which would be an IN instruction TO the pc. So this is called I/O mapped I/O.
Now on computers, wires on buses represent address lines or data lines, BUT they are in binary, i.e. with 2 wires you can have 00 01 10 11 i.e. 4 combinations 2^2, so with 8 lines 2^8=256 possibilities, with 20 lines 2^20=1048576 with 30 lines 2^30=1073741824 (1 gig) of possibilities with 30 lines. So this is why it's called MAPPED, rather than just saying I/O and memory, they are saying I/O mapped, and memory mapped, because you are mapping the wires AS A COMBINATION y binary coding them. So if say you had 2 wires, 4 combinations, they can't just be connected to bulbs, (not to mention the current amplification required from the tiny voltages from the MPU, and the prevention of feedback current), but the 2 wires have to pass through a decoder (we used to use a 138 to decode 3 lines into 8 lines, a 164 to decode 4 binary lines into 16 lines.) Once through the decoder these 2 lines e.g. A0 and A1 (address0 and address 1 (LINES)), become 4 lines (on or off) for the particular bulb you are driving (in the case on a computer, THE MEMORY), but in some cases these location instead select some Input/output device, and say 'use me' instead, i.e. like memory, once located, data is then passed either one way or the other(using  clever tri state logic to cut off voltages on way each time) on the data bus lines D0..7 or D0..31 or whatever size the data on the computer is (you have a 2 bit, 4bit, 8bit, 16bit, 32bit, 64bit, 128bit, 256bit, computer, whatever computer you are building). So the data passes naturally in or out from the data lines to the memory or to the I/O device (IF it is memory mapped), but THIS SHOULD NOT BE CONFUSED WITH THE IN/OUT instructions, THIS IN and OUT means from some OTHER I/O memory block, a special I/O memory block inside the MPU assigned specially just for I/O, i.e. (not memory mapped), this I/O space you don't always get on some microprocessors, e.g. I don't think we had it on a 6502, but we had it on a z80. More  artistic chips used just memory mapping, e.g. in games consoles etc, more sensible but uninteresting (stayed in the book) chips go for I/O space as well. Memory mapped I/O is lightening speed since it incorporates memory addressing (which is super fast for the RAM), hence graphics type computer use just memory mapping for the I/O to get the speed. I/O mapped I/O is assigned for slow ports e.g. rs232, or the parallel port, and uses the IN OUT commands.
Now if instead of adding two wires, if you actually replaced two wires that originally went to bulbs and took some of those bulbs and replaced them with other things, e.g a bell on one and a switch on another, these are now not referenced (selected) with the IN and OUT instructions respectively, they are referenced by accessing that particular memory location that selects those wires (that were originally bulbs). So this is memory mapped I/O.
Memory Mapped I/O means that the actual address bus that normally goes to the memory (the RAM), is connected also to OTHER decoders (logic decoders), and when it senses the particular binary combination of address signals, it produces an output high, (e.g. if you had a load of and and not gates, and you said, if this and not that and so on, using pins A0..A20 or whatever size your address bus is), then this high signal ENABLES a latch, (for a particular device, like a serial port, a parallel port), this latch then PASSES the data on the data bus, through to the I/O device. This is for writing to the I/O device. Reading works the opposite way round, the I/O device, passes the data back, and if I remember rightly, it sends the exact same address code combination onto the address lines.
I presume, it must work this way the same today, except they'll just be far more data and address lines.
You literally are WIRING the I/O to the address lines. Hence the I/O is effectively MAPPED into the memory space, as though it were memory. But another latch disables the address pins from accessing the ram at the same time, so that you don't get voltages of two address or data sources on the same line, which would damage the chips.
With the IN and OUT instruction, we had this 40 years ago, on the z80 chip. This is for special cases where the chip actually deals with I/O itself a different way, i.e. it is not memory mapped. (i.e. with memory mapped, you just read or write to the memory location, but with IN and OUT you are already telling the CPU that it is an I/O signal and not memory). So with the IN/OUT instruction, this has its own I/O address space (which is extra to the memory of the ram), this I/O Ram, as it Appears to be, has a set of addresses just the same, except you are directly accessing the device through a decoder attach to those I/O addresses, and you are not access the I/O device from the standard address pins, this is for the IN/OUT instruction.
When you IN and OUT a STRING I don't know x86 but presumably this means you're sending or receiving data on the data bus (using all the data pins D0..D15 or whatever size the data bus is) MANY TIMES IN SERIES at the maximum data rate possible for that particular I/O device (perhaps to do this it uses some kind of handshaking signal you'll have to look it up.) So, the data on the D0..63 lines (or D0..31 on old pc's or D0..15 on late 80's early 90's pcs, or D0..7 or 80's and pre 80's pcs, is in SERIES one after the other, instead of just one time with IN and OUT. I.e. INSTR and OUTSTR is just multiple IN's and OUT's at some defined data rate. E.g. if you were accessing the internet, you'd want a lot of information in and out at each time, so you'd be using in and out of data bytes, which for this case are best passed as strings of ASCII codes for letters and numbers. These commands are exactly the same as if you used the IN and OUT instructions in a loop where the count is the string length.
If you are accessing e.g. the pc speaker you'd just be passing one piece of data at a time using OUT.
If you were reading from the parallel port, you'd be doing IN, and using the code for the I/O address of the port. Writing to it, e.g. to drive old printers or robotics by electronic signals, you'd use the OUT command. The parallel port and serial port (old RS232) are typical ports that were used. The RS232 is serial data, only one bit allowed in or out, so if you were reading from an rs232, you'd only have 1 bit of the byte that is relevant,same with outputting. The baud rate is about 17kHz max for an rs232, but these used to drive electronics a lot, back in the days, I used to build rs232 circuits, e.g. to read voltages or drive PIC micro-controllers.
Each port, is named e.g. COM1 COM2 COM3 COM4 and they have I/O addresses. I'm not sure at hand here, but they are similar to e.g. 3F8h 378h  (h=hex address)
I am not sure about the modern ports but if you were writing to the USB, this will be most likely memory mapped I/O for greater speed.
The PS/2 keyboard port, I think this uses the IN instruction, to read data from the keyboard. This replaces the old RS232, but has a slightly different spec I believe.
A disk drive was usually memory mapped, presumably it still is now, i.e. you don't drive a disk drive with IN/out instructions, they'd be too slow. But ports are slow anyway so it doesn't matter, e.g a printer is slow as far as data rate required compared to the terrific e.g. 200 Megabyte/second required of a hard disk. A speaker, it only needs the frequency of the sound times about 10 or 20, say 20kHz would be ample for a buzzer, hence it's I/O. Slow things use I/O, the IN/OUT instructions. Hence the USB is probably now memory mapped, you'll have to check up on it.
A better way to understand it is this. On old computers back in the 80's sometimes you wanted to control some device you had built, and had no spec for the output ports (as in those days manufacturer's kept this hidden so that certain companies e.g joystick and cartridge companies) could get ahead in the market by some business deal). What you had to do was open the computer and literally solder wires to some points on the address bus, e.g. you soldered three wires to some points in the circuit at a safe distance (so as not to damage the chip with the heat), those points wired by the circuit board layout to e.g. pins A15 A7 and A1 on the microprocessor. And you'd have to wire also usually a MREQ line (a memory request line and/or the RD/WR line to make a neater signal, and add that into the and or not logic, but if you were clever you could just do it with the address lines) And then you connected these three wires + this extra Ready type signal (e.g. MREQ RD or WR line to give some active low or high (which would need a possible extra NOT gate here) to say DATA is ready on the line NOW) through a 4 input AND gate, which gave an output to an led through a 200 ohm resistor, you have you're own memory mapped high speed I/O to a led light, which you could latch through an SR latch or D type latch to store it in a 1 bit memory externally on some circuit board. Here 15 is the 32K line, 7 is the 64 line, 1 is the 2 line (binary works in powers of 2, so A1 is 2^1, A7 is 2^7, and A15 is 2^15), So if you addressed location 32768+64+2=32834 = F041 in hex, using LDA or STA or LD on old MPU's in the assembler, you would output to this led, it would light up bright if the resistor was say about 100 ohms. So you have done memory mapped I/o, that as simple as it is, you could do it today by soldering to your mpu address lines the same. But you wouldn't do it now due to the delicacy of the circuits. But you could also join the data lines D0..7 (in the old days) or say d0..31 now for 32bit on an old 486 PC. Then if you addressed that location in machine code by doing a load the accumulator with value 8 (mov ax,8 nowadays) or store that  accumulator value into an address location (mov F041h,ax accumulator, you would EVEN today get that led to come on. Note, the 8, in the example is what is on the data bus, in this particular case, we are not passing data we are just enabling the particular device (LED is on, if we have selected THAT I/O device, here, just an LED), so in this example it doesn't matter what number we have with that MOV ax,8 instruction, it could be e.g. mov ax,243 and we'd still be enabling the LED on the F041h line when we then do mov F041h,as since we are using the same address. You see, there are address lines and there are data lines. So when you address 3F8 in COM1 or whatever the address is, the I/O memory map is simply sending a signal out to a port, e.g. ps/2, and an and gate is checking if you have 1110000100 on the lines i.e. 11 is 3 1000 is F and 0100 is 8, see binary to hex conversion. If high voltages appear in those bit positions where there is a 1, then the port, e.g. rs232 or ps/2, is set to active, i.e. it is enabled, this enables the latches, by the CE chip enable signal, or CS chip select simple.
On a latch it is the E Enable pin or OE active low output enable. I.e. with the example above described we use the addresses to select (by decoding) WHICH I/O device we want to use (i.e. in the example the LED comes on, if that I/O device is selected. So this is the enable line. THEN, once the I/O device is selected, THEN data is passed from the data bus (D0..7 in the old days, or example D0..63 now for a 64bit computer), via octal latches 373's in the old days, these are D-type flip flop circuits which store the data inside the flip flops. With an active high clock edge, the data passes through and is stored. This clock edge will come from the 'DATA RDY' signal on the data signal, this has various names, I don't know what the name is now. So for 64bit, we have 8 octal latches. And they use bi-directional latches to control data either way, or tri-state, so that when the I/O device is not used, the data lines are in the high impedance state. So therefore you select the I/O device with a combination on the address lines, this is the number, e.g. 3f8h in OUT 3F8h, 7, and the data, here in the example 7, is what is passed on the data lines, in the OUT command the data is passing OUT to the data latch, and out to the I/O device. If you had IN, you'd be doing a command e.g. IN 3f8h,800h, (I expect, but I don't know the syntax of x86 assembler), what I mean is, for IN, you are inputting the data from the data lines (after having selected the address, e.g. here 3f7h, which selects THAT I/O device), this data comes from the I/O device, through the D-type flip flops in the data latch (one for each bit of the data bus lines), and is input to the D0..7 or (D0..63 on modern pcs) pins on the MPU Micro-processing unit). In this example I put IN 3f8h, 800h, to show that once the data comes in it is then stored into address 800h. The syntax of x86 I think is different, you'd have to do probably IN 3f8h, ah or something similar, i.e. into a register first with the data coming in, then you'd MOV 800h, ah i.e. mov the data into the memory location in the RAM, (If you wanted to store it), or do something else with ah etc. ah is an example register, it could be any, al, bh, bl etc whatever, but check the syntax, every assembler system is slightly different, I am not an expert on x86. Again, I am using 3f8h as an example I/O address, there are hundreds, probably thousands of these addresses, e.g. 378h.. See the I/O memory maps for the IBM PC, for full lists.
Whereas when you access the memory(the RAM, e.g. 64byte static rams and dynamic RAMs in the 70's, 8K SRAMs and DRAMs in the 80's, rows of SIMMS each having a few megabytes each(single in line memory module) in the 90's and now is in the form of DDR modules containing  DIMMs, dual in line memory modules, I haven't checked but the latest probably no doubt each have a few gigabytes on each little chip), if it isn't an I/O address (very few addresses are I/O addresses, nowadays memory is millions of times or more likely to be in the address space than I/O on a modern pc), you still use the same read write data instructions to memory, but you aren't driving some external logic circuits that look for those bits, instead those address and data pins are wired directly to the RAM chips.
In machine code, I/O and memory addressing just appears the same, as though they are both memory accesses, but what physically goes on is totally different in the actual electronic circuit.


text:
Q: remove addEventListener for font-weight - Javascript I created javascript eventListener by using javascript for my dropdown link. When I click on 'bold', everything turn bold. It is ok for me but I want to remove it when clicking. When I click again, my removeListener does not work, it is missing something I guess.
Thank you in advance.
//HTML

                <button class="dropbtn"  id="dropbutton">Style menu</button>

                    Bold
                    Italic

                <button class="dropbtn"  id="dropbutton1">Thèmes site</button>

                    Fonce
                    Pale

// JAVASCRIPT

const bold = document.querySelector(".bold");
const italic = document.querySelector(".italic");
const fonce = document.querySelector(".fonce");

function Mystyle(){
   bold.style.fontWeight = "bold";
   italic.style.fontWeight = "bold";
   fonce.style.fontWeight = "bold";

};

bold.addEventListener("click", Mystyle);

// It does not work
function removeEvent() {
    bold.removeEventListener("click", Mystyle);
  }

A: Do not remove the event listener; instead, change the styles (or toggle a class) depending on the current state for each click.
function Mystyle(){
    if (bold.style.fontWeight === 'bold')
        bold.style.fontWeight = italic.style.fontWeight = fonce.style.fontWeight = "";
    else
        bold.style.fontWeight = italic.style.fontWeight = fonce.style.fontWeight = "bold";

};
bold.addEventListener("click", Mystyle);

It is more convenient to toggle a class instead:

function Mystyle() {
  document.querySelector('.navBar').classList.toggle('bold');
}
document.querySelector('.bold').addEventListener("click", Mystyle);
.navBar.bold .bold, .navBar.bold .italic, .navBar.bold .fonce {
/* or perhaps use .navBar.bold a */
  font-weight: bold;
}

    <button class="dropbtn" id="dropbutton">Style menu</button>

      Bold
      Italic

    <button class="dropbtn" id="dropbutton1">Thèmes site</button>

      Fonce
      Pale


text:
Q: Не обновляется panelgroup в jsf Пытаюсь обновить по кнопке компонент panelgroup, но ничего не происходит. Я уже пробовал многие способы и ничего не помогает. Подскажите, что ещё можно сделать, чтоб обновить panelgroup?
    <h:panelGroup layout="block" id="content">
            <h:panelGroup layout="block" id="nav">
                <h:form id="itemsMenu">
                    <h:commandLink value="View" update="workplace" actionListener="#{main.determineAction}">
                        <f:param name="link" value="Viewing telephone book"/>
                    </h:commandLink>
                </h:form>
            </h:panelGroup>
            <h:panelGroup id="workplace">
                <h:panelGroup layout="block" rendered="#{main.responseRendered}">
                    <ui:include src="#{main.linkPage}"/>
                </h:panelGroup>
            </h:panelGroup>
        </h:panelGroup>

Код бина
@ManagedBean(name = "main")
@ViewScoped
public class MainBean implements Serializable {

    private static final long serialVersionUID = 1L;
    private List<String>      listItemsMenu;
    private String            linkPage;
    private boolean           responseRendered = false;

    public boolean isResponseRendered() {
       return responseRendered;
    }

    public void setResponseRendered(final boolean responseRendered) {
       this.responseRendered = responseRendered;
    }

    public String getLinkPage() {
       return linkPage;
    }

    public void setLinkPage(final String linkPage) {
       this.linkPage = linkPage;
    }

    public void determineAction(final ActionEvent event) {
       final Locale currentLocale = SessionBean.getCurrentLocale();
       final MessageManager messageManager = new MessageManager(currentLocale);
       final Map<String, String> mapParameters = FacesContext.getCurrentInstance()
                .getExternalContext().getRequestParameterMap();
       final String linkType = mapParameters.get(Constants.ATTRIBUTE_LINK_TYPE);
       if (linkType.equals(messageManager.getProperty(
                           Constants.MESSAGE_MENU_VIEWING))) {
           linkPage = Constants.PAGE_VIEW;
       }
       ...
       responseRendered = true;
    }
}

A: Попробуйте так:
<h:commandLink render="workplace" ... >

Вообще html компоненты входящие в реализацию jsf (Mojarra, MyFaces) используют термины jsf ajax стандарта: render - обновить компоненты с указанными id, execute - отправить значение компонентов на сервер. Термины же updete & process используют переопределённые ajax реализации, например PrimeFaces.


text:
Q: Como mostrar tela de "carregando" com modal bootstrap em qualquer processo do servidor c# Necessito de que as minhas páginas mostrem a todo processo do servidor uma tela com um tipo de Carregando usando o modal bootstrap que criei abaixo. Meu problema é conseguir mostrar isso em todos os processos.

*

*Existe alguma forma de fazer isso?

*Alguém tem alguma ideia?

Meu código:

                                     Aguarde

A: Você pode fazer isso para todos os ajax da sua aplicação, utilizando os eventos  globais.
Exemplo:
$(document).ajaxSend(function () {
    ///chama seu processando
});

$(document).ajaxComplete(function () {
    //finaliza seu processando
});

Você também pode usar o .ajaxError() para criar um tratamento de erro global, conforme expliquei aqui.


text:
Q: How to display a list of items both ungrouped and grouped. (ListView vs ExpandableListView) I'm trying to display a list of items (songs) in various forms dynamical selected by the user.  I'm using an ExpandableListView to group by album, artist or year depending on the user's selection.  When the selection changes it automatically regroups the items.
What makes this more complicated is that the items are the result of a search which may still be in progress.  So there is a fairly strong coupling between the search thread class and the adaptor (BaseExpandableListAdapter) so that the search can dynamically pump data into the groups and generate new groups over a period of up to two minutes.  This all is working fine.
My question is how do I switch to showing all tracks ungrouped.  There doesn't seem to be an option to display child items without a group item.  At the moment I've got round this by creating a single group "All items".  This doesn't look good on the UI.  I've tried setting it to expanded and visibility GONE but that still leaves the group item in place, just blank. Are there any better solutions?

A: What about using both at the same time ListView and ExpandableListView, overlapping each other inside a relative layout ?
Then you may use something like this to switch from one to another
public void setListViewMode(boolean isExpandable){
    findViewById(R.id.my_expandable_listview).setVisibility(isExpandable ? View.VISIBLE : View.GONE);
    findViewById(R.id.my_normal_listview).setVisibility(!isExpandable ? View.VISIBLE : View.GONE);
}

or another way (maybe more easy):
Have you tried to hide your view group inside
public View getGroupView(){

    ...

    convertView.setVisibility(isExpandable ? View.VISIBLE : View.GONE);
    return convertView;
}

or maybe:
getExpandableListView().setGroupIndicator(null);


text:
Q: Table - 3 cells per row http://jsfiddle.net/tiitremmel/DpMB7/ - basic sample what I've done already

I'm trying to rearrange table cells so that the table will result always 3 cells per row. Table have always by default 1 cell per row.
Default table look:
1
2
3
4
5
6
7
And the result should look
1 2 3
4 5 6
7
jQuery should limit 3 cells per row.

A: You can use slice to split up your td's in the fashion you want and append them to your des table.
while($("#source td").length > 0){
    $("#des").append($("
").append($("#source td").slice(0, 3)));
}
$("#source").remove();

Given this source:

        1

        2

        3

        4

        5

        6

        7

You will end up with the following:

                1

                2

                3

                4

                5

                6

                7

Example on jsfiddle.

A: You can try something like this http://jsfiddle.net/DpMB7/10/
var table$ = $('
');
$('table.myTable td').each(function(index) {
    if (index % 3 === 0) {
        table$.append('
');
    }
    table$.find('tr:last').append(this);
});
$('body').append(table$);

It's not the best jQuery code in the world, but hey, I'm learning :)


text:
Q: Mongodb php compound query returns nothing I have the following array:
Array
(
    [data.cars] => 44
    [data.xp] => Array
        (
            [$gte] => 100
            [$lte] => 500
        )

    [data.money] => Array
        (
            [$gte] => 200
            [$lte] => 1000
        )

)

When issuing this array to find it returns NULL.
Am I doing something wrong, I formated it according to this page, here:
http://us1.php.net/manual/en/mongo.sqltomongo.php
So basically, if I have
SELECT * FROM mytable WHERE data.cars = 44 AND data.xp >= 100 AND data.xp <= 500 AND data.money >= 200 AND data.money <= 1000

This query when run in the console gives exactly 4 results.
Here is the query:
{$and:[{"data.cars":44}, {"data.xp": {$gt:100, $lt:500}}, {"data.money": {$gt:200, $lt:1000}}]}

My array should work, but hey, it does not, please point me to what I'm doing wrong.
Thank you!

A: The query on MongoDB PHP should be formatted like this:
array(
    'data.cars' => 44,
    'data.xp' => array(
        '$gt' => 100,
        '$lt' => 500
    ),
    'data.money' => array(
        '$gt' => 200,
        '$lt' => 1000
    )
)

A: By doing json_encode() on two version of arrays, both at first sight seem identical, but as you will see, they are not, I discovered the "bug".
Both array's look like so:
array(
    'data.cars' => 44,
    'data.xp' => array(
        '$gt' => 100,
        '$lt' => 500
    ),
    'data.money' => array(
        '$gt' => 200,
        '$lt' => 1000
    )
);

One was hardcoded the other was dynamically built, but both json encoded were different, here they are:
{"data.cars":"44","data.xp":{"$gte":"100","$lte":"500"},"data.money":{"$gte":"200","$lte":"1000"}}

{"data.cars":44,"data.xp":{"$gte":100,"$lte":500},"data.money":{"$gte":200,"$lte":1000}}

The first array had the values as string, but couldn't see that on a regular print_r or a var_dump, so what I did was a force cast on the values and ... it WORKED :)
Thank you all guys for your effort and interest!

A: First of all it is really bad to use . or $ symbols in a keys name (and I actually thought that this is illegal ). This is because dot operator is used to access subdocuments.
So the first thing is to change that. The second thing is that you do not need $and there. So if you want to find the document, which has a = 1 and b = 2, then you do not need to do {$and : .... } all you need to do is {a : 1, b : 2}


text:
Q: Mysql not using an index on where in with two columns I have the following query:
select * from my_table
where (col1, col2) in ( (1000,1), (2000,2) )

I have indexes defined on col1, col2 and col1 and col2 together. If I run an explain on it, I see that mysql does not find an available index to use. Interestingly enough if I put only one pair in the IN clause, the explain finds all the indexes.
Tried force index, does not help
Any ideas, how can I make mysql recognize the index?

A: You need MySql version 5.7.3 or above
Earlier versions do not implement an optimization for row constructor expressions
Please follow this link for details: https://dev.mysql.com/doc/refman/5.7/en/range-optimization.html#row-constructor-range-optimization

8.2.1.3.4 Range Optimization of Row Constructor Expressions
As of MySQL 5.7.3, the optimizer is able to apply the range scan access method to queries of this form:
SELECT ... FROM t1 WHERE ( col_1, col_2 ) IN (( 'a', 'b' ), ( 'c', 'd' ));
Previously, for range scans to be used it was necessary for the query to be written as:
SELECT ... FROM t1 WHERE ( col_1 = 'a' AND col_2 = 'b' )
OR ( col_1 = 'c' AND col_2 = 'd' );

Note: a row constructor is an expression of a form:( value1, value2, ... ,valueN) or ROW( val1, val2, ..., valN).

A: I managed to solve this without upgrading the mysql version, by adding an extra where in condition on one of the columns only:
select * from my_table
where (col1, col2) in ( (1000,1), (2000,2) )
and col1 in (1000,2000)

This way, the optimizer will find the index on col1, and will search by it, which did the job for me.

A: I wasn't not aware about this; so tried out first (Fiddle http://sqlfiddle.com/#!2/f88bb/2) and yes it's correct; for a multi column IN clause it's using full table scan instead of using the index available.
After some more search found that it's a BUG in MySQL which is targeted to be released or fixed in MySQL 6.x.
See here for a full info Multi column IN does not use index
So for now you can transform your query to use single IN clause so that it recognizes the index; like
select * from my_table
where col1 in ( 1000,2000) and col2 in (1,2)

Person who created the BUG/Optimization request has explained (OR) given reproduction steps here
Multi-Column IN clause – Unexpected MySQL Issue


text:
Q: ActionBarDrawerToggle issue on Android well guys, I'm development a private personal app for my job, but I'm having an unknown issue, I'm kind of lost with this, not understanding what is this happening, I'm trying to setup a simple ActionBarDrawerToggle, but it doesn't working, and It's even showing and unset Icon instead I setted, so please, can anybody help me? I couldn't go ahead if I don't resolve this first
public class MainActivity extends Activity {
    private String[] titulos;
    private DrawerLayout NavDrawerLayout;
    private ListView NavList;
    private ArrayList<Item_objct> NavItms;
    private TypedArray NavIcons;
    private ActionBarDrawerToggle mDrawerToggle;
    private CharSequence mDrawerTitle;
    private CharSequence mTitle;
    NavigationAdapter NavAdapter;

//Implementacion del ListView
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    //Drawer Layout
    NavDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    //Lista
    NavList = (ListView) findViewById(R.id.lista);
    //Declaramos el header el caul sera el layout de header.xml
    View header = getLayoutInflater().inflate(R.layout.header, null);
    //Establecemos header
    NavList.addHeaderView(header);
    //Tomamos listado  de imgs desde drawable
    NavIcons = getResources().obtainTypedArray(R.array.navigation_iconos);
    //Tomamos listado  de titulos desde el string-array de los recursos @string/nav_options
    titulos = getResources().getStringArray(R.array.nav_options);
    //Listado de titulos de barra de navegacion
    NavItms = new ArrayList<Item_objct>();
    //Agregamos objetos Item_objct al array
    //Pedidos
    NavItms.add(new Item_objct(titulos[0], NavIcons.getResourceId(0, -1)));
    //Gastos
    NavItms.add(new Item_objct(titulos[1], NavIcons.getResourceId(1, -1)));
    //Productos
    NavItms.add(new Item_objct(titulos[2], NavIcons.getResourceId(2, -1)));
    //Clientes
    NavItms.add(new Item_objct(titulos[3], NavIcons.getResourceId(3, -1)));
    //Ganancias
    NavItms.add(new Item_objct(titulos[4], NavIcons.getResourceId(4, -1)));
    //Capital
    NavItms.add(new Item_objct(titulos[5], NavIcons.getResourceId(5, -1)));
    //Declaramos y seteamos nuestrp adaptador al cual le pasamos el array con los titulos
    NavAdapter= new NavigationAdapter(this,NavItms);
    NavList.setAdapter(NavAdapter);
    //Siempre vamos a mostrar el mismo titulo
    mTitle = mDrawerTitle = getTitle();

    // Declaramos el mDrawerToggle y las imgs a utilizar
    mDrawerToggle = new ActionBarDrawerToggle(
            this,                   /*Host Activity*/
            NavDrawerLayout,        /*DrawerLayout Object*/
            R.drawable.ic_drawer,   /*Icono de navegacion*/
            R.string.app_name,      /* Nombre de aplicacion*/
            R.string.hello_world    /* "Close drawer" description*/
    ) {
        /**
         * Called when a drawer has settled in a completely closed state
         */
        public void onDrawerClosed(View view) {
            Log.e("Cerrado Completo", "!!");
        }

        /**
         * Called when a drawer has settled in a completely open state
         */
        public void onDrawerOpened(View drawerView) {
            Log.e("Apertura Completa", "!!");
        }
    };

    //Establecemos que mDrawerToggle declarado anteriormente sea el DrawerListener
    NavDrawerLayout.setDrawerListener(mDrawerToggle);
    //Establecemos que el ActionBar muestre el boton Home
    getActionBar().setDisplayHomeAsUpEnabled(true);

That is my Main Activity class, I just don't find the asnwer why this

A: I think you forgot to add some things:
1.-Override following Activity methods to sync DrawerToggle with the state:
@Override
protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    // Sync the toggle state after onRestoreInstanceState has occurred.
    mDrawerToggle.syncState();
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    mDrawerToggle.onConfigurationChanged(newConfig);
}

2.- Also, you need to tell the ActionBar than home icon must be enabled. So call the following in OnCreate for example:
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);

I hope this helps you.
If this does not help you, check:http://developer.android.com/training/implementing-navigation/nav-drawer.html Its a good guide
Good luck


text:
Q: Average without avg function I need to calculate average value from 6 columns but when there is an empty field I don't want to have it calculated.
For example, if I have (2, 3, 2, 3, 2, 3) I should get 15/6 = 2,5 but when it is (2, 3, 2, 3, 'empty', 'empty') I need to have 10/4 = 2,5.
How to achieve this?
This is average from 6 columns co I can't use avg function which ignores NULLs as default.

A: You can create a view or subquery which skips rows with "empty" values and take an average on the view or subquery.
SELECT AVG(value) FROM
    (SELECT value FROM table WHERE value <> the_value_that_janek_considers_as_empty)

But I would seriously advise you to reconsider your notion of "empty".  There is no such thing as an empty numeric value in databases.  Either you say "empty" when in fact you mean "null", or you are doing something horrible, like storing numbers in textual columns.

A: Catch your NULL values by using CASE statement. See Below:
SELECT
     AVG(ISNULL(Column_to_Average,0)[Column_to_Average])
FROM #yourtable

OR
SELECT
     AVG(CASE WHEN Column_to_Average IS NULL OR Column_to_Average=''
              THEN 0 ELSE Column_to_Average END)
FROM #yourtable

OR You can also do this if you want to get the average of each rows.
SELECT
     (
     (CASE WHEN Column_to_Average_1 IS NULL OR Column_to_Average_1='' THEN 0 ELSE Column_to_Average_1 END) +
     (CASE WHEN Column_to_Average_2 IS NULL OR Column_to_Average_2='' THEN 0 ELSE Column_to_Average_2 END) +
     (CASE WHEN Column_to_Average_3 IS NULL OR Column_to_Average_3='' THEN 0 ELSE Column_to_Average_3 END) +
     (CASE WHEN Column_to_Average_4 IS NULL OR Column_to_Average_4='' THEN 0 ELSE Column_to_Average_4 END) +
     (CASE WHEN Column_to_Average_5 IS NULL OR Column_to_Average_5='' THEN 0 ELSE Column_to_Average_5 END) +
     (CASE WHEN Column_to_Average_6 IS NULL OR Column_to_Average_6='' THEN 0 ELSE Column_to_Average_6 END)
     )/6 Column_to_Average
FROM #YourTable

A: Ignoring nulls is QUITE easy, sqlserver already ignores null values:
SELECT avg(x)
FROM (values(4),(6),(null)) x(x)

Result
5

Edit since your comment says your numeric column is a varchar - which is silly, do this instead to handle empty and null values:
SELECT
  avg(cast(nullif(x, '') as decimal(18,2)))
FROM (values('4'),('6'),(null), ('')) x(x)

A: select sun(x)  --sql server ignore null,
       count(x)  --sql server ignore null,
       sum(x)/count(x) as avgx
from tbl

A: You face two problems:

*

*You have to convert the strings to numbers, and avoid the null and empty strings.

*You need to calculate the average of columns, so the avg function isn't usable as long as the data is in that form.
Basically there are two possible approaches, either you can just use the column values, or you can turn the columns into rows.
Using the column values naturally becomes repetetive. You have to both convert each column, and check how many usable columns there are:
select
  (
    case when Col1 is null or Col1 = '' then 0.0 else cast(Col1 as float) end +
    case when Col2 is null or Col2 = '' then 0.0 else cast(Col2 as float) end +
    case when Col3 is null or Col3 = '' then 0.0 else cast(Col3 as float) end +
    case when Col4 is null or Col4 = '' then 0.0 else cast(Col4 as float) end +
    case when Col5 is null or Col5 = '' then 0.0 else cast(Col5 as float) end +
    case when Col6 is null or Col6 = '' then 0.0 else cast(Col6 as float) end
  ) / (
    case when Col1 is null or Col1 = '' then 0.0 else 1.0 end +
    case when Col2 is null or Col2 = '' then 0.0 else 1.0 end +
    case when Col3 is null or Col3 = '' then 0.0 else 1.0 end +
    case when Col4 is null or Col4 = '' then 0.0 else 1.0 end +
    case when Col5 is null or Col5 = '' then 0.0 else 1.0 end +
    case when Col6 is null or Col6 = '' then 0.0 else 1.0 end
  ) as Average
from
  TheTable

You could create user defined function to do the conversion and counting, but you still need to do it for each column.
(A word of caution also; if there isn't a value in any of the columns, this would give you a division by zero error.)
You can use unpivot to turn the columns into rows, but you need a unique value to group the result on to keep the rows together that belong together. Example:
select
  Id, avg(cast(Col as float))
from
  TheTable
unpivot
  (Col for ColName in (Col1, Col2, Col3, Col4, Col5, Col6)) x
where
  Col <> '' and Col is not null
group by
  Id


text:
Q: Can i find frequency of visit of stores using the information provided? I have a warehouse, which serves 100 stores.
Each store has to be visited N times a month to fulfill its demand.
i'e every day a Van V starts from the warehouse W , and cover n stores in a day(8 hours) and come back to warehouse
I want to find the no. N , i'e how many times a store should be visited in a given month to fulfill its demand.
I am gathering what information is needed for every store to calculate its frequency.
I could come up with the following:

*

*Sale value of each store(monthly). i.e in this month a store will sell k items which will gain them the sale value s

*Total weight of the k items.

*Weight of the Truck
Can this problem be solved by using knapsack algorithm?
If yes, apart from the 3 points, is any other information required at store level?
I have each store to store distance, also warehouse to store distance matrix available.
Below shown is just the snapshot of the data i thought was required, and created a random dataset.
Customer_code = store_code.

PS . I am developing in python.
Code to create random dataset:
import pandas as pd
import random
from numpy.random import uniform
my_randoms = random.sample(range(1000), 100)
weights = random.sample(range(100), 100)

df = pd.DataFrame({'customer_code':list(range(1,101)),
               'latitude':uniform(24.74272,28.1234,100),
                'longitude':uniform(46.1234,50.123445,100),
               'sale_value':my_randoms,
               'weights':weights})


text:
Q: Stopping certain data from ever leaving your Mac? Is there any way to stop certain data (e.g., a particular string) in unencrypted, clear, plain text from ever leaving my Mac by any network protocol (including my home network) but not affecting regular backups to other drives?
I seem to remember Intego's NetBarrier had this facility, years ago at least, though I'm not sure if any of their products still do this, but I wondered if there was an alternative, simpler way of doing this?

A: Practically, no
Practically speaking, it is not possible to ensure a particular string never leaves your computer via a network connection.
You can however monitor and manage who your Mac communicates with, see Is there a good tool for monitoring network activity on Mac OS X?
Why?
Applications and processes running on your computer could encode or encrypt the string in a manner that can not be easily detected, and that encoded form could then be sent over the network.
Network traffic is encrypted
On a recent installation of macOS, there are vanishingly small amounts of plain network data for you to filter and monitor.
Modern network protocols encrypt the data being sent. Protocols that send data in a plain unprotected form are being actively removed or relegated to exceptions rather than common use.
Even the widely deployed Hyper Text Transfer Protocol (HTTP) is rapidly being superseded by the encrypted replacement HTTPS, as browser makers raise awarness with their users.
Theoretically, yes
In theory, it feels possible. A solution would have to inspect every network connection and be able to decrypt every encrypted connection. This might even be attempted in some secrecy focused organisations.
For a home or professional user, such a task unlikely to be achievable while retaining a functioning useful computer.
Man-in-the-Middle Attack
I am assuming you do not want to Man-in-the-Middle (MITM) attack your own computer's traffic; this itself is complex, error prone, and defeats the benefits of encryption.
I am also aware of an increasing number of services that pin their TLS certificates to thwart such attacks.

A: Snort and a transparent proxy could do exactly what you ask for,
it's how I implement sensitive information control of certain department or network.
You can log / reject possibly "bad" connection base on file fingerprint. It's not hard to set up.
Both the encrypted and plain text can be inspected and reacted upon.


text:
Q: Image caching and loading in Linear layout I am searching for fast solution how to cash images.
I found many done this in loading in ListView images.
However i need to load images into ImageButton which is subview of Linear layout.
Maybe someone saw this implemented or could give me some tips how to do this ?
Thanks.

A: You can use your applications cache directory to cache your images. Use Context's getCacheDir() api to get your cache directory path.


text:
Q: Laravel groupBy with pagination I'm trying to use the queryBuilder to get all the results from one table, paginated by 15 grouped by one field.
$data['invoices'] = InvoiceModel::selectRaw("*")
    ->groupBy('serie')
    ->paginate(15);

Laravel throws the following error:
SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'projetoservidor.vendas_195295269.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by (SQL: select count(*) as aggregate from (select * from vendas_195295269 group by serie) as aggregate_table)
What should I do?

A: Laravel does not support groupBy with pagination

Read more at Laravel docs:

*

*https://laravel.com/docs/7.x/pagination#paginating-query-builder-results

*https://laravel.com/docs/7.x/pagination#manually-creating-a-paginator
Update
The above warning has been removed from Laravel 8.x docs. And @ronline confirms in the comment that pagination operations that use a groupBy have been sorted out since then.

A: Unfortunately, Laravel doesn't support pagination for Eloquent's groupBy as it's complicated case.
But here is a tip, In case of you use groupBy of the collection after fetching the data and you want to keep the pagination object to look the same.
// Get the activities
$activities = $user->activities()->paginate(6);

// This will replace data property of the pagination
$activities->setCollection($activities->groupBy('type'));

Now the $activities will look like same as before you group it
{
   "current_page": 1,
   "data": {
       "type_1": [
           ...
       ],
       "type_2": [
           ...
       ]
   },
   "first_page_url": "http://URL?
   page=1",
   "from": 1,
   "last_page":
   ...
}

A: Taken from the Laravel documentation here:

Currently, pagination operations that use a groupBy statement cannot be executed efficiently by Laravel. If you need to use a groupBy with a paginated result set, it is recommended that you query the database and create a paginator manually.

A: I am using Laravel Query Builder for : cross join, group by, pagination and it works. Here is working code.
Thread::join('participants as p', 'p.id', 'threads.id' )
   ->join('messages as m', 'm.thread_id', 'threads.id' )
   ->join('users as u', 'm.user_id', 'u.id' )
   ->select
   (
       array(
           'u.email as creator',
           'p.*',
           'threads.*',
           'threads.id as id'
          )
   )
   ->latest('threads.updated_at')
   ->groupBy('threads.id')
   ->paginate($numberOfPages)

A: Use This with any Laravel version. Its working for me
$draws = Draw::with('location')->select('location_id', 'draw_number', 'created_at')
        ->paginate(30);

$draws->setCollection($draws->groupBy(function ($date) {
    return Carbon::parse($date->created_at)->format('Y-m-d');
}));

A: Eloquent Relationship

Assuming Invoice n..1 Serie

If serie is an Eloquent Relationship you can group by paginate using the relationship model as the pagination target.
Serie::with([
    'invoices',
])
    ->paginate();

This can also give you the possibility to filter by serie or invoice
If filtering by invoice for example
Serie::whereIn('id', Invoice::where($condition)->select(['serie_id']))
    ->with([
        'invoices' => function ($query) use ($condition) {
            $query->where($condition);
        },
    ])
    ->paginate();

Field
If serie is a field, it is a bit more complicated to paginate, but you can still do it if the select clause only contains aggregated columns. And it's preferable to add an order by clause.
use Illuminate\Support\Facades\DB;

// -----

Invoice::select([
    'serie',
    DB::raw('min(column1)'),
    DB::raw('max(column2)'),
    DB::raw('avg(column3)'),
    // ...
])
    ->orderBy(DB::raw('min(column1)'), 'asc') // or desc
    ->paginate();


text:
Q: How to select checkbox manually in wpf when toggle button exist? When I clicked toggle button it selects each and every checkbox. When
I click the toggle button again, it will uncheck every checkbox.
If I clicked individual checkbox, it selects all checkbox.
Is it possible to select manually individual checkbox without clicking toggle button?
<CheckBox Uid="checkbox1" Name="checkbox1" Checked="CheckBox_Checked" Unchecked="CheckBox_UnChecked" IsChecked="{Binding ElementName=button,Path=IsChecked}">
    <Image Source="{Binding Path=UriSource}" Stretch="Fill" Width="100" Height="120" />
</CheckBox>
<ToggleButton x:Name="button" Content="Select/Unselect" Click="ToggleButton_Click" HorizontalAlignment="Left" Margin="54,545,0,0" VerticalAlignment="Top" Width="115" Height="57" RenderTransformOrigin="0.986,1.365" />

A: You can achieve it with the help of following code
<StackPanel Orientation="Horizontal">
        <CheckBox Name="checkbox1"
                  Content="Checkbox 1"
                  Margin="5"
                  IsChecked="{Binding ElementName=button,Path=IsChecked,Mode=OneWay}"></CheckBox>
        <CheckBox Name="checkbox2"
                  Content="Checkbox 2"
                  Margin="5"
                  IsChecked="{Binding ElementName=button,Path=IsChecked,Mode=OneWay}"></CheckBox>
        <ToggleButton x:Name="button"
                      Content="Select/Unselect"
                      Width="Auto"
                      Height="25"
                      Margin="5"
                      VerticalAlignment="Top" />
    </StackPanel>

You need to set binding mode of check boxes to OneWay as shown in above code


text:
Q: Arrays in JavaScript - sorting text and numbers in Arrays I want to populate 2 arrays that I have which are called 'regions' and 'asbos'. I want to do this using a list of the following data of ASBOs record in each Criminal Justice System area:
Avon and Somerset    559,
Bedfordshire         220,
Cambridgeshire       285,
Cheshire             387,
Cleveland            489,
Cumbria              275,
Derbyshire           319,
Devon and Cornwall   473,
Dorset               197,
Essex                361,

I also wanted to create a loop for each region, giving it a particular font size that depends on the number of ASBOs and then store that formatted text in the 'tempText variable' as follows:
tempText += "" + regions[i] + " ";

This is what I have so far in my HTML file:
<!DOCTYPE html>

      <title>Javascript_Arrays</title>

A:

var $body         = $('body'),
    regions_asbos = $('#inputs').text().split(/,\s*/gm), // <== 1
    asbos         = {};                                  // <== 2

regions_asbos.forEach(function(line){                    // <== 3
  asbos[ line.replace(/(\d+)/,'').trim() ] = RegExp.$1;  // <== 4
});

var regions = Object.keys(asbos);                        // <== 5
regions.forEach(function(region){                        // <== 6
  if (!region)                                           // <== 7
    return;

  var $span = $('',{                        // <== 8
    'style': 'font-size: ' + asbos[region]/14 + 'px',
    'text':  region
  });

  $body.append($span);                                   // <== 9
});

Inputs

Avon and Somerset    559,
Bedfordshire         220,
Cambridgeshire       285,
Cheshire             387,
Cleveland            489,
Cumbria              275,
Derbyshire           319,
Devon and Cornwall   473,
Dorset               197,
Essex                361,

*

*Get the text of your input (I put it in a pre) and split them up into an array, treating a comma and any whitespace (newline,etc) as a delimiter; this creates an array for each line or region/asbos association

*Create a placeholder object; instead of having two separate arrays, all you need is one object that acts as a dictionary/hash

*Iterate over each line

*Use regex to capture the numbers (held in RegExp.$1) of the line (assuming your regions don't have numbers in their name) and replace those numbers with a blank string; this leaves the line with only the region name and a bunch of white text.  You can then trim off the whitespace and use the region name as the key of your dictionary/hash/object and assign it that number value you captured earlier.

*You can use the Object.keys() class function to get all the user-defined properties of your object and store it in an array (this is your regions).

*You can then iterate over your array of regions

*If the line didn't have a region (it's null, undefined, etc.; often related to having a trailing comma)

*Create the span (or whatever element) that you will post on the page; notice the use of asbos[region], where region is a variable (one of the regions of your input)

*Put that value some place on the page; in this case, at the end of the body

A: First split the given text with , (comma & space together)
Then use the following regex to separate each member of this splitted array into two arrays; /([\w\s]+\w)\s+([\d]+)/ first capture will be for region, and second capture for the ASBO array.
I hope this will be helpful.
var str = "Avon and Somerset 559, Bedfordshire 220"
var splitArr = str.split(", ");
for (var i = 0; i < splitArr.length; i++) {
   var matched = splitArr[i].match(/([\w\s]+\w)\s+([\d]+)/);
   region.push(matched[1]);
   asbo.push(matched[2]);
}

will result in;
region = {"Avon and Somerset", "Bedfordshire"}
asbo = {"559", "220"}


text:
Q: Xcode 6.1 - ObjC/Swift Codebase, Bridging Header and Code Completion so I'm attempting to add some Swift classes to my existing ObjC codebase. However, now I'm running into a weird issue:
I created my ProjectName-Bridging-Header.h and have been importing my ObjC header files as I need them in my new .swift files. I have a nested .xcodeproj inside my project and upon attempting to expose a class from that nested project to Swift via my bridging header, Xcode stops auto-completion.
Funny thing is, I can still run the app without problems:
let myObj = Object()
println(myObj) //returns <Object: 0x7abde160>

when typing myObj Xcode auto-complete shows me <<error type>>. I have tried the common suggestions, removing ModuleCache folder and all.. Nothing helped.
Anybody experience the same issue ?


text:
Q: Deleting all selected rows using easyui and php I have created the following function to get all my selection and send the selected ids to another php file (process.php) for processing.
Here is my function:
function getSelections(){
            var ss = [];
            var rows = $('#dga').datagrid('getSelections');
            if (rows){
            $.messager.confirm('Confirm','Are you sure you want to delete this user?',function(r){
                    if (r){
                        for(var i=0; i<rows.length; i++){
                            var row = rows[i];
                            ss.push(row.id);
                            }
                        /*$.messager.alert('Info', ss.join('
')); for testing*/
                    $.post('process.php', ss.join({id:row.id}),function(result){
                    if (result.success){
                        $('#dga').datagrid('reload');   // reload the user data
                    } else {
                        $.messager.show({   // show error message
                            title: 'Error',
                            msg: result.msg
                        });
                    }
                },'json');
            }
        });
    }
}

I want to get the data by this medthod in process.php:
$id = intval($_REQUEST['id']);
include 'conn.php';
$N = count($id);
for($i=0; $i < $N; $i++){
$sql = "delete from user where id=$id[$i]";
$result = @mysql_query($sql);
    if ($result){
        echo json_encode(array('success'=>true));
        } else {
        echo json_encode(array('msg'=>'There is error.'));
        }
}

I could not delete multiple rows. I could only delete single user at a time. Please help me.
What I want to achieve:
I want to delete all my selections (all users selected using checkbox) in one go and reload the grid? The answer below works with single record but not works with multiple records. Any help and suggestion are greatly appreciated. It is a part of my project.

A: Try
function getSelections() {
    var rows = $('#dga').datagrid('getSelections');
    if (rows) {
        $.messager.confirm('Confirm', 'Are you sure you want to delete this user?', function (r) {
            if (r) {
                var ss = $.map(rows, function (item, idx) {
                    return item.id;
                });
                /*$.messager.alert('Info', ss.join('
')); for testing*/
                $.post('process.php', {
                    'id[]': ss
                }, function (result) {
                    aler(result.success)
                    if (result.success) {
                        $('#dga').datagrid('reload'); // reload the user data
                    } else {
                        $.messager.show({ // show error message
                            title: 'Error',
                            msg: result.msg
                        });
                    }
                }, 'json').fail(function (jxhr, status, error) {
                    alert('error: ' + status + ':' + error)
                });
            }
        });
    }
}

then
$id = $_POST['id'];
include 'conn.php';
$N = count($id);
for($i=0; $i < $N; $i++){
$sql = "delete from user where id=$id[$i]";
$result = @mysql_query($sql);
    if ($result){
        echo json_encode(array('success'=>true));
        } else {
        echo json_encode(array('msg'=>'There is error.'));
        }
}

A: You could delete multiple rows using a statement like
DELETE FROM user WHERE id IN (1,2,3,4)

Click here for full explanation. Let me know if this helps!


text:
Q: Getting the resource path of the java project from a custom gradle plugin Trying to create a custom gradle plugin in java, how do i get the resources path from inside the task class?
public class MyCustomPlugin implements Plugin<Project> {

  @Override
  public void apply(Project project) {
    project.getTasks().register("doStuff", CustomTask.class);
  }
}

public class CustomTask extends DefaultTask {

  // How do I get java project resources dir from here?
  @Inject
  public CustomTask(ProjectLayout projectLayout) {
    directoryProperty = projectLayout.getBuildDirectory();
  }

  @TaskAction
  public void execute() {
    ...
  }

}

A: I would recommend to not get the directory inside the task, because the plugin that provides it might not be applied. Instead I would do it from within your plugin that registers the task, this way you can also ensure that the necessary plugin is actually applied. Gradle will display an error if the task is used without a value being assigned to the input that explains that nothing was assigned.
With the kotlin-dsl:
@CacheableTask
abstract class CustomTask : DefaultTask() {
    @get:InputFiles
    abstract val resources: FileCollection
    //...
}

I cannot answer if @InputFiles is the right annotation for your use case, because I don't know what you want to do with the resource. Refer to the Gradle documentation for more information on the available annotations, and what they do.
plugins {
    java
}

tasks.register<CustomTask>("customTask") {
    resources.set(sourceSets.main.map { it.resources })
}

Notice the map {} which ensures that our task has a dependency on the processResources task, this is done automatically for us because we stick to the provider API of Gradle for everything.
Note that the resources are by default in one directory, but they don't have to be. This is why the resources are defined as SourceDirectorySet and not as Provider<Directory>. The same is true for anything that originates from the SourceSetContainer. It is easier to explain with Java source code: imagine you have Java and Kotlin, then you will have src/main/java and src/main/kotlin, hence, 2 directories. The former will have a **/*.java include filter, whereas the latter has a **/*.kt includes filter. If we just want to get all sources then we use sourceSets.main.map { it.java.sourceDirectories }, and if we want to get one of both it gets complicated.

A: First, you'd have to ensure this is a Java project: either applying the "java" plugin from your plugin (project.getPluginManager().apply("java")), or only registering the task when the "java" plugin has been applied by the user (project.getPluginManager().withPlugin("java", ignored -> { project.getTasks().register(…); });).
You could then get the resources from the main source set:
SourceSetContainer sourceSets = project.getExtensions().getByType(SourceSetContainer.class);
// Use named() instead of get() if you prefer/need to use providers
SourceSet mainSourceSet = sourceSets.get(SourceSet.MAIN_SOURCE_SET_NAME);
SourceDirectorySet resources = mainSourceSet.getResources();

BTW, the best practice is to have tasks only declare their inputs and outputs (e.g. I need a set of directories, or files, as inputs, and my outputs will be one single file, or in one single directory) and have the actual wiring with default values be done by the plugin.
You could have the plugin unconditionally register the task, then conditionally when the "java" plugin is applied configure its inputs to the project resources; or conditionally register the task or unconditionally apply the "java" plugin, as I showed above.

A: You can access the sources through the project.sourceSets.
@Inject
  public CustomTask(Project project) {
    directoryProperty = project.projectLayout.getBuildDirectory();
    sourceSet = project.sourceSets.main
  }

See also the reference documentation here: https://docs.gradle.org/current/userguide/java_plugin.html#sec:java_project_layout