Q: Best way to create a unique number for each many to many relationship I have a table of Students and a table of Courses that are connected through an intermediate table to create a many-to-many relationship (ie. a student can enroll in multiple courses and a course can have multiple students). The problem is that the client wants a unique student ID per course. For example:
rowid Course Student      ID (calculated)
1     A      Ben          1
2     A      Alex         2
3     A      Luis         3
4     B      Alex         1
5     B      Gail         2
6     B      Steve        3

The ID's should be numbered from 1 and a student can have a different ID for different course (Alex for example has ID=2 for course A, but ID=1 for Course B). Once an ID is assigned it is fixed and cannot change. I implemented a solution by ordering on the rowid of the through table "SELECT Student from table WHERE Course=A ORDER BY rowid" and then returning a number based on the order of the results.
The problem with this solution, is that if a student leaves a course (is deleted from the table), the numbers of the other students will change. Can someone recommend a better way? If it matters, I'm using PostgreSQL and Django. Here's what I've thought of:

*

*Creating a column for the ID instead of calculating it. When a new relationship is created assigning an ID based on the max(id)+1 of the students in the course

*Adding a column "disabled" and setting it True when a student leaves the course. This would involve changing all my code to make sure that only active students are used

I think the first solution is better, but is there a more "database centric way" where the database can calculate this for me automatically?

A: If you want to have stable ID's, you certanly need to store them in the table.
You'll need to assign a new sequential ID for every student that joins a course and just delete it if the student leaves, without touching others.
If you have concurrent access to your tables, don't use MAX(id), as two queries can select same MAX(id) before inserting it into the table.
Instead, create a separate table to be used as a sequence, lock each course's row with SELECT FOR UPDATE, then insert the new student's ID and update the row with a new ID in a single transaction, like this:

Courses:

Name     NextID
-------  ---------
Math     101
Physics  201

Attendants:

Student Course   Id
------- ------   ----
Smith   Math     99
Jones   Math     100
Smith   Physics  200

BEGIN TRANSACTION;

SELECT NextID
INTO   @NewID
FROM   Courses
WHERE  Name = 'Math'
FOR UPDATE;

INSERT
INTO Attendants (Student, Course, Id)
VALUES ('Doe', 'Math', @NewID);

UPDATE
  Courses
SET NextID = @NewID + 1
WHERE Course = 'Math';

COMMIT;

A: Your first suggestions seems good: have a last_id field in the course table that you increase by 1 any time you enroll a student in that course.

A:
Creating a column for the ID instead
  of calculating it. When a new
  relationship is created assigning an
  ID based on the max(id)+1 of the
  students in the course

That how I'd do it. There is no point of calculating it. And the id's shouldn't change just because someone dropped out.

Adding a column "disabled" and setting
  it True when a student leaves the
  course.

Yes, that would be a good idea. Another one is creating another table of same structure, where you'll store dropped students. Then of course you'll have to select max(id) from union of these two tables.

A: I think there are two concepts that you need to help you out here.

*

*Sequences where the database gets the next value for an ID for you automatically

*Composite keys where more than one column can be combined to make the primary key of a table.

From a quick google it looks like Django can handle sequences but not composite keys, so you will need to emulate that somehow. However you could equally have two foreign keys and a sequence for the course/student relationship
As for how to handle deletions, it depends on what you need from your app, you may find that a status field would help you as you may want to differentiate between students who left and those that were kicked out, or get statistics on how many students leave different courses.


Q: Why is an Ethernet cable not grounded? There is no dedicated GND in the classical Ethernet 8P8C ("RJ45") pinout.[1]
Why does the Ethernet spec not include a ground, unlike many other cable types used for interconnecting devices that may both have its independent power source as well, e.g. RS-232 or USB?

A: To the mix of questions and comments of USB and Ethernet, such as why is Ethernet galvanically isolated, and USB is not:
Read up on USB history, and its mandates.  It was to be a "low cost", "short distance" (5 meters) signaling port fit for computers at home and business, and low cost above all other needs.  USB also had the mandate to improve data rate performance over parallel-printer and RS232 ports.
USB was to be put on all PC's manufactured.  Whether the user needed it or not.  That means it must be low cost.  Parallel-printer ports and RS232 ports and the large associated connectors, had a serious cost penalty on all popular computers.  And that made PC's and laptops, costlier, bigger, heavier and more power consumptive.  USB, thus to be very "low cost", has no transformers to accomplish galvanic isolation.  And it makes it easy to provide DC power to the peripheral.  USB data signaling, for lack of a better phrase is "semi-differential".  That is the current in the + and - lines of the cable, are about 95% numerically opposite matched (the + and -, are always slightly in error, of not being a perfect opposite current value), as a different transistor set drives each net, + and -.
Ethernet's mandate was and is; "reliable", "medium distance" communication, and low cost.  But reliable and medium distance come first.  Medium distance of 100 meters needs galvanic isolation very much.  If two devices (such as a switch and a PC) were connected across two buildings with a few volts of ground potential difference, that's a rather bad thing, and unintended, unwanted, ground current will flow in that data cable.  And that unwanted ground flow, can have all sorts of bad effects of harming the data quality and harming the equipment's, to possibly even endangering people.
Ethernet, also has different transistor sets driving each + and -, however the signal transformer shorts the + and - together, and thus the final + and - current flow is nearly a perfect, opposite match, down to nearly a single electron.  Thus true differential signaling is achieved.  True differential signaling allows the signal voltage levels to be further reduced, and the cable distances traveled, to be increased, and for unwanted EMI to be reduced.
Later came PoE for Ethernet.  PoE's mandate was to bring "low cost" DC power to peripheral devices, ie, VoIP phones, Cameras, & Door-Access units.  The PoE typically power exits the common Ethernet switch, to multiple devices, up to 100 meters in opposite directions.  That PoE (48 to 57) VDC is a "star" connection to all the devices. That means the multiple power using devices "PD", share a common supply (this is NOT isolated power, per RJ45 connector at the PSE).  Therefore it is a GUILT-Edged "shall" that the PD's shall maintain power isolation (as per the IEEE 802.3 standard), even on the PoE power inputs, by way of either an DC-to-DC isolated converter supply in the PD, or the PD is entirely in a non-conductive case, and never are its circuits ground plane connected to the local ground of the building or other nearby equipments (such as really low end cheap peripherals).  Unfortunately, IEEE 802.3 at PoE standard does not spell this out very clearly.
Summary:  Ethernet has transformers at both ends.  If even a transformer failure happened, galvanic isolation from PD remote device, to the PSE in the Ethernet switch is not lost.
PoE, gives up DC power isolation, (for the sake of low cost) at the Ethernet switch, and leaves this isolation "shall" up to the PD peripheral manufacturer.  Nobody is really checking on these manufactured items.
If IEEE put a reward bounty on the violators, that would improve the situation.
The new PoE standard, IEEE is pondering for even higher voltages and currents, for more PoE power, should move toward some improved quality and safety. These should be on only commercial/industrial grade or better installations:
1) full power isolation at the PSE, for each connector.
2) required test reports for PSE & PD power isolation, that are filed, and downloadable for the public.  To include the wiring diagram of the PI.
3) at the manufacturers cost, maintain a server, with a list of all PD's that meet the new standard.
4) consider making an industrial grade standard, if the cost of these improvements are too much for the low end consumer markets, yet still provide the serious level of standards, safety and traceability of industrial needs.

A: If you just ignore the POE 48 Volts in the image below, you can see Ethernet uses transformers on both sides.
This way there is no need for common ground as long as the common mode voltage stays below 1500V generally. The isolation specification of the transformers.

And as a bonus you now also know how POE works. (802.3at)
However, CAT6A often has a shielded connector. The shield is then grounded to chassis using the little flaps inside the socket.
Source image

A: The answer thus far have missed one key element: shielding couples noise.
The Ethernet standard has included both UTP and STP (unshielded/shielded twisted pair) for decades.
IBM heavily influenced the original inclusion of STP, for its compatibility with Token Ring. The claim was that the STP shielding provides an extra layer of noise protection for the differential pairs (a bargain at only 5x the price!)   However real-life experience quickly demonstrated that the shielding provided worse performance.  Point sources of electrical noise were coupled to the shielding, where the noise then had the entire length of the cable to be coupled to the twisted pairs.
Shielding can also increase cross-talk.  Pairs are twisted at slightly different rates -- a typical schedule is 11/12/13/14 twists per foot.  This way they don't physically nest together to form a parasitic transformer when the cable is twisted and pulled during installation. This works great. Way better than you might expect.  But the wiggling will stretch the shield between the pairs, coupling the signal to the shield and to the other pairs.

A: Why is Ethernet not grounded? There are two reasons:

*

*It would create a ground loop between devices

*The device would also be more susceptible to ESD which is prevalent in cables that are being moved or handled (from triboelectric charging of the cable)

The reason Ethernet is more susceptible to a ground loop is because:

*

*The loops could be much larger than other cable specs, with 100m between devices. USB is 5m, RS232 us 15m. Ethernet devices are more likely to be in different rooms, whereas USB devices are usually grounded to a computer (or hub) and are on the same ground or in the same room on the same mains circuit.

*The voltage of ethernet is lower ±1V with ~10mA of current. RS232 is much higher at 5V or 15V. USB is 3.3V. This makes it more susceptible to error.

The companies and engineers that designed the ethernet spec had this in mind (there is a lot of thought that goes into specs)
If you had a ground in between the transmitter and receiver it would create a ground loop. This ground loop would be formed by the cable and the return path would be mains ground as shown below. Any magnetic fields that flow through the loop would create a current along the cable (and the rest of the loop). Even if you isolated the signal wires this would be a problem because of mutual inductance between wires (wires run along side each other can couple currents from one to the other). This would inject noise (and cause potential bit error and packet loss).

So If you add an isolation transformer between devices, you break the loop and are still able to transmit a high speed signal between the transmitter and receiver. Another benefit of galvanic isolation, also increases the impedance of the cable to the device in the event of a large electrostatic discharge.
This is an example of isolation between two devices, ethernet has two isolation transformers, but the result is the same, it breaks the ground loop (and reduces common mode noise in conjunction with the twisted pair and common mode choke).

Images from wikipedia on ground loops

A: *

*Differential signaling means that there is no need for a common ground as a reference point. Also, negates the need for shielding, which is usually grounded.

*No DC power transfer again removes the need for a common ground and makes point #3 possible.

*Galvanic separation makes grounding counterproductive. Specs put considerable effort into making devices at different potentials able to work together so adding a ground wire would pretty much void this effort.

/edit: as Tom Carpenter pointed out, properly implemented POE, with isolated DC-DC converters, still retains the galvanic isolation and "no wire at ground potential" property. (Ok, POE breaks the galvanic separation part and adds kind of grounding, not clearly visible, yet it's there. But POE is a hack on top of the Ethernet, not an original part of the specs. Non-POE devices retain the original advantages.)
USB has differential signalling as well, but it also carries DC power. Mere existence of the powering possibility makes the common ground necessary.
RS-232 doesn't carry power, but the signal is not self-contained differential pair, it's a single wire referenced against the ground - that makes the common ground necessary.

A: The Ethernet specification calls for devices to be galvanically isolated from each other - this post explains the isolation implications in more detail.
Since you mentioned power sources and grounding, the Wikipedia article on Power over Ethernet (PoE) may be relevant to you.

A: One reason WHY TP ethernet, thank $DEITY!, is not using a common ground reference between stations has not been mentioned clearly enough:
An ethernet cable can run in excess of a hundred meters, probably even connecting two buildings.
The potential difference on even a well-executed grounding system, if measured at two points tens or hundreds of meters apart, is far from guaranteed to be even close to 0V - there can be DC or low frequency AC voltage due to current flow (due to leakage currents, actual fault currents, transients, or wiring mistakes/defects...) in the grounding system, and all kinds of interference.
AC potential differences will readily cause interference, while strong current flow across a grounded cable shield could actually turn into a fire hazard.
And all this assumes equipment being properly grounded in the first place, even worse things can happen if that is no longer the case.
Not worst, but bad case example what could happen with grounded (on both sides) shields : One PC has accidentally been connected with a two wire IEC cable (as has been found in the wild before!) on an RCD-less (old TN-C-to-the-socket ...) wiring system. This PC develops an internal short connecting live mains to the metal case, to which all the ground connections in that PC are connected. The other end of that connection is to a device where the grounding has been correctly implemented. The ethernet cable used is of the lightest build possible, with thin shielding material. And it is a 30 meter piece wound up in a coil since you were out of 5m cables. At that length, this shielding could have just the right resistance (around 15 ohms would be "perfect" on a 240V system) to pass a current that is small enough not to blow any fuses or automats, but well large enough to dissipate in excess of 1000 watts on the cable shield. Which will mean a lot of smoke and not unlikely an ignition hazard to stuff around it.

A: Grounding is often misunderstood to be the end-all solution for connecting things together. However, in most cases, even on short runs, grounding adds more issues than it solves.
The issue with sharing a ground over any distance is you are assuming both ends are at the same ground potential. In a perfect world that may be true, but in real life it almost never is.
Whether it be due to bad wiring, ground leakage, or EMI effects the ground over here on this monitor is different from the ground over there on your TV. As such, when you run a cable that includes ground between them, there will be a current running through that ground.
Moreover the common ground becomes the current return path for your signal. That means you are actually adding noise into the ground line. If your communication system uses multiple lines, they effectively share the same return path and the currents get far more complex, and the noise much worse, in the common ground.

The longer the cable the more voltage difference will be evident along that ground cable. If there is enough difference the delta between ground and the signal voltage will drop so low you are no longer able to distinguish the signal.
The image below demonstrates this. Note you  have two lights above your ground in the distance. You can see that with a nice solid ground you can fairly easily tell in the middle two which light is turned on. However, in the right hand situation where the ground boundary is hard to identify, it is no longer possible to tell if that is a high or low light.

Standards like ETHERNET and other differential communication systems use a different technique that eliminates the need for a ground entirely.
By sending as a plus and minus signal over two dedicated wires the receiver can pick out the signal by examining the difference between those wires rather than comparing it to a passed reference voltage. (i.e. "Ground"). The image below indicates how this works. Notice even with the noisy signals on the right you can still tell which signal is being sent.

This technique not only allows the signal to be transmitted over much greater distance but also reduces the systems susceptibility to common mode noise. Since each signals current paths are also restricted to those two dedicated wires the inter-signal return path sharing is eliminated.
For Ethernet in particular, transformers are used to connect to the wires which provides complete isolation between the transmission medium and the sender/receiver.

A: Both RS-232 and USB have signals referenced to ground, that's why you need one. (Yes, D+ and D- signals in USB are used independently from each other with GND as a reference during device discovery). Ethernet signals are purely differential, so no GND reference is needed.

A: What makes you think it has no ground connection?

*

*"Ground" by definition is a 0V reference for some local circuit.

*Earth ground is one connected to the outside terraferma.

As you may know, all laptop/tablets have floating ground unless connected to some port with an external earth ground such as a VGA cable to a 3 pronged LCD monitor due to the galvanic transformer isolation in the battery charger.
Ethernet also has no signals in the lower spectrum including DC because of the Bi-Phase encoding methods.
More important is that for signal integrity and EMI reduction for egress and ingress, the signals are transmission lines with 75 Ω termination and balanced with CM transformer and 1:1 centre tapped transformer. This raises the CM impedance on the user side for isolation while maintaining the differential impedance on the cable side to local ground in the upper spectrum where signals exist.
See the "ground connections" below

*

*via 1000pF coupling cap and 75 Ohm terminators


Q: Django view that rewrites URL to contain username as a query parameter? I want to do simple analytics over which user is doing what on my Django site.
I think the simplest way is to rewrite all URLs so that they contain "?username=foo".
This will only happen on GET urls that don't already have any URL query parameters.
How do I do this? Can I rewrite the URL to include a new query parameter from a view?

A: Why would you want to add a get parameter to each view while the request already contains the user? Also you should probably use the middleware layer to log user actions.

A: I don't think you would have to change anything except the templates for this.
If your existing url like http://server/myapp/view1 then accessing an url like this http://server/myapp/view1?username=foo will also work.
So your existing views will work as is.
However, you will have to change templates that renders the links as per new scheme. For example for above view if you are doing {% url 'view1' %} to get a link, then you will have to change it to {% url 'view1'%}?username={{user}}.


Q: Explicit solution of the nonlinear Schrödinger equation Consider the linear Schrödinger equation,
$$ (LS)
\begin{cases}
\partial_{t}u= i\Delta u, t\in \mathbb R,\\
u(x,0)=u_{0}(x),
\end{cases}
$$
$x\in \mathbb R^{n}.$ Taking the Fourier transform with respect to the space variable $x$
in $(LS)$, we obtain,
$$
\begin{cases}
\widehat{\partial_{t}u}(\xi,t)=\partial_{t}\hat{u}(\xi,t)=\widehat{i\Delta}u(\xi,t)=-4\pi^{2}i|\xi|^{2}\hat{u}(\xi,t),\\
\hat{u}(\xi, 0)=\hat{u_{0}}(\xi).
\end{cases}
$$
The solution of this family of ordinary differential equations, with parameter $\xi,$ can be written as, $\hat{u}(\xi,t)= e^{-4\pi^{2}it|\xi|^{2}}\hat{u_{0}}(\xi);$ and then taking inverse Fourier transform, we have,
$$u(x,t)=(e^{-4\pi^{2} it|\xi|^{2}}\hat{u_{0}}(\xi) )^\vee:= e^{it\Delta}u_{0}(x).$$
Next, we consider, inhomogeneous problem,
$$ (NLS)
\begin{cases}
\partial_{t}u= i\Delta u +F(x,t), t\in \mathbb R,\\
u(x,0)=u_{0}(x),
\end{cases}
$$
$x\in \mathbb R^{n}, F\in C(\mathbb R:\mathcal{S}(\mathbb R)).$
My Question is:

How to show that the solution of $(NLS)$ is given by the formula,
  $$u(x,t)=e^{it\Delta}u_{0}+\int_{0}^{t}e^{i(t-t')\Delta} F(\cdot,t') dt'.$$

Thanks,


Q: LDA - Assigning keywords to topics I have unstructured data of about 150k documents. I am trying to group these documents using unsupervised learning algorithm. Currently I am using LDA (Latent Dirichlet allocation) in gensim Python. For LDAModel I have passed num_topics=20. Hence my whole 150k data is falling into 20 topics.
Now that I have these groups, I have 2 questions:

*

*How should I assign new documents to these topics?

The approach I am taking is:
Calculate the sum of the word scores of the document per topic and assign the document to the topic with the highest score. However this is not giving me good results.
Is there any better way to get this?

*How do I assign the main keywords that denote the topic?

A: How should I assign new documents to these topics?
Once you have a trained model you can query the model for your document with:
doc_bow = model.id2word.doc2bow(doc.split()) # convert to bag of words format first
doc_topics, word_topics, phi_values = model.get_document_topics(bow, per_word_topics=True)

re.
This code is going to provide you with per-doc and per-word information about the level of belonging to a particular topic. This means the per-word calculations are done for you automatically.
How do I assign the main keywords that denote the topic?
it is difficult to understand what you mean. The keywords denoting a topic along with their weights are the actual LDA model that you got from the training using a corpus.

I suppose you may be interested in reviewing the following notebook [*] for more information how to query model for specific information regarding a  document (per-word topic information, etc.).
[*] from which I took the excerpt of the code above


Q: Git push atomically, only if the target branch is at the expected SHA Is there a way to push to a branch only if it hasn't changed since I last fetched it?
More specifically, I'd like to delete branches that have already been merged, but only if no one else pushes new commits to them between when I check that the branch has been merged and when I push the deletion.
From the git push documentation, I see that it does support a --atomic option, but that option is for making updates to multiple branches atomically with respect to each other, rather than for ensuring that my update to a remote branch will be atomic with respect to other users' updates.
Ie, I want to delete merged branches on a remote git repository without any risk of deleting anyone else's work, even if they are working concurrently.

A: Yes, this is possible by using the --force-with-lease option.  For example:
$ git push --force-with-lease=refs/heads/foo origin :refs/heads/foo

This is designed for force pushes, but works for deletes as well.  The option has many variants and can take explicit values if you like.


Q: git - cannot push to repository - bug with hashmap When I try to push to repository, I got this message
BUG: remote.c:236: hashmap_put overwrote entry after hashmap_get returned NULL

Any idea what is wrong? Google shows nothing...
When I try push to another repository on the same server, it is working correctly. The problem is only with one repo.
Local Git version: 2.36.0.windows.1
Server Git version: 2.19.2

A: Git has self-detected an internal error.  Report this to the Git mailing list (git@vger.kernel.org).  The output from git config --list --show-origin may also be useful to the Git maintainers, along with the output of git ls-remote on the remote in question (origin, probably).  (The bug itself is in your Windows Git; the server version of Git should be irrelevant, but it won't hurt to mention that too.)

A: Based on reporting problem to git team, the problem was caused by branch with an empty name "". After removing this form .git/config, pushing works again.
However, the problem is passed to git team and will probably be solved in future version.


Q: How to get stderr using Popen + vim I am trying capture error messages from gvim using subprocess.Popen(), but not having much luck.
import sys
import subprocess
import time

ppp = subprocess.Popen(
    ["vim", "-g", "--nofork", "--some_option_that_does_not_exist", "blah"],
    stderr=subprocess.PIPE
)
time.sleep(1)
poll = ppp.poll()
err = ''
if poll != None and poll != 0:
    err  = ppp.communicate()
print '-------------------------------->>POLL\n',
print poll
print '-------------------------------->>PPP\n',
print ppp
print '-------------------------------->>err\n',
print err
print '--------------------------------<<\n\n',

print 'Trying to get:\n'
subprocess.Popen(
    ["vim", "-g", "--nofork", "--some_option_that_does_not_exist", "sasa"]
)

Result:
$ ./poperr.py
-------------------------------->>POLL
1
-------------------------------->>PPP
<subprocess.Popen object at 0xb73effec>
-------------------------------->>err
(None, '')
--------------------------------<<

Trying to get:

VIM - Vi IMproved 7.3 (2010 Aug 15, compiled Oct 26 2012 16:45:52)
Unknown option argument: "--some_option_that_does_not_exist"
More info with: "vim -h"

The point is to start vim in background and on success continue with script, on error log error message and abort script.
Guess there are some quirks using vim. Have tested various with no luck. Any ideas?
vim -h:
    -g                      Run using GUI (like "gvim")
    -f  or  --nofork        Foreground: Don't fork when starting GUI

Edit:
To emphasize: It is the (None, '') part that is the issue. As one can see stderr is an empty string: ''. If there is no error it will be None as well (like stdout).
The reason for the sleep is to give the sub-process a chance to succeed or fail. However, the real script keep polling for status on the process to detect if it has ended during its lifetime. As such the sleep is not that important, but reduces stress on the host as a lot of other tasks are skipped.
… and it makes for a more re-producible snippet here. I increased the sleep time in sample to one second to perhaps make it more clear.

Another example would be this. In this case errorfile.txt is always empty.
ppp = subprocess.Popen(
    ["vim", "-g", "--nofork", "--some_option_that_does_not_exist", "blah"],
    stderr=open('errorfile.txt', 'a')
)

A: ppp.communicate() will not be called unless the process terminates in less than 0.01 seconds, which evidently is not happening. Note that ppp.communicate() will wait for the process to finish, so I'm not sure why you do time.sleep() and ppp.poll(). The following consistently works:
import subprocess

stdout, stderr = subprocess.Popen(
    ["vim", "-g", "--nofork", "--nonexistent_option", "blah"],
    stderr=subprocess.PIPE
).communicate()

print '---stdout---\n%s\n---stderr---\n%s\n---expected---' % (stdout, stderr)

subprocess.Popen(
    ["vim", "-g", "--nofork", "--nonexistent_option", "blah"]
).wait()


Q: What's the gain I can have with blocks over regular methods? I am a Java programmer, and I am learning Ruby...
But I don't get where those blocks of codes can give me gain... like what's the purpose of passing a block as an argument ? why not have 2 specialized methods instead that can be reused ?
Why have some code in a block that cannot be reused ?
I would love some code examples...
Thanks for the help !

A: Consider some of the things you would use anonymous classes for in Java. e.g. often they are used for pluggable behaviour such as event listeners or to parametrize a method that has a general layout.
Imagine we want to write a method that takes a list and returns a new list containing the items from the given list for which a specified condition is true. In Java we would write an interface:
interface Condition {
    boolean f(Object o);
}

and then we could write:
public List select(List list, Condition c) {
    List result = new ArrayList();
    for (Object item : list) {
        if (c.f(item)) {
            result.add(item);
        }
    }
    return result;
}

and then if we wanted to select the even numbers from a list we could write:
List even = select(mylist, new Condition() {
    public boolean f(Object o) {
        return ((Integer) o) % 2 == 0;
    }
});

To write the equivalent in Ruby it could be:
def select(list)
  new_list = []
  # note: I'm avoid using 'each' so as to not illustrate blocks
  # using a method that needs a block
  for item in list
    # yield calls the block with the given parameters
    new_list << item if yield(item)
  end
  return new_list
end

and then we could select the even numbers with simply
even = select(list) { |i| i % 2 == 0 }

Of course, this functionality is already built into Ruby so in practice you would just do
even = list.select { |i| i % 2 == 0 }

As another example, consider code to open a file. You could do:
f = open(somefile)
# work with the file
f.close

but you then need to think about putting your close in an ensure block in case an exception occurs whilst working with the file. Instead, you can do
open(somefile) do |f|
  # work with the file here
  # ruby will close it for us when the block terminates
end

A: The idea behind blocks is that it is a highly localized code where it is useful to have the definition at the call site. You can use an existing function as a block argument. Just pass it as an additional argument, and prefix it with an &


Q: HighChart - Stacked Bar chart - To show dash line over the bar chart but it is not visible on Left side of the bar I have attached the screenshot to show the dash line in left side of the chart. It would be helpful if we can achieve the functionality and I tried to increase the width of the border, it is visible slightly. Do you have any proper approach to achieve this?

Code Snippet :
Highcharts.chart('container', {
chart: {
type: 'bar',
charWidth: 520,
chartHeight:300,
margin: [70,0,0,0]
},
xAxis: {
categories: ['Jan'],
visible: false
},
yAxis: {
min: 0,
visible: false
},
plotOptions: {
series:{
stacking:'normal'
},
dataLabels: {
enabled : false,
}
},

series: [{
name: 'John',
data: [{
  y: 15
}]

}, {
name: 'Jane',
data: [{
y: 22
}]
}, {
name: 'Joe',
data: [{
y: 33,
}]
}, {
stacking: false,
data: [55],
grouping: false,
dashStyle:'ShortDash',
color: 'transparent',
borderWidth: 2,
borderColor: 'red',

}]
});
Thanks for the response
[![enter image description here][2]][2]

A: The left side of the bar is connected to the xAxis, which makes the left border less visible. There are some possible solutions to this issue.

*

*You can set the minimum value of the xAxis to -0.1 and set startOnTick property to false. Then the left border is visible (it's not directly connected to the axis).
Demo:
https://jsfiddle.net/BlackLabel/pqy84hvs/
API references:
https://api.highcharts.com/highcharts/xAxis.startOnTick
https://api.highcharts.com/highcharts/xAxis.min
yAxis: {
 min: -0.1,
 visible: false,
 startOnTick: false
}

*You can set the borderWidth property to 3. Then the border is visible.
Demo:
https://jsfiddle.net/BlackLabel/01m6p47f/
API references:
https://api.highcharts.com/highcharts/series.bar.borderWidth
{
 name: 'Joe',
 borderWidth: 3,
 borderColor: 'red',
 data: [{
  y: 33,
 }]
}

*You can also use SVG Renderer and render the border yourself.
Docs:
https://api.highcharts.com/class-reference/Highcharts.SVGRenderer
Example demo of using SVG Renderer:
https://jsfiddle.net/BlackLabel/2koczuq0/


Q: how to connect socket_io_client via https in flutter? I work with socket_io_client. So how do I connect the https socket in my application.
below is code example
Socket socket = io('https://abcd.co.in:1000005',
OptionBuilder().setTransports(['websocket']).build());

    socket.connect();
    socket.onConnect((_) {
      print('connect');
      socket.emit("Client", [MyConstants.CtName]);
      socket.emit("room", [MyConstants.CtName]);
    });

I am use socket_io_common: ^2.0.0 because of my flutter channel is flutter channel stable 2.2.3.
also I am use socket_io_client: any. it is work fine with my other http socket url


Q: Install/Uninstall WSS 3.0 What is best and easiest way to uninstall WSS 3.0 from your server.
I simply tried Remove option from WSS setup wizard but it does  not uninstall all content.
like
1> Site created (they were still there in virtual Directories)
2> Database
3> Dlls from GAC
4> Custom controls under Templates->ControlTemplates
So what i did is just removed Databse (admin,configuration and WSS_Content)
but when i tried to reinstall WSS it gave an error "Failed To Connect Content Database".
Do any one have any idea why this is happening?
SQL services are already running and i am able to access sql server through window credentials

A: First of all when removing SharePoint (any version) the only account that can do this successfully is the same account that installed it.
The uninstaller does not remove any content created by SharePoint, only the files installed during the setup. Just like removing Office does not remove all your documents.

A: WSS 3.0 makes use of Windows Internal Database, which cannot be removed using Add/Remove programs options.
Please refer the below Microsoft KB Link to remove it manually:
http://support.microsoft.com/kb/920277/en-us
Additional Notes: If you uninstall Windows SharePoint Services 3.0, and then later install Windows SharePoint Services 3.0 on the same computer, the Setup program could fail when creating the configuration database causing the entire installation process to fail. You can prevent this failure by either deleting all the existing Windows SharePoint Services 3.0 databases on the computer or by creating a new configuration database. You can create a new configuration database by running the following command:
psconfig -cmd configdb -create -database <uniquename>

Hope this helps.

A: Thanks Wictor & kamleshrao
Just one more thing i want to add here is the resolution of error.
Just change Registry Key for server role (HKLM/Software/Microsoft/Shared Tools/Web Server Extensions/12.0/WSS/ServerRole) is set incorrectly.  It was set to SINGLESERVER.
--Please backup your registry settings before making any change in it----
I changed ServerRole’s value from SINGLESERVER to APPLICATION and it worked.
for more detail please refer
Link
But i couldn't figure out what is logic behind it.How and when it's changed to SINGLESERVER during installation/un-installation and why changing it to 'Application' worked?

A: I have been having a lot of trouble installing WSS 3.0 on windows server 2008, usign SQL 2008.
I have found often the solution where it asks to create the db usign the psconfig command line but without luck.
I the registry, the server role was WFE and when I changed it to APPLICATION, it is worst. The setup freezes.
I first made a mistake, installing wss as a standalone.... do you know any other reg key that might makes the connection to sql fails   ? It is weird since the setup creates 2 bd (config and admin content) and then cannot connects to it.
I have the same error when trying to connect to an existing farm. It's saying that sharepoint serivces are not initialized.
Thanks for any input.


Q: Can't hear sound from bluetooth speaker I'm using Raspberry Pi with Ubuntu 22.10 and Java 19.
I'm trying to play a sound with the following code:
private static void testMixers() throws IOException, UnsupportedAudioFileException
{
    try (AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new BufferedInputStream(Objects.requireNonNull(Listener.class.getResourceAsStream("/alarmSound.wav")))))
    {
        final Scanner scanner = new Scanner(System.in);
        for (Mixer.Info info : AudioSystem.getMixerInfo())
        {
            System.out.println("Testing sound for mixer \"" + info + "\"...");
            try (Clip clip = AudioSystem.getClip(info))
            {
                clip.open(audioInputStream);
                clip.setFramePosition(0);
                clip.start();
                System.out.println("Did you hear any sound? (true|false)");
                if (Boolean.parseBoolean(scanner.nextLine()))
                    return;
            }
            catch (Exception e)
            {
                System.out.println(e);
            }
        }
    }
    System.out.println("Mixer not found!");
}

alarmSound.wav is under src/main/resources (this is a Maven project).
AudioSystem.getMixerInfo() gives me the following Mixer.Info[]:

*

*Port Headphones [hw:0], version 5.19.0-1006-raspi

*Port vc4hdmi0 [hw:1], version 5.19.0-1006-raspi

*Port vc4hdmi1 [hw:2], version 5.19.0-1006-raspi

*Headphones [default], version 5.19.0-1006-raspi

*Headphones [plughw:0,0], version 5.19.0-1006-raspi

*vc4hdmi0 [plughw:1,0], version 5.19.0-1006-raspi

*vc4hdmi1 [plughw:2,0], version 5.19.0-1006-raspi
Only the Headphones Mixers don't give the error:

java.lang.IllegalArgumentException: Line unsupported: interface Clip supporting format PCM_SIGNED unknown sample rate, 16 bit, stereo, 4 bytes/frame, big-endian

I didn't tested the headphone jack.
This is completely different from Ubuntu 22.04 which gave more Mixer.Infos.
Is there any workaround? it seems that every Ubuntu version requires different workaround for being able to play a sound that can be heard not through the headphones (but from bluetooth speakers or via HDMI for example).


Q: Can I use html area tag to create different shape text containers? Is it possible to create text container which is not square/rectangle?
Can I use area tag for this?
Any example snippet will be appreciated.

A: No. All elements are rectangles by defintion. Even the <area> tag wouldn't get past that.


Q: Como puedo monitorizar un proceso java que se cierra sin razón aparente? buen día. Tengo un proceso java (Spring Boot) corriendo en un servidor AWS el cual se sierra sin dejar rastro alguno y siempre a las misma hora (19:05), verifique el log y no encuentro absolutamente nada, también pensé que podía ser que el aws se reiniciara pero al parecer tampoco es el caso. Un detalle extra es que están 2 servicios de spring boot pero con diferentes dependencias y al parecer el primero no se detiene, solo el segundo.
Sistema operativo: Linux 2 AMI
El proceso se lanza desde un "java -jar"
Las dependencias que usa el servicio son muy simples:
   <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-log4j2</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
          <groupId>com.google.firebase</groupId>
          <artifactId>firebase-admin</artifactId>
          <version>7.0.1</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20200518</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
    </dependencies>

Si ayuda en algo adjunto el archivo que ocupo para generar los logs:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN" monitorInterval="30">
    <Properties>
        <Property name="LOG_PATTERN">%d{yyyy-MM-dd HH:mm:ss.SSS} %-5p ${PID:- } --- [%-40.40logger{39}]: %X{REQUEST_ID} %msg%n</Property>
        <property name="api.name">${bundle:application:configuration.api.name}</property>
        <property name="dir.home">${bundle:application:configuration.api.home}</property>
    </Properties>
    <Appenders>
        <Console name="console" target="SYSTEM_OUT">
            <PatternLayout pattern="${LOG_PATTERN}" />
        </Console>

        <RollingFile name="file"
            fileName="${dir.home}/${api.name}/Log/${api.name}.log"
            filePattern="${dir.home}/${api.name}/Log/$${date:yyyy-MM}/${api.name}-%d{yyyy-MM-dd}-%i.log.gz">
            <PatternLayout pattern="${LOG_PATTERN}" />
            <Policies>
                <TimeBasedTriggeringPolicy /><!-- Rotated everyday -->
                <SizeBasedTriggeringPolicy size="5 MB" />
            </Policies>
        </RollingFile>
    </Appenders>
    <Loggers>
        <Root level="info">
            <AppenderRef ref="console" />
            <AppenderRef ref="file" />
        </Root>
    </Loggers>
</Configuration>


Q: Is gaining enough understanding of SVD/QR factorization until you have their formulas memorized useful? Is knowing how to compute SVD/QRfactorization,Power iteration/power method by hand without notes useful in applications such as Statistics?
Now adays, we can do everytime by Mathematica/computer without really understanding the mechanics of matricies.
Does knowing the manual computation cold assist us with anything?
I 've taken linear algebra, but everytime I have to do a QR factorization or SVD, I have to look up the formula. It doesn't make intuitive sense where I have it memorized, should I take another linear algebra class that assumes basic knowledge of linear algebra, but focuses specifically on matrix decompositions?

A: I think if we understand these factorizations sufficiently well then we can rederive them on the spot. For example, if we know that QR factorization encodes the Gram-Schmidt process, then we can see what the formula for the QR factorization is and a way to compute it (by doing the Gram-Schmidt process).
For the SVD, one should understand that $v_i$ is chosen to be the unit vector $v$ which maximizes $\| Av \|$ subject to the constraint that $v$ is orthogonal to the vectors $v_1, \ldots, v_{i-1}$. If we define a nonnegative scalar $\sigma_i$ and unit vector $u_i$ so that $A v_i = \sigma_i u_i$, and if we are good at block matrix multiplication, then we can see immediately that
$$
\tag{1}AV = U \Sigma,
$$ where $V$ is the matrix whose columns are the vectors $v_i$, $U$ is the matrix whose columns are the vectors $u_i$, and $\Sigma$ is a diagonal matrix with diagonal entries $\sigma_i$. Multiplying both sides of (1) on the right by $V^{-1} = V^T$, we see that $A = U \Sigma V^T$, and we can't forget it.
We could equivalently say that $v_i$ is chosen to be the unit vector $v$ that maximizes $\| Av\|^2 = v^T A^T A v$ subject to the constraint that $v$ is orthogonal to the vectors $v_1, \ldots, v_{i-1}$. If we are familiar with the variational characterization of the eigenvalues of a symmetric matrix, we now recognize that the vectors $v_i$ are eigenvectors of the matrix $A^T A$. This gives us a way to compute them, if we are able to compute eigenvectors of a symmetric matrix (which is not necessarily easy or obvious).
(There are more efficient algorithms for computing these factorizations which are not obvious.)


Q: Getting the Value which is already selected in drop down menu by Selenium Webdriver i have a Drop Down menu which has pre-selected a value please help me how to get the selected value text and print it in console
drop down menu html code is
<select id="ctl00_ContentPlaceHolder1_ddlCalculation" class="normalText"
    style="width:100%;"
    onchange="javascript:LoadMethods(this.value);
              CallonChange(this.value,'spn_ddlCalculation');
              return false;"
    disabled="disabled" name="ctl00$ContentPlaceHolder1$ddlCalculation">

    <option value="0" selected="selected">--- Select ---</option>
    <option value="f">Formula Based</option>
    <option value="m">Formula Based with Matrix Table</option>
    <option value="q">Quantity Based</option>
    <option value="t">Time Based</option>
</select>

A: Please try the following and let me know if it works :
Select dropdown = new Select(driver.findElement("Use the correct selector");
WebElement option = dropdown.getFirstSelectedOption();
String content = option.getText();
System.out.println("selected Value " + content);


Q: how to write value to file with node.js so i have a multiple requests from client, each request contain data,
{
 key: 'string',
 public_url: 'string'| null ,
 value: 'string',
 created_at:'string',
 updated_at: 'string',
 content_type: 'string',
 size: 'int',
 checksum: 'string',
 theme_id: 'int',
 warnings: []
}

so lets say i have 243 requests, for each request i need to write the data to file,
i have tried many ways like fs.writeFile , fs.writeFileSync,fs.createWriteStream,promises,etc,
const sourceStoreShopName = session.shop.split('.')[0]
    const fetchData = await restClient.get({
        path: 'assets',
        theme_id: id,
        query: {
            ['asset[key]']: assetPath,
        },
    })
    const asset = fetchData.body.asset
    const filename = asset.key.split('/')
    const dir = filename.length > 2 ? `${process.cwd()}/tmp/${sourceStoreShopName}/${filename[0]}/${filename[1]}` : `${process.cwd()}/tmp/${sourceStoreShopName}/${filename[0]}`
    if (!fs.existsSync(dir)) {
        fs.mkdirSync(dir, { recursive: true })
    }
    const ws = fs.createWriteStream(path.join(dir, filename.slice(-1)[0]))
    const API_LIMIT = fetchData.headers.get('x-shopify-shop-api-call-limit').split('/')
    return asset
}

so i want to copy content from value to file
for one file it passed , more then 2 got the error.
the error i got
1:23:07 PM [vite] http proxy error:
Error: socket hang up
  at connResetException (node:internal/errors:704:14)
  at Socket.socketOnEnd (node:_http_client:505:23)
  at Socket.emit (node:events:525:35)
  at endReadableNT (node:internal/streams/readable:1359:12)
  at process.processTicksAndRejections (node:internal/process/task_queues:82:21)

any ideas how to solve that problem?


Q: Best method to get double value from datetime in jquery Which is the best way to convert datetime to double in jquery? I have used Date.parse. But, it is not correct in few cases. Also,i am unable to pass datetime format for that method.
-
Viji

A: In JavaScript, you can simple do variablename.toFixed(2); for that.
Example:
var num1 = 12312.12312
console.log(num1.toFixed(2)); // Will give 12312.12


Q: javascript program to check if a string is palindromes not returning false I wrote this bit of code a a part of an exercise to check weather or not a string is palindromes. They program is working correctly in terms of checking the string but it does not return false when the string is not palindromes. What am I doing wrong? thanks
//convert the string to array
var stringArr = [ ];
var bool;
function palindrome(str) {
  // make lowercase
  var lowerCase = str.toLowerCase();
  //remove numbers, special characters, and white spaces
  var noNumbers = lowerCase.replace(/[0-9]/g, '');
  var noSpecials = noNumbers.replace(/\W+/g, " ");
  var finalString = noSpecials.replace(/\s/g, '');
  stringArr = finalString.split("");

    if (stringArr.sort(frontToBack)==stringArr.sort(backToFront)) {
       bool = true;
    }
    else {
       bool= false;

    }
  return bool;
}
function frontToBack (a,b) {return a-b;}
function backToFront (a,b) {return b-a;}

palindrome("eye");

A: if (stringArr.sort(frontToBack)==stringArr.sort(backToFront)) { is your problem.
In JavaScript, the sort method updates the value of the variable you are sorting. So in your comparison, once both sort's have run, both end up with the same value (since the second sort, effectively overrides the first).
For example.
var a = [1,7,3];
a.sort();
console.log(a); // will print 1,3,7

Edit: had a quick test, I think eavidan's suggestion is probably the best one.
Edit2: Just put together a quick version of a hopefully working palindrome function :)
 function palindrome(str) { return str.split("").reverse().join("") == str;}

A: It is because string subtraction yields NaN, which means both sorted arrays are the same as the original.
Even if you did convert to ASCII coding,  you sort the entire string, then for instance the string abba would be sorted front to back as aabb and back to front as bbaa. (edit: and also what Carl wrote about sort changing the original array. Still - sort is not the way to go here)
What you should do is just reverse the string (using reverse on the array) and compare.

A: You might do as follows;

var isPalindrome = s => { var t = s.toLowerCase()
                                   .replace(/\s+/g,"");
                          return [].slice.call(t)
                                   .reverse()
                                   .every((b,i) => b === t[i]);
                        };

console.log(isPalindrome("Was it a car or a cat I saw"));
console.log(isPalindrome("This is not a palindrome"));

A:        function pal()
        {
            var x=document.getElementById("a").value;

            //input String

            var y="";

           //blank String

            for (i=x.length-1;i>=0;i--)
          //string run from backward

                {

                    y=y+x[i];
       //store string last to first one by one in blank string

                }

            if(x==y)

          //compare blank and original string equal or not

                {

                    console.log("Palindrome");

                }

            else

                {

                    console.log("Not Palindrome ");

                }

        }


Q: Is it possible to access the ZFS checksums to compare files I have a FreeNAS 8 machine (FreeBSD 8.2-RELEASE-p1) with two different shares on it. I'm migrating files from Share1 to Share2. The Shares have different directory structures and naming conventions. I'm looking for a way to verify that a file on Share1 actually exists (and is accurate) on Share2.
My plan is basically to checksum every file on both Shares and make sure that all the checksums in the Share1 set exist in the Share2 set. I can do this relatively easily with a bash script, but it'll take a long time to generate each of the checksum sets. My question is: Is it possible to access the native ZFS checksums to use them for this comparison?

A: I don't believe it is possible to extract the block level checksums from a ZFS filesystem, but since the checksums are at the block level, not the file level, it probably wouldn't help you anyway.
A while back I wrote a couple of programs for producing a manifest of a filesystem and for comparing an existing filesystem with that manifest.
Here's chksum.pl
#! /usr/bin/perl
#
# generate a system manifest
#

use strict;

use File::Find;
use Digest::MD5;

our %config;

$| = 1;

&main;
exit;

sub initialize {
    my ($exclude_next, $include_next, @ex, @in, @ex_pats, @in_pats, %in, @x);

    # the exclude/include list looks like what you would pass to rsync
    my $elist = ['--exclude' => '/var/log',
                 '--exclude' => '/var/tmp',
                 '--exclude' => '/tmp',
                ];

    foreach my $op (@$elist) {
        if ($op eq '--exclude') {
            $exclude_next = 1;
        } elsif ($op eq '--include') {
            $include_next = 1;
        } elsif ($op eq '--delete') {
            # ignore
        } else {
            if ($exclude_next) {
                push(@ex, $op);
            } elsif ($include_next) {
                push(@in, $op);
            } else {
                warn "don't know what to do with $op\n";
            }
            $include_next = 0; $exclude_next = 0;
        }
    }

    $config{'exclude_list'} = \@ex;
    $config{'include_list'} = \@in;
    @ex_pats = map(glob($_), @ex);
    @in_pats = map(glob($_), @in);

#    print STDERR "exclusion patterns:\n", join("\n", @ex_pats), "\n\n";
#    print STDERR "inclusion patterns:\n", join("\n", @in_pats), "\n\n";

    # remove exclusions that exactly match inclusions
    foreach my $pat (@in_pats) {
        $in{$pat}++;
    }
    foreach my $pat (@ex_pats) {
        next if $in{$pat};
        push(@x, $pat);
    }

    $config{'ex_pats'} = \@x;
}

sub wanted {
    my($type, $extra);

    my $path = $File::Find::name;

    my @ex = grep($path =~ m"^$_", @{$config{'ex_pats'}});

    my($mode, $uid, $gid, $dev) = (lstat($path))[2,4,5,6];

    if (scalar(@ex) > 0) {
        # if we're excluding, and it was a dir, don't bother to descend
        $File::Find::prune = -d _;
        return;
    }

    $mode &= 07777;                             # mask off mode bits
    if (-d _) {
        $type = "dir ";
    } elsif (-l _) {
        $type = "link";
        $extra = "\"" . readlink($path) . "\"";
    } elsif (-f _) {
        $type = "file";
        $extra = &md5sum($path);
        return unless defined($extra);
    } elsif (-p _) {
        $type = "pipe";
    } elsif (-S _) {
        $type = "sock";
    } elsif (-b _) {
        $type = "bdev";
        $extra = "\"" . ($dev >> 8) . " " . ($dev & 0377) . "\"";
    } elsif (-c _) {
        $type = "cdev";
        $extra = "\"" . ($dev >> 8) . " " . ($dev & 0377) . "\"";
    } else {
        $type = "unk ";
    }

    printf "%s 0%04o %d %d \"%s\"", $type, $mode, $uid, $gid, $path;
    print " $extra" if $extra;
    print "\n";
}

sub md5sum {
    my $file = shift;
    my $context = Digest::MD5->new;
    unless(open(F, $file)) {
        warn "WARNING: couldn't open $file: $!\n";
        return;
    }
    $context->addfile(*F);
    close(F);
    my $digest = $context->hexdigest;
    return($digest);
}

sub main {
    &initialize;

    &find({no_chdir => 1, wanted => \&wanted}, '/');
}

and here's verify_sum.pl
#! /usr/bin/perl

# verify that a system matches the sum file produced by chksum.pl

use strict;

use File::Find;
use Digest::MD5;
use Text::ParseWords;

our %config;

$| = 1;

&main;
exit;

sub initialize {
    my ($exclude_next, $include_next, @ex, @in, @ex_pats, @in_pats, %in, @x);

    my $elist = ['--exclude' => '/var/log',
                 '--exclude' => '/var/tmp',
                 '--exclude' => '/tmp',
                ];

    foreach my $op (@$elist) {
        if ($op eq '--exclude') {
            $exclude_next = 1;
        } elsif ($op eq '--include') {
            $include_next = 1;
        } elsif ($op eq '--delete') {
            # ignore
        } else {
            if ($exclude_next) {
                push(@ex, $op);
            } elsif ($include_next) {
                push(@in, $op);
            } else {
                warn "don't know what to do with $op\n";
            }
            $include_next = 0; $exclude_next = 0;
        }
    }

    $config{'exclude_list'} = \@ex;
    $config{'include_list'} = \@in;
    @ex_pats = map(glob($_), @ex);
    @in_pats = map(glob($_), @in);

#    print STDERR "exclusion patterns:\n", join("\n", @ex_pats), "\n\n";
#    print STDERR "inclusion patterns:\n", join("\n", @in_pats), "\n\n";

    # remove exclusions that exactly match inclusions
    foreach my $pat (@in_pats) {
        $in{$pat}++;
    }
    foreach my $pat (@ex_pats) {
        next if $in{$pat};
        push(@x, $pat);
    }

    $config{'ex_pats'} = \@x;
}

sub md5sum {
    my $file = shift;
    my $context = Digest::MD5->new;
    unless(open(F, $file)) {
        warn "WARNING: couldn't open $file: $!\n";
        return;
    }
    $context->addfile(*F);
    close(F);
    my $digest = $context->hexdigest;
    return($digest);
}

sub wanted {
    my $path = $File::Find::name;

    my @ex = grep($path =~ m"^$_", @{$config{'ex_pats'}});

    if (scalar(@ex) > 0) {
        # if we're excluding, and it was a dir, don't bother to descend
        $file::Find::prune = -d $path;
        return;
    }

    if (! $config{'seen'}->{$path}) {
        warn "new file: $path\n";
        $config{'new'}++;
    }
}

sub main {
    $config{'mismatch'} = 0;
    $config{'missing'} = 0;
    $config{'new'} = 0;

    &initialize;

    while (<>) {
        chomp;
        my ($type, $mode, $uid, $gid, $path, $extra) = &shellwords($_);
        my ($etype, $eextra);

        $mode = oct($mode);
        my($emode, $euid, $egid, $edev) = (lstat($path))[2,4,5,6];

        if (! -e _) {
            warn "missing file: $path\n";
            $config{'missing'}++;
            next;
        }

        $emode &= 07777;
        if (-d _) {
            $etype = "dir";
        } elsif (-l _) {
            $etype = "link";
            $eextra = readlink($path);
        } elsif (-f _) {
            $etype = "file";
            $eextra = &md5sum($path);
            return unless defined($eextra);
        } elsif (-p _) {
            $etype = "pipe";
        } elsif (-S _) {
            $etype = "sock";
        } elsif (-b _) {
            $etype = "bdev";
            $eextra = ($edev >> 8) . " " . ($edev & 0377);
        } elsif (-c _) {
            $etype = "cdev";
            $eextra = ($edev >> 8) . " " . ($edev & 0377);
        } else {
            $etype = "unk";
        }

        if ($type ne $etype) {
            warn "mismatch file type ($type vs $etype): $path\n";
            $config{'mismatch'}++;
        } else {
            # types are the same, compare other factors

            if ($mode != $emode) {
                warn sprintf("mismatch mode (0%o vs 0%o): %s\n", $mode, $emode, $path);
                $config{'mismatch'}++;
            }
            if ($uid != $euid) {
                warn "mismatch uid ($uid vs $euid): $path\n";
                $config{'mismatch'}++;
            }
            if ($gid != $egid) {
                warn "mismatch gid ($gid vs $egid): $path\n";
                $config{'mismatch'}++;
            }
            if ($extra ne $eextra) {
                if ($etype eq 'link') {
                    warn "mismatch link target ($extra vs $eextra): $path\n";
                } elsif ($etype eq 'file') {
                    warn "mismatch file checksum ($extra vs $eextra): $path\n";
                } elsif ($etype eq 'bdev' or $etype eq 'cdev') {
                    warn "mismatch device node ($extra vs $eextra): $path\n";
                }
                $config{'mismatch'}++;
            }
        }

        $config{'seen'}->{$path}++;
    }

    # now walk the filesystem looking for "new" files

    &find({no_chdir => 1, wanted => \&wanted}, '/');

    print "$config{'mismatch'} files changed\n";
    print "$config{'missing'} files missing\n";
    print "$config{'new'} new files\n";

    if ($config{'mismatch'} > 0 or
        $config{'missing'} > 0 or
        $config{'new'} > 0) {
        exit 1;
    }

    exit 0;
}

You'll probably want to tweak these scripts a bit for things like the exclude list, root directory of the comparison, etc.


Q: How can I add meta data to the head section of the page from a wordpress plugin? I am writing a wordpress plugin and need to add some meta tags to the head section of the page from within my plugin. Does anyone know how I would do this?
Thanks

A: Yes you can add an action hook to wp_head like this:
add_action('wp_head', myCallbackToAddMeta);
function myCallbacktoAddMeta(){
  echo "\t<meta name='keywords' content='$contents' />\n";
}


Q: Change button background programmatically I'm creating a Tic-Tac-Toe app using Android Studio, this is the layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.company.alex.tic_tac_toe.MainActivity"
android:layout_margin="16dp"
android:layout_marginBottom="16dp">

<Button
    android:id="@+id/B2"
    android:background="#33b5e5"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true"
    android:layout_width="80dp"
    android:layout_height="80dp"
    android:textSize="@dimen/activity_vertical_margin"
    tools:textStyle="normal"
    tools:textSize="36sp" />

<Button
    android:layout_height="80dp"
    android:layout_above="@+id/B2"
    android:layout_centerHorizontal="true"
    android:id="@+id/A2"
    android:layout_marginBottom="16dp"
    android:background="#33b5e5"
    android:layout_width="80dp" />

<Button
    android:layout_alignBottom="@+id/B2"
    android:layout_toEndOf="@+id/B2"
    android:id="@+id/B3"
    android:background="#33b5e5"
    android:layout_marginLeft="16dp"
    android:layout_width="80dp"
    android:layout_height="80dp"
    tools:textSize="@android:dimen/thumbnail_width" />

<Button
    android:id="@+id/B1"
    android:layout_below="@+id/A2"
    android:layout_toStartOf="@+id/B2"
    android:layout_marginRight="16dp"
    android:background="#33b5e5"
    android:layout_width="80dp"
    android:layout_height="80dp" />

<Button
    android:layout_alignTop="@+id/A2"
    android:layout_alignEnd="@+id/B1"
    android:id="@+id/A1"
    android:background="#33b5e5"
    android:layout_width="80dp"
    android:layout_height="80dp" />

<Button
    android:id="@+id/C2"
    android:background="#33b5e5"
    android:layout_below="@+id/B2"
    android:layout_toEndOf="@+id/B1"
    android:layout_marginTop="16dp"
    android:layout_width="80dp"
    android:layout_height="80dp" />

<Button
    android:layout_alignTop="@+id/C2"
    android:layout_toStartOf="@+id/C2"
    android:id="@+id/C1"
    android:background="#33b5e5"
    android:layout_marginRight="16dp"
    android:layout_width="80dp"
    android:layout_height="80dp" />

<Button
    android:layout_alignTop="@+id/C2"
    android:layout_toEndOf="@+id/C2"
    android:id="@+id/C3"
    android:layout_marginLeft="16dp"
    android:background="#33b5e5"
    android:layout_width="80dp"
    android:layout_height="80dp" />

<Button
    android:text="NUOVA PARTITA"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_alignParentStart="true"
    android:id="@+id/bNewGame"
    android:layout_alignParentEnd="true"
    android:background="#f17a0a"
    tools:textSize="24sp" />

<Button
    android:layout_height="80dp"
    android:id="@+id/A3"
    android:background="#33b5e5"
    android:layout_width="80dp"
    android:layout_alignTop="@+id/A2"
    android:layout_alignStart="@+id/B3" />

<TextView
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_marginBottom="18dp"
    android:id="@+id/punteggio"
    android:layout_width="80dp"
    android:layout_alignParentEnd="true"
    android:layout_alignParentStart="true"
    android:textAppearance="@style/TextAppearance.AppCompat" />

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:srcCompat="@drawable/grigio"
    android:id="@+id/imageView5"
    android:layout_alignBottom="@+id/C2"
    android:layout_alignEnd="@+id/B3"
    android:layout_alignTop="@+id/A2"
    android:layout_alignStart="@+id/B1"
    android:background="@drawable/grigio" />

</RelativeLayout>

I would like to change the background color of the three buttons when a player wins.
I check the winner in this part of code
`{
    boolean there_is_a_winner = false;
    //prima si controllano le linee orizzontali
    if (a1.getText() == a2.getText() && a2.getText() == a3.getText() && !a1.isClickable())
        there_is_a_winner = true;
    else if (b1.getText() == b2.getText() && b2.getText() == b3.getText() && !b1.isClickable())
        there_is_a_winner = true;
    else if (c1.getText() == c2.getText() && c2.getText() == c3.getText() && !c1.isClickable())
        there_is_a_winner = true;

        //adesso si va a controllare le linee verticali
    if (a1.getText() == b1.getText() && b1.getText() == c1.getText() && !a1.isClickable())
        there_is_a_winner = true;
    else if (a2.getText() == b2.getText() && b2.getText() == c2.getText() && !b2.isClickable())
        there_is_a_winner = true;
    else if (a3.getText() == b3.getText() && b3.getText() == c3.getText() && !c3.isClickable())
        there_is_a_winner = true;

        //adesso si controllano le diagonali
    if (a1.getText() == b2.getText() && b2.getText() == c3.getText() && !a1.isClickable())
        there_is_a_winner = true;
    else if (a3.getText() == b2.getText() && b2.getText() == c1.getText() && !b2.isClickable())
        there_is_a_winner = true;`

if i put "Button11.setBackgroundColor(Color.RED);" under the first if the program fails
How can I do this?


Q: React gives me red underline errors but there is no error Visual Code gives errors in lines but there are no errors in those lines.

A: Please rename your file to "todo.jsx".
Explanation:
VSCode and other IDEs choose your parser based on the file extension. For VSCode it looks like you are creating a "normal" JavaScript file. But JavaScript does not know tags, so you get an error message.
A small addition: if you ever work with TypeScript in React, the same applies: instead of the .ts extension you should choose the .tsx extension.

A: It looks like your file is named ToDO.js. Since you're using JSX syntax, the file should be given a .jsx extension, so that VSCode knows how its syntax should be parsed (and, as a result, what errors to display).
So, rename it to ToDO.jsx.


Q: Tkinter Wait for Key to Be Pressed I am using Python 3 and Tkinter, and I have a wait() function, waiting until the right arrow key or left arrow key is pressed, however, it just freezes everything, and I have to force stop the program.
from tkinter import *

right = left = False

def setLeft(event):
    global left
    left = True
    print('Left!')
def setRight(event):
    global right
    right = True
    print('Right!')

def wait():
    global right, left
    left = right = 0
    while not (left or right):
        pass
    print(right) #0 for left, 1 for right
    left = right = 0

root = Tk()
root.bind('<Left>', setLeft)
root.bind('<Right>', setRight)

Is there a way for the wait() function to work like it is supposed to, or do I need to find a different way?

A: Yes, you need a different way, because of event-driven nature of Tkinter GUI programming. When some event lead you to your wait() function there it is: you're stuck in infinite loop, and you can't get outside with events anymore!
As @Bryan Oakley pointed - GUI is constantly in a waiting state by default, since you reached a mainloop(). And I think, that you trying just suppress all other events (or just navigate keys) when user navigating through a tree , except this two (Left and Right clicks).
So here is a small example:
import tkinter as tk

# Main - application
class App(tk.Tk):
    # init of our application
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        self.minsize(width=450, height=100)
        self.wm_title('Just another example from SO')
        self.wait_state = False
        self.init_events()

    # switch state
    def switch_wait_state(self, event):
        self.wait_state = not self.wait_state
        print('Wait state switched to: %s ' % self.wait_state)

    # init events
    def init_events(self):
        self.bind('<Key>', self.wait)
        self.bind('<Control-s>', self.switch_wait_state)

    # waiter(listener) for keypress
    def wait(self, event):
        if self.wait_state and any(key == event.keysym for key in ['Left', 'Right']):
            print('I have successfully waited until %s keypress!' % event.keysym)
            self.do_smth(event.keysym)
        else:
            print('Wait state: %s , KeyPress: %s' % (self.wait_state, event.keysym))
            self.do_nhth()

    @staticmethod
    def do_smth(side):
        print("Don't be rude with me, Im trying my best on a %s side!" % side)

    @staticmethod
    def do_nhth():
        pass

app = App()
app.mainloop()


Q: Get name of All Constraints from access table in java How can I get all constraints like Primary Key and Foreign Key defined in MS Access database.
For MySql, we use describe table_name
Similarly, what is the query for MS Access for using it in java program?

A: import java.sql.*;
public class DescQueryOutput{

  public static void main(String args[])
  {
      try
      {
          Class.forName("com.mysql.jdbc.Driver");
          Connection con = DriverManager.getConnection ("jdbc:mysql://localhost:3306/test","root","root");
          Statement stmt = con.createStatement();
          String query = "DESC newaccount";

          ResultSet rs = stmt.executeQuery(query);
          System.out.println("COLUMN NAME\tDATATYPE\tNULL\tKEY\tDEFAULT\tEXTRA");
  while (rs.next())
  {
      System.out.print(rs.getString(1)+"\t");
      System.out.print(rs.getString(2)+"\t");
      System.out.print(rs.getString(3)+"\t");
      System.out.print(rs.getString(4)+"\t");
      System.out.print(rs.getString(5)+"\t");
      System.out.println(rs.getString(6));
  }
      }

      catch (SQLException e) {
          e.printStackTrace();
      } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

      finally {
      }
  }
}


Q: If entropy is increasing does it mean universe is non-deterministic? I watched some video where they said entropy can be considered as information.
They also stated that universe's entropy is always increasing...
Now here comes the problem my IT mind can't understand:
If entropy is increasing, in other words universe is conveying more and more information, doesn't it mean it is ultimately non-deterministic?
I mean for new information to be introduced it must come from some random source, otherwise it's not new information - if it was derived it would mean it could be compressed to what we already had - so no new information...
So what am I missing?

A: Your question is an excellent one and I think your IT approach is spot on.
The contradiction you rightly point out arises partly from the subtle differences between the different Conditional Entropies (Conditional Informations) at play in this discussion.
Leaving aside Universes for the moment, let's instead think about a truly thermodynamically isolated system. If that system is deterministic, then, as you say, one can always compute its state at any time given a full specification of its beginning state. The most losslessly compressed description of the system possible then measures the amount of "information" in the system as the Kolmogorov Complexity relative to the language you use to define the compression algorithm in - be aware that an absolute measure of information is not definable in these terms, only relative to a certain language, but I should think that you appreciate that fact.
As you rightly point out, this measure of information does not change with time: it specifies once and for all the system's history
If there are $\Omega$ possible microstates at some time, and if we can assume the Ergodic Hypothesis that all are equally likely, then this minimum information in bits is $\log_2\Omega + \Delta$: which comprises $\log_2\Omega$ bits to write down the integer in $1,\,2,\,\cdots,\,\Omega$ naming which microstate the system is in and a fixed length "foreword" or "header" that describes how to decode the integer into the relevant microstate. As $\Omega$ gets mightily big, $\log_2\Omega$ overwhelms $\Delta$ and so we can make the proportional error in the storage space needed to define the microstate arbitrarily small by looking at bigger and bigger systems and so we often forget about $\Delta$. This justifies the somewhat sloppy statement that the storage people often cite is simply $\log_2\Omega$ bits.
But $\log_2\Omega$ is not the same as the thermodynamic entropy, which is defined wholly in terms of macroscopic state variables such as temperature, pressure, volume, moles of this chemical reactant here and moles of that reactant there and so forth. This is the Conditional Entropy (Conditional Informations): the entropy conditioned on the knowledge of these macrostate parameters. Not all of the possible states of an isolated system are consistent with certain macrostate observations, so the number of states that the system might be in if we know its macrostate is in general smaller than $\Omega$, and so the system's thermodynamic entropy is in general smaller than $\log_2\Omega$ and moreover, this conditional entropy can change with time as the system's microstate evolves.
Now it can be shown, from the laws of large numbers alone, that for a system of $N$ statistically independent particles, the number of bits per particle $\frac{1}{N} \log_2 \Omega$ needed to specify the particle's microstate is arbitrarily near to the Shannon entropy per particle of the a priori maximum likelihood microstate, with the two quantities equal in the limit as $N\to\infty$. What this means is that in any large system of particles there are states that look almost exactly like maximum a priori likelihood states and there is almost nothing else. Microstates that are significantly different from the maximum likelihood one do of course exist, but they form a fantastically small proportion of the total so that if the system for whatever reason finds itself in one of these unlikely states, any evolution of the system will almost certainly carry it nearer to the maximum likelihood one. These unusual states might be extremely simple to specify: our $\log_2\Omega$ bits in computer memory set to all noughts, for example, or a pellet of 1 mole of native sodium in a bucket of water, so their conditional information - their thermodynamic entropy - will be very small. But the system, by the laws of large numbers, must, in any evolution, almost certainly increase its conditional entropy simply because the maximum likelihood states are the overwhelming majority of all the microstates.
This is a sketch of a proof of a weak form of the second law of thermodynamics that an isolated system's thermodynamic entropy will increase with time, whilst its unconditional entropy, $\log_2\Omega$ does not.
To read more about these ideas, please see my answer to the Physics SE question "Why are the laws of thermodynamics “supreme among the laws of Nature”?"
At the level of universes, though, I am not a cosmologist, so I don't know for sure what the general opinion is as to whether the Universe is isolated (in the thermodynamic sense) or not, whether it is infinite or finite, what its global topology is and so forth. But if the universe is truly an isolated system and if as many physicists believe it can ultimately be thought of as a gigantic evolving quantum state, then its state at any time is defined by a unitary transformation of its state at any other time. "The World does not forget its history". So the same ideas as above would apply. We just make the experimental observation that, somehow (and this somehow is quite a mystery to modern cosmology) the Universe found itself in an exquisitely low thermodynamic entropy at the big bang and, through its unitary state evolution, has been moving further and further away from that state ever since.
Some references which you might find helpful and interesting are the following.
E. T. Jaynes, "Information Theory and Statistical Mechanics", Phys. Rev. 106, number 4, pp 620-630, 1965
E. T. Jaynes, "Gibbs vs Boltzmann Entropies", Am. J. Phys. 33, number 5, pp 391-398, 1965 as well as many other of his works in this field
The Gibbs entropy is invariant one for an isolated system, the Boltzmann entropy is the one defined from the experimentally measured macrostate variables.

A: My two cents to add to the great response from wetsavanna: a short explanation would be the following. Technically, information never increases or decreases at the microscopic level. Entropy is a measure of information about how much do we know about the microscopic levels when making a macroscopic observation. But the relationship between entropy and information is the opposite of what you stated. The more entropy the less information we have (about the microscopic level from a macroscopic level observation).
Thus "apparent" information is decreasing, not increasing with an increase in entropy.


Q: A basic vanilla javascript AJAX loader I am trying to write a simple function to return data from an ajax call. Here is what I have
var mytext = "";

function load(url){
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url);
    xhr.send();
    xhr.onloadend = function(e){
        return xhr.responseText;
    }
}

var mytext = load('window.html');

console.log(mytext);

I am stuck, How do I get the returned value? I'ts a function in a function and I am lost :(

A: There are serveral ways to do that. Since you seems to be new to javascript, you can start with callback:

function load(url, callback){
    var xhr = new XMLHttpRequest();
    xhr.onloadend = function(e){
        callback(xhr);
    };
    xhr.open('GET', url);
    xhr.send();
}

load('/', function (data) {
  console.log(data);
});

In this example, callback is a function, and we pass xhr as a parameter to that function while calling.

A: My advice is to make use of the Promise and fetch APIs.
function ajax(options) {
  return new Promise(function (resolve, reject) {
    fetch(options.url, {
      method: options.method,
      headers: options.headers,
      body: options.body
    }).then(function (response) {
      response.json().then(function (json) {
        resolve(json);
      }).catch(err => reject(err));
    }).catch(err => reject(err));
  });
}

You can use it like so:
  const ajaxResponse = await ajax({url: '/some/api/call', method: 'get'});

In case you don't already know, await can only be used inside async functions. If you don't want to use async functions, do the following:
ajax({url: '/some/api/call', method: 'get'}).then(data => {
  // process data here
});

Explanation:
JavaScript is a single-threaded language. This means everything runs in a blocking manner. If your Ajax call takes 3 seconds, then JavaScript will pause for 3 seconds. Luckily, the XMLHttpRequest and fetch APIs combat this issue by using asynchronous functions, meaning code can continue running while the Ajax call is awaiting a response.
In your code, you're not getting a response from your function because the Ajax call doesn't stop the execution, meaning by the time the call has been made, there's nothing to return yet and by the time the call is finished, the function's call is long in the past too. You can tell JavaScript however to keep track of this asynchronous task through Promises. When your task is finished, the Promise's then function is called with the data from the Ajax call.
JavaScript also provides syntactic sugar to make reading asynchronous code easier. When we use an async function, what we're actually doing is creating a regular function, whose body is wrapped in a Promise.
This also means that when you want to wait for the result of a previous Promise, you can prepend await in front of the Promise reference and await the completion of the Promise.
So you may have code that looks like this:
const call = await ajax({ ... });
console.log(call);

which actually translates to the following:
ajax({ ... }).then(call => {
  console.log(call);
});


Q: How to delete extra kernel images? I have Ubuntu installed on a partition with very minimal space. Every so often, the update manager informs me that there are some updates to install.
One of those updates is the kernel itself. The new kernel is installed alongside the old and a new item appears on the Grub boot menu.
My question is... how do you get rid of the old kernel images? They're just taking up space.

A: Aha! I just figured it out.
All you have to do is use synaptic to remove them.


Q: What is the reason StandardDeviation doesn't cooperate with Quantity "Percent"? Consider the following list of numbers
y = {13, 0.2, 11.201};

Turning y into a list of Quantity's and calculating some stats works just as one would expect:
Evaluating
Through[{Mean, StandardDeviation}[Quantity[y, "km"]]]

returns

 {Quantity[8.13367, "Kilometers"], Quantity[6.92939, "Kilometers"]}

Trying to do the same exact calculations but this time using "Percent" as the underlying unit produces the following problem:
{8.13367%, 6.92939Sqrt[None]}

It seems that StndardDeviation is having trouble processing the "%" unit.
One way around this is to define the following auxiliary functions:
qf = QuantityUnit /* First;
qsd = (Through[{QuantityMagnitude /* StandardDeviation, qf}[#]] &) /* Apply[Quantity];

which essentially assist in deconstructing a Quantity, applying StandardDeviation and repackaging the result into a Quantity with appropriate units.
Through[{Mean, qsd}[Quantity[y, "Percent"]]]

{Quantity[8.13367, "Percent"], Quantity[6.92939, "Percent"]}

Is this behavior reproducible on different systems than mine?
Can anybody think of a reason why this is happening?
Are there any other ways around this problem?
Thanks!


Q: How can use Codeigniter my_model class for udate with multiple where condetion? Iam used codeigniter my_model class for update my table datas.
Actulay i need the query is
`UPDATE `pay_project` SET `awarded` = '129' WHERE `pay_id` = 1 and `status` ='y'

For this purpose am tried the codeignter my_model function update
$this->pay_project_model->update_by(array('pay_id'=>1,'status'=>'y'),$updateJob);

But the code is not working, if am trying the update() instead of update_by() at that time its showing like this
`UPDATE `pay_project` SET `awarded` = '129' WHERE 'id'=array()

Please help me to solve this ? Also am trying with update_many(), same is not working..
The model using is
https://github.com/jamierumbelow/codeigniter-base-model

A: Try this Active Records it'll let you know what you were doing along with query
function update($data = array(), $where = '') {
    $where = array('pay_id'=>1,'status'=>'y');
    $data = array('awarded' => '129');
    $this->db->where($where);
    $res = $this->db->update($this->main_table, $data);
    $rs = $this->db->affected_rows();
    return $rs;
}

A: Here is the query you need in your model function.
class my_model extends CI_Model {

    function __construct(){
        parent::__construct();
    }

    /*Model function*/
    function update_by($condition = array(),$updateJob=array())
    {
        if($condition && $updateJob)
        {
            $this->db->where($condition);
            $this->db->update('pay_project', $updateJob );
        }

    }
}

Now you can use your existing code from controller for your desired purpose.
$updateJob = ['awarded' => '129'];
$this->pay_project_model->update_by(array('pay_id'=>1,'status'=>'y'), $updateJob);

A: use this codeigniter active records for doing database operations
$data = array(
           'awarded' => '129'
        );
$where = array(
          'pay_id'=>1,
          'status'=>'y'
         );

$this->db->where($where);
$this->db->update('pay_project', $data);

For documentation refer this link
  codeigniter active records update

A: Use this
$query = $this->db->query("UPDATE pay_project SET awarded = '129' WHERE pay_id = '1' and status ='y' ");
$result = $query->result_array();
return $result;

A: If you are using Codeigniter My_model class, then you need to change your model like this to work the update_by() function
class Pay_project_model extends MY_Model {
protected $table='pay_project';
function update_by($where = array(),$data=array())
 {
        $this->db->where($where);
        $query = $this->db->update($this->table,$data);
        return $query;
  }
}

In My_model class there is not a default option to update the class by multiple where conditions, So you need to write update_by() function. Simple copy paste the function inside your class, and this will be work perfectly.


Q: How to resolve 404 Error for an AJAX call in Django I am getting a 404 Error for an AJAX call in Django
Here's my code:
jQuery Script:
$('#cluster-id').change( function(){
        $.ajax({
            url: '/ajax_demo/',
            type: 'get',
            dataType: 'json',
            complete: function( jqXHR, textStatus ){
                console.log("complete " + textStatus);
            },
            success: function( data, jqXHR, textStatus ){
                console.log("success " + data);
            },
            error: function(jqXHR, textStatus, errorThrown ){

                console.log("error: " + errorThrown );
            }
        });

I am trying to get the data( in json ) form this function:
from django.http import JsonResponse
def ajax_demo( request ):
    cluster = request.GET.get('cluster', None)
    data = {
        'name' : 'abc'
    }
return JsonResponse(data)

I have set the url correctly too:
urlpatterns = [
    url( r'^$', views.main_page_demo, name = 'main_page_demo' ),
    url( r'^demo/', views.ajax_demo, name = 'ajax_demo'),

    ]

I am new to AJAX and jQuery and i don't know what's the issue.
root url
urlpatterns =[

    url(r'^admin/', include(admin.site.urls)),
    url(r'^$', include( 'app.urls', namespace = "mainPage")),

A: You have several obvious errors here.
Firstly, you are posting to /ajax_demo/, but you don't have that as a URL; only /demo/. You did either change the URL pattern or the URL you are posting to.
Secondly, you have included the app patterns wrongly; to must not use a terminal $ with include. It should be:
url(r'^$', include( 'app.urls', namespace = "mainPage")),

Thirdly, you are not including any data with your request. You need a data key:
   $.ajax({
            url: '/demo/',
            type: 'get',
            data: {"cluster": "value"}
            ...


Q: Pointer to function instead if in c I'm making a little calculator in C with only "+, -, /, *, %" parameters, and honestly, this is working fine. But I would try to make it with pointer to function I think I will use a better syntax but I don't know where I may start and how can I do/can I use it? I would like improve myself.
Someone can explain me please?
#include <unistd.h>
#include <stdio.h>

int     ft_atoi(char *str);
void    ft_putnbr(int nb);

int check_by_zero(int a, int b, char oper)
{
    int res;

    if (oper == '/')
    {
        if (b == 0)
        {
            write(1, "Stop : division by zero\n", 24);
            res = -1;
        }
        else
            res = a / b;
    }
    if (oper == '%')
    {
        if (b == 0)
        {
            write(1, "Stop : modulo by zero\n", 22);
            res = -1;
        }
        else
            res = a % b;
    }
    return (res);
}

int do_result(int a, int b, char oper)
{
    int res;

    if (oper == '-')
        res = a - b;
    if (oper == '+')
        res = a + b;
    if (oper == '/' || oper == '%')
        res = check_by_zero(a, b, oper);
    if (oper == '*')
        res = a * b;
    return (res);
}

int main(int ac, char **av)
{
    int     value1;
    int     value2;
    int     res;
    char    c;

    if (ac != 4)
        return (0);
    value1 = ft_atoi(av[1]);
    value2 = ft_atoi(av[3]);
    c = av[2][0];
    if ((!(c == '+' || c == '-' || c == '*'
        || c == '/' || c == '%')) || av[2][1] != 0)
        res = 0;
    else
        res = do_result(value1, value2, c);
    if (res != -1)
    {
        ft_putnbr(res);
        write(1, "\n", 1);
    }
    return (0);
}

EDIT: Can't use standard function. Only mine. This is the reason why I use write instead printf

A:
make it with pointer to function

Create a function for each operator.
int hh_div(int a, int b) {
  // TBD: add some checks
  return a / b;
}

int hh_add(int a, int b) {
  // TBD: add some checks
  return a + b;
}

Then use an array of function pointers indexed by char oper.
int do_it(char oper, int a, int b) {
  static const int (*all[256])(int, int) = { //
        ['/'] = hh_div, //
        ['+'] = hh_add, //
        // etc
  };
  int (*f)(int a, int b) = all[(unsigned char) oper];
  if (f == NULL) {
    Handle_NotDefined();
  }
  return f(a, b);
}

Code could use a big if() or switch(), but with a nice function look-up table, what is a 1 or 2 k-byte table between friends?
Of course the table could be smaller with some pre-tests.
Ref: Some 2 operand operators: % ^ & * + - | \ < > /