How does this stove gas valve work?

Question: What is it called and what does it do?
Is there a way to know if gas is available?
This bottom of the pipe leads to a stove.
Comment: One part of the question is how would you know if gas is available. This is a shut-off valve and it is presumptively turned off. What appliance is this connected to?

First guess is the lower tube is the outlet. What does the lower tube lead to?
Comment: To determine if gas is available a competent gas plumber would make a presumptive determination of which way the gas was flowing, then disconnect the presumed outlet fitting at the valve, in this case disconnect the lower hose, cautiously. No gas should flow because the valve is closed. (If gas does flow continuously, then presumably the wrong choice of direction of flow was made.) The plumber would then cautiously open the valve. If gas is available, there would be a hissing sound and smell of natural gas (mercaptan odorant). Be prepared to shut the valve quickly.
Comment: Do you have access to the gas meter? Is the valve at the meter open? If not, you would have to get the gas supplier to turn on the valve at the meter.
Comment: Another way to proceed would be to identify the appliance that the outlet side of this valve goes to. Presumably this will lead to a gas cooking stove or a gas fired water heater or a furnace. Maybe the appliance has been disconnected and even removed. Which is it in your case? If it is a cooking stove, you could try to get the stove operating.Tell us what you have so we don't have to give instructions for every possibility.
Answer: These valves are simple in operation>
If the handle is inline with the pipe then it is open,
If the handle is "across" the pipe then the valve is closed.
The valve itself is a ball with a hole through it.
Comment: @JimStewart CW in North America and Europe. CCW in Australia and South America :-)
Comment: @manassehkatz I think you mean ACW, not CCW :-)
Comment: @JimStewart the picture shows a stop tab at top of valve ... it can only turn CCW
Comment: Speaking from experience: Those valves exist also in a "childproof" variant. One needs to push the handle to unlock it.
Comment: @jstola I think you are correct. Also there is a double arrow on the handle which indicates that "O" is CCW and "S" is CW.
Comment: @jstola some ball valves are designed so that the handle can be taken off and repositioned 180 deg different AND end up on the other side of a stop on the valve body. In valves designed that way the sense of rotation can be reversed from CCW "ON" to CW "ON". I don't know if this is a feature or a bug.
Comment: @jsotola Just looked at the ball valve for gas to our tankless water heater. The double ended arrow indicates CW is "S" CCW is "O". I know the valve is open and can see handle is lined up with the pipe and can see the stop so that the only way to turn ithe handle is CW. Evidently the idea is turning a screw (ordinary right handed screw) CW tightens the screw so the idea is tightening is the natural way to shut a valve. Ball valves are symmetric internally so without stops a ball valve could be switched from on to off and back to on by turning 90 deg twice in the same sense.
Comment: So for this valve do I need to turn it to clockwise or counterclockwise? @JimStewart
Comment: Just like @jsotola wrote you would turn it CCW 90 deg to open the valve.
Comment: Turn the larger end of the handle down.
Comment: But it is not a good idea to turn on the gas until you verify that there is no leak downstream of this shut-off valve.
Answer: One part of the question is how would you know if gas is available. This is a shut-off valve and it appears to be off or shut. I believe on the handle the "O" is for open and the "S" is for shut.
What appliance is this connected to? First guess is the lower tube is the outlet. Where does that line lead? Is it connected to anything?
You should not open the valve until you verify that there are no open lines downstream of this valve. Alternatively, you can disconnect the outlet fitting at the valve.
The safest way to proceed would be to gradually loosen the fitting on the outlet line which we have identified as probably the lower line. Loosen it in stages and listen for hissing and the odor of gas. This is with the valve shut as it is now.
If you get no continuous hissing and odor of gas, then loosen the fitting completely and gently separate the lower line from the valve. Now slowly open the valve and listen for hissing and odor of gas. If gas flows, let it flow for a few seconds to establish that there is a continuous flow of gas, then shut the valve. You will have the answer. You have gas.
Now reconnect the lower line and snug it tight but do not overtighten.

How does this stove gas valve work?


NTP is not working in ubuntu

Question: I installed NTP on my server and client then I changed time in client. When I run the ntpd -dq command, it shows:
Unable to bind to wild card address 0.0.0.0 , maybe another process is running

Answer: To change your client time with ntp-client , i suggest you to run this command :
Example:
ntpdate ntp.myserver.net
Or
ntpdate 126.96.36.199
you can change word "ntp.myserver.net" and "18.104.22.168" your domain and your ip_server .

NTP is not working in ubuntu


Expand Pandas columns with lists

Question: I have a dataframe with one row that looks like the following:
a   b   c   d   e
1   [2,4]   [2,7]   apple   orange

I know i how to do this with one list column, but wasn't sure how this changes with multiple list columns.  I essentially want to expand the dataframe into n rows depending how many elements in each list.  The number is always the equivalent between the columns with lists.  So the example above would become:
a   b   c   d   e
1   2   2   apple   orange
1   4   7   apple   orange

Answer: Funny how a simple problem can be difficult:
(pd.DataFrame(df.loc[0,['b','c']].to_list(), columns=['b','c'])
   .join(df.loc[df.index.repeat(len(df.loc[0,'b'])),['a','d','e']].reset_index(drop=True))
)

Comment: It's funny how that works out.  I was thinking about doing something similar to this, but I figured there'd be a pandas method similar to 'explode' that I didn't know about.  Thanks man!
Answer: An alternative way using explode to arrive at the solution:
ndf = pd.concat([df.explode('c').drop('b', axis=1), df.explode('b').drop('c', axis=1)], axis=1)

ndf.loc[:,~ndf.columns.duplicated()]

Answer: I'm not shure if this solution will work for your real dataframe. It seems to me, that this only works because of the simple example data.
import pandas as pd
import io

t = '''
a   b   c   d   e
1   [2,4,5]   [2,7,2]   apple   orange'''

# Setting up the dataframe with lists in `b` and `c`.
df = pd.read_csv(io.StringIO(t), sep='\s+', converters={'b': eval, 'c': eval})

df.apply(pd.Series.explode)

Out:
   a  b  c      d       e
0  1  2  2  apple  orange
0  1  4  7  apple  orange
0  1  5  2  apple  orange

Answer: if your lists are all the same length you can use the pandas dataframe constructor with a dictionary:
import pandas as pd

data = pd.Series([1, [2,4], [2,7], 'apple', 'orange'],
                  index=['a','b','c','d','e'])
data = pd.DataFrame(data).T
print(data, '\n\n')

output = pd.DataFrame(dict(zip(data.columns, data.loc[0])))
print(output)

   a       b       c      d       e
0  1  [2, 4]  [2, 7]  apple  orange

   a  b  c      d       e
0  1  2  2  apple  orange
1  1  4  7  apple  orange

Expand Pandas columns with lists


save a pdf filename with slash in root directory cakephp

Question: I am working with cakephp 2.5 and trying to save a pdf file into root directory named Service_Invoices .
PDF File name is :
<code>$pdf_file_name = 'ISE-00000104/17.pdf';
</code>
And the Root path :
<code>$pdf_file_path = WWW_ROOT . 'files\Service_Invoices';
</code>
The problem is the slash in the file name. How to save this file with filename contain slash.
NB. The file name is a invoice id so it can not be changed.
Comment: don't use slashes in filenames
Comment: Change the slash to something neutral, like a `-`.
Comment: presuming a linux server, you cant: https://stackoverflow.com/questions/9847288/is-it-possible-to-use-in-a-filename if the name is important then you can encode it so it can be retrived, eg with base_64, or save the name elsewhere, such as a database or textfile etc
Answer: The content of $pdf_file_name is not a filename, but a file path. The filename is 17.pdf.
Several options here:

You can remove the slash and replace with another char, if you want to keep the original file path information.
You can create the folder ISE-00000104 within your target directory and save the 17.pdf in there to have the same structure.
You can remove the path information and just save 17.pdf to $pdf_file_path.

Filenames with a slash are not possible on Windows or Unix.


Cucumber+Gherkin: Parse natural language to boolean

Question: So, we just introduced Cucumber + Gherkin to explore e2e testing in our fairly fresh Angular2 project. We decided to write the step definitions in JS. I am trying to be fairly generic in the steps definitions.
This is what I am trying to achieve:
We have
this.Then(/^I should see (.*) on the page$/, function(componentName, callback) {
    expect(element(by.id(componentName)).isPresent()).to.eventually.be.true;
    setTimeout(callback, 1000);
  });
I would like to also allow definitions in the form of:
Then I should not see Results on the page
To denote that certain elements are not supposed to be displayed. Any elegant way of doing that or even built in-tools I could use? The documentation and googling only gave me things that included true/false in the description. I have a feeling that c'n'p will make our step definitions grow super quickly and make maintenance unnecessarily hard unless we figure out this kind of thing up front.
Stop me if you think this is a stupid idea and if so please tell me why.
Answer: You could catch the keyword 'not' in your step and implement two paths in your step implementation with a condition choosing the correct one.
I would, however, not do that and instead accept two steps. That would make your code easier to read and therefore less error prone.
I would work hard on making the steps one-liners and delegate the execution to a helper class. The helper class can have two ways in, the positive case and the negative case. It may also handle things like you seem to do with time out etc.
Re-writing your code, I would try to have something like this:
this.Then(/^I should see (.*) on the page$/, function(componentName) {
    isPresent(componentName);
  });

And the negative case as
this.Then(/^I should not see (.*) on the page$/, function(componentName) {
    isNotPresent(componentName);
  });

I'm not fluent in JavaScript so this may not be the Javascript way. But I would work hard on pushing potential common details to a helper and minimize the glue code needed between Gherkin and JavaScript.
Comment: That sounds like the reasonable middle-ground. Thanks!


Characteristic polynomial of triangular blocks matrix

Question: Let A be a triangular blocks matrix (the blocks are: A1,...,Ak).
Show that CA(t)=CA1(t)*...*CAk(t).
Any help ? thanks ;)
(edit: CA and CAj are the characteristic polynomials of the blocks)
Comment: I don't get what $A$ is. Are you sure $A$ is supposed to be triangular?
Comment: If A is triangular, the proof is even simpler.  But as long as it is block diagonal the statement works.
Answer: $$C(A)\equiv \det(A - tI)$$
Start from the theorem that determinant is multiplicative
$$ \det(KJ) = \det(K) \det(K)$$
Now consider any pair of 2-square-blocks square matrices
$$ K ^{(N\times N)}=  \left( \begin{array}{cc}
k^{r\times r} & 0^{r \times s} \\  0^{s \times r} & I^{s \times s}
\end{array} \right) $$
and
$$ J ^{(N\times N)}=  \left( \begin{array}{cc}
I^{r\times r} & 0^{r \times s} \\  0^{s \times r} & j^{s \times s}
\end{array} \right) $$
It is easy to see that
$$
KJ = JK =
\left( \begin{array}{cc}
k^{r\times r} & 0^{r \times s} \\  0^{s \times r} & j^{s \times s}
\end{array} \right)
$$
By induction, it is then clear that the block diagonal matrix $A$ is product of matrices each containing one of the blocks of $A$ and 1's on the remainder of the diagonal. And $A-tI$ has that same structure
$$
A - tI = \prod_{i=1}^{k} \mbox{Block}_i (A_k - tI)
$$
and
$$
C(A) = \det(A - tI)  = \prod_{i=1}^{k} \det \left(\mbox{Block}_i (A_k - tI) \right)
$$
But the determinant of each of the $mbox{Block}_i (A_k - tI) = \det((A_k - tI)$. And $\det((A_k - tI)$ is C(A_k).
So
$$ C(A) = \prod_{i=1}^{k} C(A_k)$$


How range overflow affects the simulation and synthesis?

Question: module dut ( a,b_out,array,c);
input [2:0] a;
input [3:0] array;
input       c;
output reg  b_out;
always@( a or c or array) begin
  if(c)
    b_out = 1'b0;
  else
  b_out = array[a];
  end
endmodule

There is a possible range overflow in the above RTL, how it exactly affects the simulation and synthesis?
Answer: When a > 3 and !c then b_out will be undef in simulation because an out-of bounds access to a vector returns undef (i.e. 1'bx). See 5.2.1 in IEEE Std 1364-2005:

A part-select of any type that addresses a range of bits that are
  completely out of the address bounds of the net, reg, integer, time
  variable, or parameter or a part-select that is x or z shall yield the
  value x when read and shall have no effect on the data stored when
  written. Part-selects that are partially out of range shall, when
  read, return x for the bits that are out of range and shall, when
  written, only affect the bits that are in range.

In synthesis this don't care will be transformed into whatever the synthesis tool deems the most efficient. Very likely that means that only the bottom two bits of a are used in array[a], i.e. it is identical to array[a[1:0]]. But there is no guarantee for that whatsoever and it would be equally correct to create a circuit that for example always returns 1 or 0 when a[2] is high.


Live encode H.264 stream on Android

Question: I am writing an Android app where I plan to encode several images in to a live h.264 video stream that can be replayed on any browser. I am using the MediaCodec API for encoding and then MediaMuxer to write it to a file as per the example here http://bigflake.com/mediacodec/.
What I am stuck with is that how to tell the encoder/muxer to encode it such that it can be progressively played back. From the examples only when the encoder/muxer.stop()/encoder/muxer.release() call is made, then the video file gets the right meta headers, etc..
Thanks
Comment: you need to move the MPEG4 meta information from the end of file to the beginning see http://mithunme.wordpress.com/2009/11/04/streaming-mp4-via-http/
Comment: The `MediaMuxer` class really wants to write a .mp4 file to disk.  It's not suited to streaming.  If what you're after is live-streaming an edited video feed from your app to a host browser, you need to sort out network video streaming protocols.  But I'm not convinced I fully understand what you're after.
Answer: I guess you are considering the time at which each frame is shown.
You need to give MediaMuxer, along with the frame, the right "MediaCodec.BufferInfo," whose "presentationTimeUs" is set accordingly.
For example, there are 3 frames, each is shown for 1 second in the video:
<code>sec 0---------1---------2-----------
    frame1    frame2    frame3

int[] timestampSec = {0, 1, 2};
for (int i = 0; i < 3; i++) {
    muxer.writeSampleData(trackId,
                          frame[i],
                          timeStampSec[i] * 1000000);
}
</code>
As to initialization and ending of MediaMuxer:

addTrack: when you get index == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED when you call MediaCodec.dequeueOutputBuffer(), send the format to MediaMuxer to initialize a new track for this format(it's "vidio/avc" in this case).
mediamuxer.start()
start put frames as above
mediamuxer.stop(), release()

Live encode H.264 stream on Android


Distinction between type aliases and type lambdas

Question: This question is about a limitation of Scala's implicit resolution system that I've run into a few times when using Scalaz and that doesn't make a lot of sense to me. I've distilled the problem to a Scalaz-less version below, but I'm happy to provide more information about motivation if needed.
Suppose I have a couple of type classes that witness something about a type constructor:
import scala.language.higherKinds

trait Foo[F[_]]
trait Bar[F[_], A]

Now also suppose that if I have a Foo instance for some F, I know I also have a Foo instance for Bar[F, _]:
implicit def barFoo[F[_]: Foo] = new Foo[({type L[X] = Bar[F, X]})#L] {}

I've also got instances for List and the right side of Either:
implicit object listFoo extends Foo[List]
implicit def eitherFoo[A] = new Foo[({type L[X] = Either[A, X]})#L] {}

Now it's pretty clear that I should be able to write the following:
type BarList[X] = Bar[List, X]

implicitly[Foo[BarList]]

Or, equivalently:
implicitly[Foo[({type L[X] = Bar[List, X]})#L]]

And indeed, both work exactly as expected.
So I try the following:
type StringOr[X] = Either[String, X]
type BarStringOr[X] = Bar[StringOr, X]

And then:
scala> implicitly[Foo[BarStringOr]]
res2: Foo[BarStringOr] = $anon$1@39a6c855

Again, no surprises here. But then I try:
implicitly[Foo[({type L[X] = Bar[StringOr, X]})#L]]

And I get the following:
<console>:15: error: could not find implicit value for parameter e: Foo[[X]Bar[[X]scala.util.Either[String,X],X]]
              implicitly[Foo[({type L[X] = Bar[StringOr, X]})#L]]
                        ^

Note that I have no problem inferring the necessary Foo instance for StringOr, or calling barFoo explicitly to get the desired instance:
scala> implicitly[Foo[StringOr]]
res4: Foo[StringOr] = $anon$1@3eaac006

scala> barFoo[StringOr]
res5: Foo[[X]Bar[StringOr,X]] = $anon$1@179fbfea

I'm having trouble identifying what important distinction there could be between the List and StringOr cases that allows the type lambda version to work for the former but not the latter.
I've tried this on Scala 2.10.0-RC5 and 2.9.2. Adding covariance throughout doesn't help.
Am I missing something obvious? Can someone point me to something in the spec that would help me make sense of this, or to previous discussions of similar issues?
Comment: I'm not sure on this topic, but it seems, it has something to do with https://issues.scala-lang.org/browse/SI-2712
Comment: @andriyp: Thanks, but I'm not sure I see how that's related.
Comment: Travis also opened a ticket on this at https://issues.scala-lang.org/browse/SI-6895
Answer: OK, I'm not 100% sure, but I think we can make some progress by reducing this to the simplest possible case that fails. Implicits are not the issue here, nor are type aliases. This is enough to fail:
trait Foo[F[_]]
trait Bar[F[_], A]

def barFoo[F[_]: Foo] = new Foo[({type L[X] = Bar[F, X]})#L] {}

val res1: Foo[({type L[X] = Either[String, X]})#L] = null

val works = barFoo[({type L[X] = Either[String, X]})#L](res1)
val fails = barFoo(res1)

The issue issems to be Scala's inabality to infer the type argument for barFoo as [X]Either[java.lang.String,X]. This seems to due to (or at least related to) to scalac's refusal to infer a partially applied type constructor.
(On a related note, this is an example of one of those types that Scala consideres unacceptably complex).


Flash Builder 4.6 Interface Programming

Question: I'm having a very difficult time finding many resources available for Flash Builder 4.6 geared towards desktop application programming.
I'm trying to accomplish a simple (or at least I think simple) task.  I have an application, and in the application is a button.  When the user clicks the button, I want a new window to load, but not in the current window as a child; as a completely separate window.
I've managed to accomplish this once, but the code I was using gave a warning (from Adobe Flash Builder 4.6) that told me that it is best practice to use an "interface" as the new window is now a child of the window that opened it.  (I have since lost this code as I've been trying other things, like ModuleLoader).
Basically my question is, can someone please provide an example of how to properly implement an interface in the way that 2 separate windowedapplications can be loaded and they can communicate with each other through events?
And as a bonus, if anyone can point me in the direction of a good resource, I'd appreciate that also (book or site). :)  I have a Flex 4 book that I've read, and it has helped a lot with my understanding of the basic things, but is not geared towards AIR desktop programming (and had no mentions of interface).
Thank you for your time.
Comment: Thank you, the first example was extremely helpful and I now have it working, thanks!
Comment: Maybe this can help: http://stackoverflow.com/questions/11880104/dual-monitor-support-in-flex-application/11888089#11888089
Comment: Start Here: http://help.adobe.com/en_US/flex/using/index.html and here http://help.adobe.com/en_US/as3/dev/index.html
Comment: If you have it working; please answer your own question.  this would help people who come upon this question later.
Answer: How I solved this problem.  This article helped: Dual Monitor Support in Flex Application.
After you have created your project in Adobe Flash Builder 4.6, go to File > New > MXML Component.  Type in the details as you see fit best for your application, but under "Based on" field, put "spark.components.Window".  Click "Finish" when you are done with all the details.
In your main application, use the following code to pull up the new Window Component you just created into a separate Window.  For the purpose of this code, I will assume that your new window is located under "assets.components" and is called CompNewWindow.  Replace these details with your own.
<code><s:Button x="0" y="0" label="Button" click="_loadNewWindow(event)" />

<fx:Script>
    <![CDATA[

        import assets.components.CompNewWindow;

        private var myNewWindow:CompNewWindow;

        private function _loadNewWindow(event:MouseEvent):void
        {
            if (!myNewWindow) {
                myNewWindow = new CompNewWindow();
                myNewWindow.addEventListener(Event.CLOSE, _onNewWindowClose);
                myNewWindow.open();
            }
         }

        private function _onNewWindowClose(event:Event):void
        {
            myNewWindow.removeEventListener(Event.CLOSE, _onNewWindowClose);
            myNewWindow = null;
        }

    ]]>
</fx:Script>
</code>

Flash Builder 4.6 Interface Programming


Bootstrap columns not aligning in the same row

Question: Trying to render dynamically buttons and place 3 buttons in each row but they appear on the screen all in a separate row?

    @foreach (var sport in Model.Aggregator.SportsRepository.List().Where(x => x.ParentSportId == null))
    {

            @sport.Description

    }

Comment: Is your browser width below the threshold for Bootstrap to responsively 'snap' medium columns?
Comment: @JonUleis I don't think so Jon.
Comment: I ask because the 3 buttons appear in a row fine on this JSFiddle if the pane is > 992px (which is Bootstrap's medium threshold): https://jsfiddle.net/um9krh1y/
Comment: @JonUleis Even on the Fiddle they appear in a separate row on my screen, what would be the alternative for this in my case?
Comment: Did you make the pane 992px or wider?
Comment: @JonUleis If i am looking at the right think it is 1583px
Answer: From the Bootstrap documentation:

Containers provide a means to center your site's contents. Use .container for fixed width or .container-fluid for full width.

Rows are horizontal groups of columns that ensure your columns are lined up properly. We use the negative margin method on .row to ensure all your content is aligned properly down the left side.

Content should be placed within columns, and only columns may be immediate children of rows.

In other words, div class='row' needs to be inside div class='container' in your code.

.sports-container {
  background-color: whitesmoke;
  margin-top: 20px;
}
<link rel="stylesheet"
  href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css"
  integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M"
  crossorigin="anonymous">

Baseball

Hockey

Tennis


Java: Array of Custom Object References

Question: I am trying to build an array of custom object references. Here is some simplified code.
import java.util.*;

public class Map {

    private int[] dimension;

    private City[] cities;
    private int nCities;

    public static void main( String[] args ) {
        Map map = new Map( 5, 20, 500, 500 );
    }

    public Map( int nCities, int diameter, int w, int h ) {
        this.dimension = new int[2];

        this.dimension[0] = w;
        this.dimension[1] = h;

        this.create_cities( nCities, diameter );
    }

    private void create_cities( int nCities, int diameter ) {
        // data
        this.cities = new City[nCities];
        this.nCities = nCities;

        // locate cities
        long seed = System.currentTimeMillis();
        Random random = new Random( seed );

        int[] location = new int[2];

        for( int n = 0; n < nCities; n++ ) {
            location[0] = random.nextInt( this.dimension[0] );
            location[1] = random.nextInt( this.dimension[1] );

            this.cities[n] = new City( diameter, location );

            System.out.println( this.cities[n].toString() );
        }
        System.out.println( "\n" + Arrays.toString( this.cities ) );
    }
}

Result:
diameter: 20, location: [311, 324]
diameter: 20, location: [85, 294]
diameter: 20, location: [364, 182]
diameter: 20, location: [269, 412]
diameter: 20, location: [123, 200]

[diameter: 20, location: [123, 200], diameter: 20, location: [123, 200], diameter: 20, location: [123, 200], diameter: 20, location: [123, 200], diameter: 20, location: [123, 200]]

Can anyone unbang my head from the wall? I am storing the same reference 5 times over, correct? How do I not do that? I would like to store a reference to each unique City object.
Answer: You're storing the same location array in each city. Make a new array for each one and you should be good to go.
    for( int n = 0; n < nCities; n++ ) {
        int[] location = new int[2];
        location[0] = random.nextInt( this.dimension[0] );

Comment: Good psychic debugging. You have guessed that the location is stored in the city as an array and not as integers that are copied, right?
Comment: @JKE Actually, it is safer to copy the values of the array passed in location inside the city class. It works both ways, but if you reuse the city class and you don't know how it is implemented, this is a likely error to happen
Comment: I guessed that the `location` reference is stored as-is in the City objects, which would produce the output shown. If the array was copied in the constructor, the points stored in another structure or as plain ints, no sharing would have happened and JKE wouldn't have had a problem.
Comment: @Luis Your suggestion to copy `location` in `City`'s constructor also fixes it as Mat confirmed. I agree that this way seems like a cleaner design. Thanks all for the help!
Answer:         this.cities[n] = new City( diameter, location );

This is assigning the Reference to same 'location' object to each city, Thus in the end when you are printing all the cities, it shows the locations as latest object refernce..
Move the
       int[] location = new int[2];

inside the loop
     for( int n = 0; n < nCities; n++ ) {

or  simply
        this.cities[n] = new City( diameter, new int[](random.nextInt( this.dimension[0] ),random.nextInt( this.dimension[1] ) );

Answer: You are passing same diameter and location to the City constructor while creating City object, you need to find a way to pass different diameter and location each time you create a City object.
store the different diameter and location in an array and pass proper values while creating City Object.

Java: Array of Custom Object References


How to get all item names in getview method in side base adapter before scorlling in Android

Question: In my application I am fetching all the images and names from a MySQL server database to the Android mobile. If the emulator screen is HVGA, only five images and names are getting displayed. In logcat also only five names are getting printed. When I scroll the screen, how many names I can see on the screen only that much names are getting printed. Instead of that, all the names have to get printed before scrolling.
This my Java code:
<code>public class VegdishesListview extends BaseAdapter {
    String qrimage;
    Bitmap bmp, resizedbitmap;
    Bitmap[] bmps;
    Activity activity = null;
    private LayoutInflater inflater;

    private ImageView[] mImages;
    String[] itemimage;
    TextView[] tv;
    String itemname,price,desc;
    String[] itemnames;
    String[] prices;
    String[] descs;
    HashMap<String, String> map = new HashMap<String, String>();

    public VegdishesListview(Context context, JSONArray imageArrayJson) {
        //inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        //  imageLoader=new ImageLoader(activity);
        inflater=LayoutInflater.from(context);
        this.mImages = new ImageView[imageArrayJson.length()];
        this.bmps = new Bitmap[imageArrayJson.length()];
        this.itemnames = new String[imageArrayJson.length()];
        this.prices=new String[imageArrayJson.length()];
        this.descs=new String[imageArrayJson.length()];
        try {
            for (int i = 0; i < imageArrayJson.length(); i++) {
                JSONObject image = imageArrayJson.getJSONObject(i);
                qrimage = image.getString("itemimage");
                itemname = image.getString("itemname");
                price=image.getString("price");
                desc=image.getString("itemdesc");

                itemnames[i] = itemname;
                prices[i]=price;
                descs[i]=desc;

                byte[] qrimageBytes = Base64.decode(qrimage.getBytes());

                bmp = BitmapFactory.decodeByteArray(qrimageBytes, 0,
                                                    qrimageBytes.length);
                int width = 100;
                int height = 100;
                resizedbitmap = Bitmap.createScaledBitmap(bmp, width, height,
                                                          true);
                bmps[i] = bmp;

                mImages[i] = new ImageView(context);
                mImages[i].setImageBitmap(resizedbitmap);

                mImages[i].setScaleType(ImageView.ScaleType.FIT_START);

                // tv[i].setText(itemname);
            }
            System.out.println(map);
        }
        catch (Exception e) {
            // TODO: handle exception
        }
    }

    public int getCount() {
        return mImages.length;
    }

    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(final int position, View convertView, ViewGroup parent) {
        View vi=convertView;
        vi = inflater.inflate(R.layout.vegdisheslistview, null);

        TextView text=(TextView)vi.findViewById(R.id.vegdishestext);
        ImageView image=(ImageView)vi.findViewById(R.id.vegdishesimage);
        TextView text1=(TextView)vi.findViewById(R.id.vegdishesprice);
        TextView text2=(TextView)vi.findViewById(R.id.vegdishesdesc);
        image.setImageBitmap(bmps[position]);
        text.setText(itemnames[position]);
        text1.setText(prices[position]);
        text2.setText(descs[position]);
        System.out.println(itemnames[position]);

        return vi;
    }
</code>
When I am scrolling means how many itemnames can view that many item I can print here. How do I print all itemnames instead of scrolling?
Answer: As you are actually storing the  names as a member field of your adapter class, you could print them inside the constructor, just iterating over the array.


I am unable to fix this issue MySQL

Question: I have recently started MySQL and I got the MySQL Workbench and I am making a table.
But there is a section where it has the red cross and I do not know what is wrong with my code. I have tried changing the syntax but the error does not go away. Can someone please help me?
CREATE DATABASE form_acceptance;
CREATE TABLE form_acceptance (
    PersonID int,
    Player_Name varchar(255),
    Countries varchar(255),
    Username varchar(255),
    Level_and_rank varchar(255),
    Max_BR varchar(255)
);
INSERT INTO form_acceptance (SayByeBye_exe, SayByeBye_exe, US, '^GYMP^SayByeBye_exe', '12_Luitenant', '4.7');
SELECT PersonID, Player_Name, Countries, Username, Level_and_rank, Max_BR

This is my code so far. Except where it says INSERT INTO form_acceptance it says it is wrong and I have no idea why.
enter image description here
Thanks
Comment: You title is not reflecting the actual issue. It makes it difficult to search.
Answer: It appears that you roughly got the insert logic backwards, providing the target column names in the select, and the literal values in the insert clause.  Try reversing this order:
INSERT INTO form_acceptance (PersonID, Player_Name, Countries, Username, Level_and_rank, Max_BR)
SELECT 'SayByeBye_exe', 'SayByeBye_exe', 'US', '^GYMP^SayByeBye_exe', '12_Luitenant', '4.7';

You could also just use a VALUES clause here:
INSERT INTO form_acceptance (PersonID, Player_Name, Countries, Username, Level_and_rank, Max_BR)
VALUES
    ('SayByeBye_exe', 'SayByeBye_exe', 'US', '^GYMP^SayByeBye_exe', '12_Luitenant', '4.7');

Comment: PersonID is int column. So 'SayByeBye_exe' will throw error.
Answer: You just need to reverse your syntax -
INSERT INTO form_acceptance (PersonID, Player_Name, Countries, Username, Level_and_rank, Max_BR)
SELECT Some_integer_value, 'SayByeBye_exe', 'US', '^GYMP^SayByeBye_exe', '12_Luitenant', '4.7';

I am unable to fix this issue MySQL


Replace carousel indicators with images

Question: I have a carousel and im trying to replace the indicators with circle images, whenever i do it the image appears but the indicator doesn't disappear, i want to move the indicators and keep the image as an indicator, and i want to move the indicators to the left, how can i do that? here is my code:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

        ...

        ...

    ...

    Previous

    Next

Answer: Please try with this, If you need further assistance, comment bellow the answer.
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Document</title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

          1

           2

           2

        Previous

        Next

Comment: I don't see anything except the white square background, where the indicator image should be.  My image won't show, for some reason. I used your CSS code and this `` Any idea why it's not showing?
Comment: Is it working fine when you are using http://placehold.it/70x70 instead of "assets/1.png"?
Answer: Change carousel indicators position from bottom to left using ".carousel-indicators" class
add this style at bottom of your css file.
 .carousel-indicators {
           text-align: left;
        left: inherit;
        width: 15px;
        top: 47%;
        position: absolute;
        left: 2%;
        margin-left: 0;
    }

Replace carousel indicators with images


mongodb TypeError: client.db.collection is not a function

Question: when I use "mongodb": "^3.0.5",
    const cn = require('./connect');

    function showItems(req, callback) {
      cn.MongoClient.connect(cn.url, (err, database)=> {

        const collection = database.db.collection('items');

        collection.find({}).toArray((err, result)=> {

          callback(result);
        });

        database.close();
      })
    }

    module.exports = showItems;

I got,

/node_modules/mongodb/lib/mongo_client.js:433
throw err
^
TypeError: database.db.collection is not a function

But,when I use "mongodb": "^2.2.33" , it worked.
    const cn = require('./connect');

    function showItems(req, callback) {
      cn.MongoClient.connect(cn.url, (err, db)=> {

        const collection = db.collection('items');

        collection.find({}).toArray((err, result)=> {

          callback(result);
        });

        db.close();
      })
    }

    module.exports = showItems;

connect.js
    const url = "mongodb://127.0.0.1:27017/databasename";
    const MongoClient = require('mongodb').MongoClient;

    module.exports = {url, MongoClient};

Use "mongodb": "^3.0.5" , How to solve this problem ?
Comment: don't know how this works in earlier version, Here is a guide that may help using later/latest version https://github.com/usman154/movieApp
Comment: What does your `./connect` do ? If you want to use `cn.MongoClient.connect` you shoud replace `const cn = require('./connect');` by `const cn = require('mongodb');`
Answer: I think this is permission error.so we need to get the database first then try to access the collections. will solve the problem.
const MongoClient = require('mongodb').MongoClient;
const cn = require('./connect');

MongoClient.connect(cn.url, (err, database) => {
  if (err) {
    console.log(err);
    throw err;
  } else {
    const myDB = database.db('myDatabaseName')
    const collection = myDB.collection('items');
    collection.find({}).toArray((err, result) => {
      callback(result);
    });
    db.close();
  }
}

Comment: still this issue
Comment: then uninstall mongo from npm js & reinstall npm package will solve your problem.
Answer: Try with :
client.collection()

instead.
The connect method return the database object.
Comment: TypeError: client.collection is not a function
Comment: Did you check the err value ?


Painted walls showing darker when dry where painted with brush, than with roller

Question: I've recently painted a room using primarily a roller, and for the edges (corners, skirting boards, ceilings), I've used a brush.
Where the paint was applied with a brush, it is considerably darker than where it was panted with a roller.

As you can see, there are dark "areas" around the wall join, and the joint with the ceiling. I'm shining a very bright torch as it demonstrates the problem better, hence the odd looking shadow at the bottom of the image.
I've asked a handful of very experienced people I know who have painted many rooms (all DIYers, but still), and they all concluded that the paint wasn't applied thick enough on the wall itself, and that actually the problem is not the joints, but the main area of the wall which was applied with a roller. Upon hearing this, I was slightly shocked since the dark areas actually look like they are not well adhered, but I played along and re-applied the whole room using a roller with a third, then forth coat, and the same problem persisted.
At that point, I decided I was right, and that it is the areas around the corners. I've now been out and purchased a much smaller roller, which has allowed me to cover the corner areas with great success, and now they have been painted with that the problem has disappeared entirely, except for the very thin slithers around the edges where I have a 5-10mm gap which I daren't touch with a roller, even if I mask, since I'm going to make a really big mess, the roller won't roll properly, it will grind on the ceiling (even masked) and leave streaks... It's just not a good move, I can feel it going horribly wrong and being very frustrating already.
The question I'd like to ask is how can I achieve the same finish using a brush as I did using a roller. I would imagine the problem is something to do with the pattern a roller leaves reflecting light in a certain way, since that would fall in line with my experiments so far. Naturally I could just roller them very carefully and re-paint the ceiling and skirting, but that defeats the object. I want them looking good, and I've done this before without problems.
Can somebody explain the physical problem, and possibly suggest a solution to it? I'm 5 tins of paint deep at this point, and it should've been a 2 tin job at most if I hadn't been misguided so badly.
Comment: Is it 100% dry, perhaps the thicker coat of the brushed paint is simply taking longer to dry. wait 24 hours and reinspect.
Comment: It's had about 24 hours to dry in the picture, the current coat has upwards of 48 hours drying, and it's still dark in the corner strips that I couldn't reach...
Comment: Was the previous color darker or lighter?
Comment: Very similar, I'd say marginally lighter.
Answer:
how can I achieve the same finish using a brush as I did using a roller

In my experience, you can't. I usually find that brushed paint doesn't cover as well as paint applied using a roller. I find it helpful to do the corners first, going slowly. Apply extra coats as necessary. Then use a roller for the main part of the wall and paint as close into the corner as possible. A damp cloth (if water-based emulsion/latex) and a paint-guard can help.
I don't know about you, but I find I am much more fussy about these things when I am doing the work, but after a week I never think about or notice small defects any more.
Comment: I do my edging using a "twitchy dab" technique leaving a rather heavy application of paint. I then roll over as much of it as possible to blend texture and pick up excess. Doing so works well even for deep color changes.
Answer: I use an edging tool that rolls along the wall leaving roughly a 5 inch band at the top of the wall and around trim or whatever you are edging. Its super fast and if you tape everything you don't get bleeding or accidental paint where you don't want it. When you go back and roll the walls it does not leave a different shade where the edging was done.
Answer: Glossy paint shows differences much more than satin or less glossy paints.  When painting along the ceiling and corners it is important to do small sections at a time. If the brushed paint dries before you overlap it with a roller you will see the differences much more. Paint about 3 feet (1 meter) along the top with a brush and then use a roller to paint from the unpainted area of the wall in towards the wet brushed area. Do not put the wet roller on the wet area and go into the unpainted area.  Once you are done that section of the wall paint the next small section along the top with the brush and continue as before.  The key is not to let the paint dry too much before going into it with the roller.
Answer: Use flotrol additive to your paint so it thins out and lays better and stay wet longer with a brush.


How can we represent the word "Action" with an Icon

Question: I personally think that "Action" itself represents all other actions. Since it's so vague, there can't be a representation.
But this is needed, to be used in a tooling application UI. Please help with a design or a suggestion.
Comment: Could you give a little more of context?
Comment: Icon requests are not normally allowed here so this question might be put on hold (see the tour under Help). Enter "Actions" into https://www.iconfinder.com and you will see a few which might meet your needs.
Comment: Borderline. The question of whether or not it can/should be represented by an icon is on-topic, although we'd need more context in order to have that discussion. The question of what icon should be used, if any, would be off-topic.
Answer: first, can you describe what this icon does in a sentence?
can you describe what will happen when you click it?
can you give additional meanings to this Icon?
sometimes it's easier to define a word in an icon by explaining it to yourself(that's also true for copywriting). As you said it's vague and can have many meanings, so try to find your aim. Also, you can search icon sites like https://www.iconfinder.com/, search for action, and find other descriptive wards for similar icons, this technic might get you closer to your goal.


Proving $n\not\in n$ for $n\in\mathbb N$ without regularity

Question: Is there a way to prove in ZF theory without regularity axiom $\forall n\in\mathbb N$, $n\not\in n$? At this point, I haven't proved yet that $\mathbb N$ is a well-ordered set, so a proof of the well-order shall not use $\forall n\in\mathbb N, n\not\in n$.
I tried induction, but I struggle with the recursive step as I only found that $n\not\in n\Leftrightarrow n\neq n^+$.
Comment: What is your definition of $\mathbb{N}$?  The intersection of all sets that contain $\emptyset$ and are closed under $x\mapsto x\cup\{x\}$?
Comment: @EricWofsey That's it.
Answer: First you can prove that the relation $\in$ is transitive on $\mathbb{N}$.  That is, if $x,y,z\in\mathbb{N}$ satisfy $x\in y$ and $y\in z$, then $x\in z$.  The proof of this is quite straightforward by induction on $z$.  (For the induction step, if $x\in y$ and $y\in z^+$ then either $y\in z$ so $x\in z\subseteq z^+$ by the induction hypothesis or $y=z$ so $x\in z\subseteq z^+$.)
Now let us prove that $n\not\in n$ for all $n\in\mathbb{N}$ by induction.  The base case $n=\emptyset$ is trivial.  In the induction step, suppose we know $n\not\in n$ and we wish to show $n^+\not\in n^+$.  Well, if $n^+\in n^+=n\cup\{n\}$ then either $n^+\in n$ or $n^+=n$.  In the first case, we have both $n\in n^+$ and $n^+\in n$ so by transitivity $n\in n$, contradicting the induction hypothesis.  In the second case, we have $n\in n^+= n$, again contradicting the induction hypothesis.
Comment: "Induction" is iff "well ordered"
Comment: @markvs You don't need well-order to prove induction, what's your point?
Comment: This proof is so clear, I can't believe how hard it was to find it online or by myself. Trying to prove the apparently obvious things, I understand now why logicians were deemed crazy.
Comment: @Maxence1402: Induction and well order are equivalent. If you use one, you can use another.
Comment: @markvs This has yet to be proved here.
Comment: @markvs: Well-ordering is trivially equivalent to *strong* induction.  In this context we only have weak induction (which is basically immediate from the definition of $\mathbb{N}$ used here) and have not yet proved strong induction.
Comment: OK, since the OP is ha[[y with it, I am not going to argue.
Answer: We will demonstrate that $\in$ is well-founded on $\mathbb{N}$.
Suppose we have some $W$. Suppose that for all $k \in \mathbb{N}$, if (for all $j \in \mathbb{N}$, if $j \in k$ then $j \in W$), then $k \in W$. I claim that $\mathbb{N} \subseteq W$.
To prove this, we will show that for all $n \in \mathbb{N}$, $n \subseteq W$. We do this by induction on $n$.
In the base case of $n = \emptyset$, the claim that $n \subseteq W$ is immediate.
For the inductive step, suppose that $k \subseteq W$. We wish to show that $k \cup \{k\} \subseteq W$. To do so, it suffices to show that $k \in W$, since we already know that $k \subseteq W$ by the inductive hypothesis. Now consider some arbitrary $j \in \mathbb{N}$ such that $j \in k$. Then $j \in k \subseteq W$, so $j \in W$. Therefore, we see that $k \in W$ as claimed. The induction is complete.
In particular, then, given some $n \in \mathbb{N}$, we have $n \in n \cup \{n\} \subseteq W$, so $n \in W$. This completes the proof that $\in$ is well-founded on $\mathbb{N}$. $\square$
Now suppose that $R$ is well-founded on set $S$. Suppose we had some $s \in S$ such That $s R s$. Then define $S' = S \setminus \{s\}$.
Now consider some arbitrary $w \in S$. Suppose that for all $w' \in S$, if $w' R w$ then $w' \in S'$. Now suppose $w \in \{s\}$; that is, suppose $w = s$. Then $w \in w$, so in particular, $w \in S'$. But then $w \notin \{s\}$; contradiction. Therefore, $w \notin \{s\}$. Thus, $w \in S'$.
Therefore, by well-foundedness, $s \in S \subseteq S'$. Then $s \in S'$. Contradiction. Therefore, we must in fact have had $\neg (s R s)$. $\square$
Combining these two facts completes the proof.


Automount of external hard disk

Question: I have an Intenso 6002560 1TB Memory Station - an external hard disk. This hard disk gets connected via Y-USB cable. When I connect both USB-ends to my Notebook, it gets recognized by my Ubuntu 10.04.4 LTS system:
moose@pc07:~$ lsusb
[...]
Bus 002 Device 005: ID 13fd:1840 Initio Corporation
[...]

and
Disk /dev/sda: 320.1 GB, 320072933376 bytes
255 heads, 63 sectors/track, 38913 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00065e10

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1   *           1       37810   303704064   83  Linux
/dev/sda2           37810       38914     8864769    5  Extended
/dev/sda5           37810       38914     8864768   82  Linux swap / Solaris

Disk /dev/sdc: 1000.2 GB, 1000204886016 bytes
255 heads, 63 sectors/track, 121601 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x0d6ea32a

   Device Boot      Start         End      Blocks   Id  System
/dev/sdc1               1      121601   976759008+   c  W95 FAT32 (LBA)

But it did not get mounted:
moose@pc07:/dev$ mount -l
/dev/sda1 on / type ext4 (rw,errors=remount-ro,user_xattr)
proc on /proc type proc (rw,noexec,nosuid,nodev)
none on /sys type sysfs (rw,noexec,nosuid,nodev)
none on /sys/fs/fuse/connections type fusectl (rw)
none on /sys/kernel/debug type debugfs (rw)
none on /sys/kernel/security type securityfs (rw)
none on /dev type devtmpfs (rw,mode=0755)
none on /dev/pts type devpts (rw,noexec,nosuid,gid=5,mode=0620)
none on /dev/shm type tmpfs (rw,nosuid,nodev)
none on /var/run type tmpfs (rw,nosuid,mode=0755)
none on /var/lock type tmpfs (rw,noexec,nosuid,nodev)
none on /lib/init/rw type tmpfs (rw,nosuid,mode=0755)
binfmt_misc on /proc/sys/fs/binfmt_misc type binfmt_misc (rw,noexec,nosuid,nodev)
gvfs-fuse-daemon on /home/moose/.gvfs type fuse.gvfs-fuse-daemon (rw,nosuid,nodev,user=moose)

However, I could mount it manually with
mount -t vfat /dev/sdc1 /mnt/sdc1

as you can see here:
moose@pc07:~$ mount -l
/dev/sda1 on / type ext4 (rw,errors=remount-ro,user_xattr)
proc on /proc type proc (rw,noexec,nosuid,nodev)
none on /sys type sysfs (rw,noexec,nosuid,nodev)
none on /sys/fs/fuse/connections type fusectl (rw)
none on /sys/kernel/debug type debugfs (rw)
none on /sys/kernel/security type securityfs (rw)
none on /dev type devtmpfs (rw,mode=0755)
none on /dev/pts type devpts (rw,noexec,nosuid,gid=5,mode=0620)
none on /dev/shm type tmpfs (rw,nosuid,nodev)
none on /var/run type tmpfs (rw,nosuid,mode=0755)
none on /var/lock type tmpfs (rw,noexec,nosuid,nodev)
none on /lib/init/rw type tmpfs (rw,nosuid,mode=0755)
binfmt_misc on /proc/sys/fs/binfmt_misc type binfmt_misc (rw,noexec,nosuid,nodev)
gvfs-fuse-daemon on /home/moose/.gvfs type fuse.gvfs-fuse-daemon (rw,nosuid,nodev,user=moose)
/dev/sdc1 on /mnt/sdc1 type vfat (rw)

edit: Another command:
moose@pc07:~$ sudo blkid -o list
device                     fs_type    label       mount point                    UUID
----------------------------------------------------------------------------------------------------------------------
/dev/sda1                  ext4                   /                              45eb611b-517e-425b-8057-0391726cccd5
/dev/sda5                  swap                   <swap>                         e9dc42f3-594c-4b62-874a-305eda5eed41
moose@pc07:~$ blkid -o list
device                     fs_type    label       mount point                    UUID
----------------------------------------------------------------------------------------------------------------------
/dev/sda1                  ext4                   /                              45eb611b-517e-425b-8057-0391726cccd5
/dev/sda5                  swap                   <swap>                         e9dc42f3-594c-4b62-874a-305eda5eed41
/dev/sdc1                                         /mnt/sdc1

edit: another command:
moose@pc07:~$ ls -l /dev/disk/by-uuid/
total 0
lrwxrwxrwx 1 root root 10 2012-09-30 09:31 45eb611b-517e-425b-8057-0391726cccd5 -> ../../sda1
lrwxrwxrwx 1 root root 10 2012-09-30 09:31 e9dc42f3-594c-4b62-874a-305eda5eed41 -> ../../sda5

Here is a link to a Launchpad question about this problem.
But I would like it to mount automatically. What do I have to do?
Comment: hi, this is strange, the result you show is like it was not actually mounted. If you try ls -l /dev/disk/by-uuid/ so you list all in an other way, what is the output?
Comment: @user81022: it outputs only the two partitions of my internal hdd, see edited post.
Comment: I think since the drive is fat32, you should mount it as sdb type (not sdc). So, first sudo umount /dev/sdc1 and then re-mount it (/dev/sdb1). I wish I could help more.
Comment: `/dev/sdb1` does not exist (`mount: special device /dev/sdb1 does not exist
`). If I try to mount `/dev/sdb` it says `mount: no medium found on /dev/sdb`. By the way, `chkdisk` on a windows machine did not reveal any errors. It worked on Windows out of the box.
Answer: It's an old question but I figured this might still help someone.
I've had the same problem with this hdd. The source turned out to be the initial format of the partition. Reformatting as NTFS using the Disks (gnome-disks) tool made it behave like any other usb hdd.
Comment: This did the trick! Thank you so much! Do you know if there is a MATE tool with which this can be done?
Comment: Awesome! Not sure what you mean by "MATE tool" – in any case, if gnome-disks isn't available, mkfs.ntfs should also do the trick on most systems.
Answer: Here you have a good guide on how to mounting drives.
https://help.ubuntu.com/community/AutomaticallyMountPartitions
You should add your drive to the /etc/fstab file which controls the mounted devices, with parameters such as

the mounting drive,
the mounting point
used filesystem
and several other options

good luck!
EDIT: If you modify fstab manually instead of using some interface, be careful with the lines you change. Do a backup of the file first or you could make your system to not boot properly.
Answer: Since it is mounted, run sudo blkid so you see the UUID of the volume.
Then, in /etc/fstab, add:
UUID=xxx /media/xxx vfat 0 0
Comment: it seems not to have a UUID (see my edit). What do I do now? (and why isn't the device displayed when I run `blkid` with `sudo`?)

Automount of external hard disk


Adding customizable Text to a Magento Page

Question: I've been tasked with trying to add a message to the Product Compare Page which will appear if the customer has, by some stroke of stupidity, been able to access the page when there are no products to compare
now i understand there a  already in there however it seems like it doesn't work if you open a new window and type in the URL (the equivalent to bookmarking the page, how i figure is that if i put this message above the  line, if the window doesn't close the customer will get the message.
Now that part is easy enough, the hard part is the second part to my task and that's allowing this text to be changeable though the blackened much like how you can change the Logo Image Alt in System > Configuration > Design > Header.
we already have some new section in System > Configuration thanks to some custom modules however i don't want to have to create an entire module just so a department we can't trust to edited the page and not stuff it up in the process can change one line of text
So is there a way to add customizable Text to a Magento Page
Answer: You could change the javascript to window.location = '/sorry-page'; or something like that and creat "sorry-page` as a CMS page. Otherwise you will need a custom module.
Comment: think i'll do the `window.location` thing since it does seem very wasteful on resources to make a module just for a line of text


Angular - How to Subscribe Data from Component to Component

Question: I am trying to subscribe a data from a component.
Somehow it's not working now, hope anyone can find out why...
app.component.html
<app-sample1></app-sample1>

<app-sample2></app-sample2>

sample1.component.html

Sample1 !

    Subsribed Title from Sample 2:

 {{titleFromSample2}}

sample2.component.html

Sample2 !

    <input type="text" #title (input)="change(title.value)">

sample.service.ts / sample1.component.ts / sample2.component.ts

When text value inserted in Sample2 Input box,
'change' method in sample2.componet.ts implements fine.
but titleFromSample2 values of sample1.component.ts and sample1.component.html are not changing.
I can't find what wrong is....
Comment: Have you had a chance to look at the guide on component interaction: https://angular.io/guide/component-interaction ? It has some recipes for different communication strategies and would be a great place to start. Also you haven't shown how titleFromSample2 is set or provided to component 1.
Comment: well.. I checked the link and Angular official documents, but Cannot find a case that matches as mine...
Answer: That's because you are returning an Observable from getTitle which is unicast by nature. What that would mean is, it won't react to changes in the value of the title property in the SampleService.
To make it multicast, you'll have to use a Subject or a BehaviorSubject instead.
Something like this:
import { Injectable } from '@angular/core';
import { Observable, BehaviorSubject } from 'rxjs';

@Injectable()
export class SampleService {

  private title: BehaviorSubject<string> = new BehaviorSubject<string>(null);

  constructor() { }

  setTitle(value: string) {
    this.title.next(value);
  }

  getTitle(): Observable<string> {
    return this.title.asObservable();
  }

}

Also since this is going to emit multiple values over time and it's not really recommended to subscribe to Observables when they are emitting multiple values over time, you should be using the async pipe in the template instead.
So your Component would look like this:
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { SampleService } from '../sample.service';

@Component({
  selector: 'app-sample1',
  templateUrl: './sample1.component.html',
  styleUrls: ['./sample1.component.css']
})
export class Sample1Component implements OnInit {

  titleFromSample2$: Observable<string>;

  constructor(private sampleService: SampleService) { }

  ngOnInit() {
    this.titleFromSample2$ = this.sampleService.getTitle();
  }

}

And then in the template:

Sample1 !

    Subsribed Title from Sample 2:

 {{titleFromSample2$ | async}}

Here's a Working Demo for your ref.
Comment: Thank you!! All you explained are very clear and understandable. Code works like charm :)
Answer: The problem is that the SampleService stores the title value but it does't emit new values. Change titleto title = new BehaviorSubject('');
Then in setTitle:
setTitle(value: string) {
  this.title.next(value);
}

That should do it.


Annihilators of a module.

Question: Let $R$ be a ring, and $M$ a (left say) $R$ module. For subgroups $M_i$ in $M$, I have been able to prove
$$\left(\sum_{i\in I}M_{i}\right)^{0}=\bigcap_{i\in I}M_{i}^{0}$$
$$\sum_{i\in I}M_{i}^{0}\subset\left(\bigcap_{i\in I}M_{i}\right)^{0}$$
Where $N^0=\left\{n\in N\vert rn=0 \textrm{ for all }r\in R\right\}$ for a subset $N$ of $M$.
Have I got these right, and is it true that the bottom one is just an inclusion, as opposed to an equality, in general? Does this change if the $M_i$ are submodules?
Answer: The top one is correct and the bottom one is just an inclusion.
Take two faithful modules $A$ and $B$ (faithful means they have zero annihilator.). Then form $M=A\times B$ and consider $A$ and $B$ as submodules of $M$.
On one hand, $A\cap B=\{0\}$, so it's annihilator is $R$.
On the other hand, the sum of their annihilators is $\{0\}+\{0\}=\{0\}$.
Comment: Awesome! Thanks

Annihilators of a module.


Can chipboard shelves be varnished?

Question: Note: including a lot of details to avoid XY problem.
Background
I have been dealing with a minor pest (psocids, in case you're wondering, but I don't want the conversation to become about that), mainly in a kitchen cupboard and the surrounding area. I've already taken a few appropriate steps, and the next step is to try to close various gaps that the bugs use to go through, such as the ones in the picture below at the back of the cupboard (I think they've nested somewhere behind there). I will be doing that with silicone sealant.

Problem
These bugs crawled everywhere, including the holes in the chipboard of the cupboard, which they seem to like. One such place where the chipboard is exposed, is the side of the shelves inside the cupboard.

I want to seal these sides to stop bugs from hiding in there and kill any bugs or eggs that are possibly still alive inside. I don't care much about appearance since these sides are out of sight, but a clear or white layer would be better.
I tried spreading a thin layer of silicone on one shelf, but this makes the shelf a bit "sticky" on the sides of the cupboard. This is not a huge problem since the shelves don't move regularly, but the silicone is coming off easily due to this "friction".

I thought to use some varnish instead, but then I saw a guy on Youtube (https://www.youtube.com/watch?v=FV-bLLVrakM) claiming that if I put plain varnish, I risk ruining the shelf by causing it to swell. He suggests "semi-transparent" (i.e., one that includes some paint), which I could not find on Screwfix or other places (UK). His interchangeable use of "varnish" and "stain" does not help either.
So, is it true that I should not use a varnish directly on the chipboard? If so, could I use a coat of paint directly and then varnish on top (since I can't find a mixed product)?
Comment: The problem with chip board is moisture - moisture it swells. You might try a resin based product to seal it. For example and acrylic or an epoxy compound. Acrylic is used for remodeling old counter tops and perhaps that material might help you the best, as it will not be so much absorbed by the chip board but rather seal it and form a barrier.
Comment: @Ken, I thought normal varnish was [based on a type of resin](https://en.wikipedia.org/wiki/Varnish).
Comment: The problem is that kind of resin and the liquidity of the varnish as there are other components - thinners and solvents - so when thinking about liquidity and how easily it is to be absorbed by the chipboard - like water. This is the real issue - what will the chip board most likely NOT absorb. A Plastic resin or acrylic will be too thick to be readily absorbed by the chip board. You could check out Rust Oleums Water Proofing Sealer (acrylic) , Flex Seal or even wood glue. (Keep in mind some bugs are attracted to certain glues..)
Answer: By Googling for "chipboard sealant" I found a UK vendor of "work top edge sealer" that seems to be designed for that sort of job.

Seals & Waterproofs Sawn Or Drilled Edges, Joints, Sink Cut Outs etc.
Excellent sealing and waterproofing properties.
Ideal for use on MDF, Chipboard, Timber etc.
Prevents water ingress into sawn edges.
Easy to use and fast drying.
Comment: This is similar to what I used when we had some rentals that had composite cabinets to prevent dampness from swelling in both the kitchen and bathroom the stuff was solvent based and it held up for many years and passed inspection when I sold them (a duplex).
Answer: I've used common water-based polyurethane on particle board and fiberboard with no ill effects. If you allow it to dry in a timely manner, you'll see virtually no swelling. If you want to be extra cautious, use oil based polyurethane. It won't absorb into the particle board as much.
Comment: I was always afraid to use water based ,glad to know it works also.
Answer: Compiling information from Ken, RedGrittyBrick, isherwood and my own experience to form proper answer:
It's possible to varnish chipboard, but a suitable varnish must be used. Suitability will depend on how difficult it is for its components to be absorbed by the chipboard and cause swelling: oil-based would probably be safer than water-based.
The safest option would probably be to look for a varnish that specifically says it's suitable for chipboard.
Comment: I ended up using Ronseal polyurethane gloss varnish that says it's suitable for chipboard. So far, so good (I'll update this if something happens).

Can chipboard shelves be varnished?


Cannot get navgrid to show on grid

Question: So, I am trying to use jqGrid and cannot seem to get the navgrid to display.  I have searched and tried many things, none of which have worked.  I am not sure what is going on.  Any help would be appreciated.  Here is my code:

        <title>User List</title>

        <meta charset=UTF-8" />

            <link rel="stylesheet" type="text/css" media="screen" href="../../jqgrid/js/themes/lightness/jquery-ui.custom.css"></link>
            <link rel="stylesheet" type="text/css" media="screen" href="../../jqgrid/css/ui.jqgrid.css"></link>
            <link rel="stylesheet" type="text/css" media="screen" href="../shared/base.css"  />

Thanks for any help.
Answer: Your code calls navGrid out of the block $(function () {...});, which is the origin of your problem. As the result you try to create navigator bar before the grid is created.
Th solve the problem you need just move the call of navGrid one line before (inside of $(function () {...});).
You should consider to use jsonReader: { id: "rec_id" } and to remove unneeded hidden column rec_id. You don't wrote which version of jqGrid you use.
I would recommend you to move the script inside of . Alternatively you can move it after

 and remove $(function () {...}); block.

Cannot get navgrid to show on grid


Negamax not working beyond depth 1

Question: I am making a chess engine in C++ and with this algorithm, I get expected play with max depth set to 1. Beyond that however, it ignores pieces that are in danger and seems to even willingly put itself in danger.
Here is my code:
int negamax(int depth, int alpha, int beta)
{
    int max = -INFINITY;

    MoveList legalMoves;
    MoveGeneration::generateCaptureMoves(&legalMoves);
    MoveGeneration::generateQuietMoves(&legalMoves);

    // No legal moves
    if(legalMoves.count == 0)
    {
        if(Position::isCheck())
        {
            // Checkmate
            if(Position::activeColor == WHITE)
                return VAL_VICTORY;
            else
                return -VAL_VICTORY;
        }
        else
        {
            // Stalemate
            return 0;
        }
    }

    // Go through legal moves
    for(int i = 0; i < legalMoves.count; i++)
    {
        // Get move score
        Position::doMove(legalMoves[i]);

        int score;
        if(depth == 0)
            score = quiescence(MAX_QUIESCENCE_DEPTH, alpha, beta);
        else
            score = -negamax(depth - 1, alpha, beta);

        Position::undoMove();

        // Pruning
        if(Position::activeColor == WHITE && score > beta) break;
        if(Position::activeColor == BLACK && score < alpha) break;

        if(Position::activeColor == WHITE && score > alpha) alpha = score;
        if(Position::activeColor == BLACK && score < beta) beta = score;

        // Best so far?
        if(score > max)
        {
            max = score;

            if(depth == MAX_DEPTH)
                bestMove = legalMoves[i];
        }
    }
    return max;
}

Answer: Try:
score = -negamax(depth - 1, -beta, -alpha);

Negamax not working beyond depth 1


Fatal error: Class 'MongoDB\Driver\Manager' not found in /srv/www/api/releases/...vendor/mongodb/mongodb/src/Client.php

Question: I am trying to configure MongoDB on the AWS server, but when I try to make an API call, I get the following error:
Fatal error: Class 'MongoDB\Driver\Manager' not found in /srv/www/api/releases/20160912135146/vendor/mongodb/mongodb/src/Client.php on line 56

I have done the following:

Install mongodb, following the instructions here -> install mongodb community edition on ubuntu
installed the php mongodb driver using pecl install mongodb
added extension=mongodb.so to php.ini at etc/php5/cli/php.ini
Started the mongodb service
on the server, I can enter the mongo console with $ mongo

What am I missing here, Please?
PS: the API is developed using Phalcon
Answer: I finally found a solution to this. Apparently, the apache server uses a special php.ini file, different from etc/php5/cli/php.ini. This file is located in etc/php5/apache2/php.ini. After installing the mongodb driver using pecl install mongodb, your extension should go in etc/php5/apache2/php.ini i.e add extension = mongodb at the end of etc/php5/apache2/php.ini. Good luck
Comment: The `php.ini` file in the `cli` directory is for when PHP needs to be ran through the `command-line-interface`. Following that logic; the `php.ini` file in the `apache` folder is for PHP ran through your web service, Apache.


make linux directory writable using bash command through java code

Question: I have a directory /webroot in my linux server. Which permission set is 771, that means 1 for others. But I want to make it 773 through java code which like is :
Process p1 = Runtime.getRuntime().exec("chmod 773 /webroot");

But it can not change the permission.
I also capture the error stream which is like as :
chmod: changing permissions of `/webroot/': Operation not permitted

I saw a nearly related post yesterday, but i could not find the appropriate answer. At this time, what can I do now?
Please any help.
Comment: Look into gaining OS permissions, I think it might help
Comment: If you dont mind, can you please let me know more details? I am totally new in linux server.
Answer: I think the error is pretty clear here.  What user is your Java code running as?  It most likely doesn't have permissions to run chmod on that directory.
Do a ls -l on that directory to see who it is owned by.  Make sure that your Java code is running at that same user.
Comment: All permission are as follows : `drwxrwx--x 9 root root 4096 Dec  7 09:47 webroot `, But how I can run java code using root user?
Comment: I wouldn't recommend it.  You may be able to use sudo.  Otherwise, maybe this is an initial setup that you need to complete outside of Java.
Comment: Hey I used `Process p1 = Runtime.getRuntime().exec("sudo chmod 773 /webroot");` but it cant change directory permission and captured error stream is as follows: `sudo: sorry, you must have a tty to run sudo `
Comment: @Pritom its strange what you're trying to do - I'd suggest sticking with ziesemer's suggestions.. but if you really want to hammer away you'll need to edit the sudoers file and include a !requiretty for your user
Comment: I am using tomcat6 and username is 'tomcat', now what could I add to my `sudoers` file???


Scio saveAsTypedBigQuery write to a partition for SCollection of Typed Big Query case class

Question: I'm trying to write a SCollection to a partition in Big Query using:
import java.time.LocalDate
import java.time.format.DateTimeFormatter
val date = LocateDate.parse("2017-06-21")
val col = sCollection.typedBigQuery[Blah](query)

col.saveAsTypedBigQuery(
      tableSpec = "test.test$" + date.format(DateTimeFormatter.ISO_LOCAL_DATE),
      writeDisposition = WriteDisposition.WRITE_EMPTY,
      createDisposition = CreateDisposition.CREATE_IF_NEEDED)

The error I get is
Table IDs must be alphanumeric (plus underscores) and must be at most 1024 characters long. Also, Table decorators cannot be used."
How can I write to a partition? I don't see any options to specify partitions via either saveAsTypedBigQuery method so I was trying the Legacy SQL table decorators.
Answer: See: BigqueryIO Unable to Write to Date-Partitioned Table. You need to manually create the table. BQ IO cannot create a table and partition it.
Additionally, the no table decorators was a complete ruse. It's the alphanumeric part I was missing.
col.saveAsTypedBigQuery(
      tableSpec = "test.test$" + date.format(DateTimeFormatter.BASIC_ISO_DATE),
      writeDisposition = WriteDisposition.WRITE_APPEND,
      createDisposition = CreateDisposition.CREATE_NEVER)


Is there any algorithm which check right NPI (National Provider Identification) number?

Question: Basically I'm developing application using asp.net and I want to write Custom validator which will check right NPI number.
Answer: Wikipedia says:

A 10-digit NPI Number may be validated using the Luhn algorithm by
  prefixing "80840" to the 10-digit number.

Obviously that just validates the check digit. To find whether a number is actually assigned, I think you need a list. There's an online lookup, for example. Even without that, there may be additional checks you can do if you know anything about how HIPAA hands the numbers out.
Comment: I think so. There might be any webservice to verify NPI but i don't want to go that much of depth. Anyways thanks for your suggestion :)
Answer: In case someone has found this post but is looking for this in Java, here is a java program that does this:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class NpiUtil {
    private static final String NPI_PATTERN_STRING = "[0-9]{10}";
    private String npi;

    public static boolean isValidNpi(final String npi) {
        return new NpiUtil(npi).isValid();
    }

    private static String fromCharCode(int... codePoints) {
        return new String(codePoints, 0, codePoints.length);
    }

    public static String generateRandomNpi() {
        Double randomNumber = Math.floor(Math.random() * (999999999 - 100000000 + 1) + 100000000);
        int tmp;
        int sum;
        int i;
        int j;
        String npi9 = String.valueOf(randomNumber.intValue());
        i = npi9.length();
        if ((i == 14) && (npi9.indexOf("80840", 5) == 0))
            sum = 0;
        else if (i == 9)
            sum = 24;
        else {
            return "!";
        }

        j = 1;
        while (i != 0) {
            tmp = npi9.charAt(i - 1) - new String("0").charAt(0);
            if ((j++ % 2) != 0) {
                if ((tmp <<= 1) > 9) {
                    tmp -= 10;
                    tmp++;
                }
            }
            sum += tmp;
            i--;
        }
        String checkDigit = fromCharCode(((10 - (sum % 10)) % 10 + 48));
        return randomNumber.longValue() + checkDigit;
    }

    private NpiUtil(final String npi) {
        this.npi = npi.trim();
    }

    private boolean isValid() {
        return this.npi.length() == 10 && this.complies();
    }

    private boolean complies() {
        if (!this.npi.matches(NPI_PATTERN_STRING)) {
            return false;
        }
        final Character lastDigit = this.npi.charAt(9);
        final List<Integer> everyOther = this.listWithEveryOtherDoubled(this.npi.substring(0, 9));
        int sum = 0;
        for (final Integer num : everyOther) {
            sum += sumOfDigits(num);
        }
        final int total = sum + 24;
        final int units = total % 10;
        final int checkDigit = (units != 0) ? (10 - units) : units;
        return Character.getNumericValue(lastDigit) == checkDigit;
    }

    private List<Integer> listWithEveryOtherDoubled(final String str) {
        final List<Integer> nums = new ArrayList<Integer>();
        for (int i = 0; i < str.length(); ++i) {
            if (i % 2 == 0) {
                nums.add(2 * Character.getNumericValue(str.charAt(i)));
            } else {
                nums.add(Character.getNumericValue(str.charAt(i)));
            }
        }
        return nums;
    }

    private static int sumOfDigits(final int number) {
        int num = number;
        int sum = 0;
        while (num > 0) {
            sum += num % 10;
            num /= 10;
        }
        return sum;
    }

    public static void main(final String[] args) {
        System.out.println("Hello, World!");
        System.out.println("1234567890".matches(NPI_PATTERN_STRING));
        System.out.println("123456789".matches(NPI_PATTERN_STRING));
    }
}

Usage:
import org.junit.Assert;
import org.junit.Test;

public class NpiUtilTest {
    @Test
    public void testNpiUtil() {
        for (int i = 0; i < 100; ++i) {
            Assert.assertTrue(NpiUtil.isValidNpi(NpiUtil.generateRandomNpi()));
        }
    }
}

Answer: There are multiple way to validate the NPI.

Use API call to validate NPI. Reference link: https://npiregistry.cms.hhs.gov/registry/help-api  and data use Querying JSON data from CMS NPI data
Using the Luhn formula. Reference document  https://www.cms.gov/Regulations-and-Guidance/Administrative-Simplification/NationalProvIdentStand/Downloads/NPIcheckdigit.pdf:

Function to validate using Python 3.8:
kk= '1497842694'
def val_npi(NPI):
    if (len(NPI)==10):
        k = 0
        k1 = 0
        if (NPI[0] in (['1','2'])):
            for i in   NPI[:9][::2]:
                if(int(i)*2<10):
                    k = k + int(i)*2
                else:
                    k = k+((int(i)*2) % 10)+ 1
            for i in  NPI[:9][1::2]:
                k1 = k1+int(i)
        if((10-(k+k1+24)%10)==int(NPI[-1])):
             return True
        if ((k+k1+24)%10)==int(NPI[-1]):
             return True
    return False

Answer: VB.Net function to validate NPI Number Checksum
Private Function ValidateNPI(ByVal sNPI As String) As Boolean
'KP calculate the Checksum of an NPI using the Luhn Algorithm
'This can easily be modified to return a checksum instead of a boolean '1/17/2007.
Dim I As Integer
Dim iCnst80840Prefix As Integer = 24
Dim iRoutine1 As Integer 'Add the 80840 prefix along with the literal even digits
Dim dRoutine2 As Double
Dim dRoutine3 As Double
Dim dRoutineResult As Double
Dim dRoutineCeiling As Double
Dim dFinalResult As Double

Try
'example NPI without check sum is "123456789″, The checksum is 3
'KJP add the even digits (From the left: 2,4,6,8) and the "80840″ Prefix value.
'This returns the first value.
iRoutine1 = iCnst80840Prefix + CInt(Mid(sNPI, 8, 1)) + CInt(Mid(sNPI, 6, 1))
+ CInt(Mid(sNPI, 4, 1)) + CInt(Mid(sNPI, 2, 1))

'KJP Loop through the odd digits(From the left: 1,3,5,7,9),
'multiply by 2 and add the numbers (not the SUM) together
'This returns the second value.
I = 1
Do Until I > 9
Dim sMidRslt As String
Dim dMidRslt As Double
Dim dMidRslt1 As Double
dMidRslt = Val(Mid(sNPI, I, 1)) * 2
sMidRslt = dMidRslt.ToString
dMidRslt1 = CDbl(Val(Mid(sMidRslt, 1, 1))) + CDbl(Val(Mid(sMidRslt, 2, 1)))
dRoutine2 = dRoutine2 + dMidRslt1
I += 2
Loop

'KJP add up and calculate all of the individual pieces
dRoutine3 = iRoutine1 + dRoutine2
dRoutineCeiling = (Val(Mid(dRoutine3.ToString, 1, 1)) * 10) + 10
dFinalResult = dRoutineCeiling – dRoutine3

'KJP result may be 10 so trim it down to the checksum of 0
If dFinalResult = 10 Then
dFinalResult = 0
End If
'KJP Do the final comparison
If CStr(dFinalResult) = Mid(sNPI, 10, 1) Then
Return True
Else
Return False
End If

Catch ex As Exception
Logger.Trace(SeverityLevel.CriticalError, ex)
Return False
End Try

End Function

Answer: I know the poster was asking for a custom validator in asp.net, but this thread pops up first when searching for NPI Validation. So, I figured I'd give my two cents.
Below is a custom validation method for the NPI/Luhn validation using
jQuery Validator as the API. Feel free to modify and apply this where needed. This could also be modified to run as a standalone function.
Below is the best solution I have come up with so far.
/**
 * jQuery Luhn validator for NPI (USA) WITHOUT the 80840 Prefix
 * Instead, using 24 as the magic bit in replacement of 80840
 * This is a tad bit more verbose than it should be,
 * but you can see how the number is being moved around which is
 * better for testing purposes.
 * https://www.cms.gov/Regulations-and-Guidance/HIPAA-Administrative-Simplification/NationalProvIdentStand/downloads/NPIcheckdigit.pdf
*/
jQuery.validator.addMethod("NPI",function(value, element){
  var npi = value;
  npi = npi.split('');
  var checkBit = npi.pop(), npi_double = [], npi_unaffected = [];
  npi.reverse();

  for (var i = 0; i < npi.length; i++) {
    if ((i % 2) === 0) { npi_double.push((npi[i] * 2)); }
    if ((i % 2) === 1) { npi_unaffected.push(npi[i]); }
  }

  npi_double = npi_double.toString().replace(/,/g, '');
  npi_unaffected = npi_unaffected.toString().replace(/,/g, '');
  var total = npi_unaffected + npi_double, total_sum = 0;

  for (var i = 0; i < total.length; i++) {
    total_sum += parseInt(total.charAt(i));
  }

  total_sum += 24; //Magic Bit
  var final = Math.ceil((total_sum)/10)*10;
  return ((final - total_sum) == checkBit) ? true : false;
}, "Not a valid NPI Number");

Be sure to add this to the rules field of validation input, e.g.,
npi:{
        required:true,
        NPI:true
      }


xpath returns more than one result, how to handle in python

Question: I have started selenium using python. I am able to change the message text using find_element_by_id. I want to do the same with find_element_by_xpath which is not successful as the xpath has two instances. want to try this out to learn about xpath.
I want to do web scraping of a page using python in  which I need clarity on using Xpath mainly needed for going to next page.
#This code works:
import time
import requests
import requests
from selenium import webdriver
driver = webdriver.Chrome()
url = "http://www.seleniumeasy.com/test/basic-first-form-demo.html"
driver.get(url)
eleUserMessage = driver.find_element_by_id("user-message")
eleUserMessage.clear()
eleUserMessage.send_keys("Testing Python")
time.sleep(2)
driver.close()
#This works fine. I wish to do the same with xpath.
#I inspect the the Input box in chrome, copy the xpath '//*[@id="user-message"]' which seems to refer to the other box as well.
# I wish to use xpath method to write text in this box as follows which does not work.

driver = webdriver.Chrome()
url = "http://www.seleniumeasy.com/test/basic-first-form-demo.html"
driver.get(url)
eleUserMessage = driver.find_elements_by_xpath('//*[@id="user-message"]')
eleUserMessage.clear()
eleUserMessage.send_keys("Test Python")
time.sleep(2)
driver.close()

Comment: Maybe you could use `find_elements_by_xpath` which will return a list and you can index it? (emphasis on element**s** instead of element). If there are 2 instances, your list will have 2 items in the order they appear on the page.
Answer: To elaborate on my comment you would use a list like this:
eleUserMessage_list = driver.find_elements_by_xpath('//*[@id="user-message"]')
my_desired_element = eleUserMessage_list[0] # or maybe [1]
my_desired_element.clear()
my_desired_element.send_keys("Test Python")
time.sleep(2)

The only real difference between find_elements_by_xpath and find_element_by_xpath is the first option returns a list that needs to be indexed. Once it's indexed, it works the same as if you had run the second option!
Comment: Thanks it worked.  Timely help when one is struggling to start.
Comment: @Ravi Glad to hear it worked! It's common practice on StackOverflow to click the check mark next to the post that solves your problem, so future viewers with the same problem will know what solution worked! When you get to 15 rep you can up-vote helpful questions and answers too! Welcome to SO.


Shopify search engine add-on

Question: I'm working on a search engine add-on.
Is it possible to add my search engine add-on into shopify frontpage?
I have research http://www.searchifyapp.com, how they can customize shopify search page?
Answer: I am not familiar with searchifyapp.com, so I won't tell you how it works, but I can tell you how it could be done.
If you want to have the shop's data indexed on your search server, then you will want to import the data from shopify on installation and use webhooks for updates.  The Syncing with a Store Shopify Wiki page explains how this is done.
You can use ScriptTags to inject javascript into the storefront. Then the javascript can find and enhance/modify the search field/form (e.g. for autocompletion/suggestions as they type, or modify the url for the search results page).
If you want to custom search results (e.g. from your own search server), then you could create an Application Proxy to serve results from your own web application.
Comment: Hi, i have read your documentation http://api.shopify.com/app_proxy.html, it doesn't work correctly, shopify give an error message "Temporary problem - We're experiencing a technical problem and we are doing everything we can to resolve it as soon as possible."
Comment: I checked and our api-proxy appears to be working.  Do you have a url, or steps to reproduce the problem?
Comment: I have solved the problem. My server in singapore, and I think shopify server is in US so that makes connection time out between the server. Thanks

Shopify search engine add-on


How to resort a collection in Java?

Question: I try make a project to write data from .mif/.tab files to Data Base using GDAL/OGR. I do:
SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(dbFeatureType);
SimpleFeatureCollection collection = FeatureCollections.newCollection();
while (mifReader.hasNext()){
  in = (SimpleFeatureImpl) mifReader.next();
  SimpleFeature dbFeature = featureBuilder.buildFeature(null);
  for(AttributeDescriptor ad : adList){
    String name = ad.getLocalName();
    Object attrValue;
    attrValue = in.getAttribute(name);
    if(attrValue instanceof String){
      String string3 = new String((attrValue.toString()).getBytes("ISO-8859-1"), "cp1251");
      if(name.trim().equalsIgnoreCase(kadname.trim())){
        dbFeature.setAttribute("kadnum", string3);
      }
    }
    if (attrValue instanceof Geometry){
        idn++;
        com.vividsolutions.jts.geom.Geometry geom = (Geometry) in.getAttribute(name);
        dbFeature.setAttribute("id", idn);
        System.out.println("after insrt="+idn);
        dbFeature.setAttribute("deleted", deleted);
        dbFeature.setAttribute("the_geom", geom);
        dbFeature.setAttribute("status_id", status_id);

    }
    collection.add(dbFeature);
    }
}

Its simple data from .mid file:
__id_|___kadnum_____

  3,"66:2:00:88 951"
  4,"66:2:00:88 952"
  5,"66:2:00:88 954"

And in db i get this:

My data is 2-4 rows. You see that i get increment variable idn and put it in attribute id. Take a kadnum from .mid and put it in attribute kadnum.
Its fine but in bd i get rows in the wrong order. I mean that element with attribute kadnum=66:2:00:88 951 gonna be in second row in db but it in 4th row.
 Its mean that i gonna change the order of items in the collection to the opposite. Its right solvetion? And how to do this? Or GDAL can do it by self?
UPDATE
I have:
 SimplePropertyImpl in =(SimpleFeatureImpl) mifReader.next();

I try:
in.getProperty("id").getName() ;

And i dont get a PropertyName i get a String. What i doing wrong?
Comment: Databases in general don't guarantee that rows are stored in a particular order. If you want to get the rows from the database in a particular order, use an `ORDER BY` clause in your SQL query.
Answer: Do you want to sort the database rows according to id?
select * from <yourtable> order by id asc;

If you want to sort your FeatureCollection in code, you may want to look into SimpleFeatureCollection.sort and SortBy. I would expect something like
collection.sort( new SortBy()
                 {
                     @Override PropertyName getPropertyName() { return YourPropertyNameImpl( "id" ); }
                     @Override SortOrder getSortOrder() { return SortOrder.ASCENDING; }
                 }

would get you started in the right direction.
Cheers,
Comment: That would indicate that *you* need to write *your own* implementation of PropertyName to tell the sort algorithm which property *you* want to sort on.
Comment: Hi, i want to sort collection. But i cant find how to use sortBy.
Comment: in this line ` @Override getPropertyName() { return "id"; } ` error `Type mismatch: cannot convert from String to PropertyName`
Comment: I did write "...get you started...", you should do some work yourself :-)
Comment: A method sortBy `The type SortBy is deprecated`.
Comment: See http://docs.geotools.org/latest/javadocs/org/geotools/filter/SortBy.html (*Please use org.opengis.filter.sort.SortBy*)
Comment: Wht is it `YourPropertyNameImpl( "id" );`? I cant find anything about propertyname.

How to resort a collection in Java?


Setting up an ecobee and need to adjust HVAC wiring

Question: My HVAC control board has two bundles of wires. One has 5 wires which runs to the thermostat but the 5th wire which I want to use as C is currently unused. The second set runs to the unit outside (condenser?).
My vague understanding is that I could just plug the unused blue wire into C beside the existing white wire and use it as C.
Here's some picture
Answer: You're spot on
Hooking the existing blue wire up to the C terminal alongside the white wire that's already there will do what you want and get you that C wire for your Ecobee.
Comment: Thanks for the quick reply. Do you think you could explain a bit why doing this won't interfere with the existing condenser wiring?
Comment: @FletcherMoore -- look at your Y terminal and how it's double tapped already


A lot of buffers are being dropped

Question: I'm trying to stream with RTP and the client says that there is allot of packet drops.
Server pipeline:
 gst-launch videotestsrc ! x264enc ! rtph264pay ! udpsink host=192.168.1.16 port=5000

Client pipeline:
gst-launch udpsrc uri=udp://192.168.1.16:5000 caps="application/x-rtp, media=(string)video, clock-rate=(int)90000, encoding-name=(string)H264, sprop-parameter-sets=(string)\"Z01AFeygoP2AiAAAAwALuaygAHixbLA\\=\\,aOvssg\\=\\=\", payload=(int)96, ssrc=(uint)1645090291, clock-base=(uint)1778021115, seqnum-base=(uint)28353" ! rtph264depay ! queue ! ffdec_h264 ! autovideosink

I can see the video on the client, but very slowly with a lot of packet drops. The error on the client side:
from element /GstPipeline:pipeline0/GstAutoVideoSink:autovideosink0/GstXvImageSink:autovideosink0-actual-sink-xvimage:
A lot of buffers are being dropped.
Additional debug info:
gstbasesink.c(2875): gst_base_sink_is_too_late (): /GstPipeline:pipeline0/GstAutoVideoSink:autovideosink0/GstXvImageSink:autovideosink0-actual-sink-xvimage:
There may be a timestamping problem, or this computer is too slow

If someone could tell me what am I doing wrong here, that would be great!
Answer: Instead of using "autovideosink" try "xvimagesink sync=false".
Comment: This works, but could you explain why sync should be false?

A lot of buffers are being dropped


Typeahead: Adding a last option

Question: I'm using Bootstrap v2.3.2 and I have a regular typeahead set up that gets data from a database.
I'm trying to make it so that the last result of each typeahead is the option "Search for <what you typed>". So if you typed "hello" in the input, the last option (under all other results) would be Search for "hello".
How would this be done?
Comment: can you share your typeahead code?
Answer: You need to modify the source parameter of Typeahead.
Here is how I implemented the same thing in my website :-
    $("#typeahead").typeahead({
        'source'=>function(query, process){
            return $.get("URL_OF_SEARCH", {string:query}, function(data){
                data = JSON.parse(data);
                var list = $.map(data, function(item){
                     var aItem = {
                         id: item.id, name: item.text, picture: item.picture
                     };
                     return JSON.stringify(aItem);
                });
                //Till here everything was done to fetch previous results and show them
                list.push({"id":"URL_OF_SEARCH/" + query ,"name":"Search for "+query, "picture":"/favicon.ico"});
                //This above line adds the last row which you want to add
                return process(list);
             });
        },
        'highlighter'=>function(item){
            item = JSON.parse(item);
            var itm = "
"
            + ""
            + "
"
            + "
" + item.name + "

";
            return itm;
        },
     });

I used 3 things to show in the list, a picture, a name and a link(ID). To implement this I also had to modify my highlighter function.
I hope this helps you.

Typeahead: Adding a last option


How to find difference of consecutive rows for different users in sql2000?

Question: I am trying to find the difference of numbers in consecutive rows, by user.
update [current]
set diff=
   ISNULL([next].number, 0) - [current].number
FROM
   my_table       AS [current]
LEFT JOIN
   my_table       AS [next]
      ON [next].ID = (SELECT MIN(ID) FROM my_table WHERE ID > [current].ID)
where [current].Date = [next].Date
and [current].User = [next].User

This code does not allow me to differentiate the users.
It just finds the difference of the consecutive rows, for all users.
I want it to find the difference of the consecutive rows for the same user.
Please help.
Comment: So if the rows were like Anna 1, Bob 2, Anna 3, would the diff for the first be 2 ( 3- 1) or -1 (0 -1) because the two Anna rows are not "consecutive"? As in, when you say consecutive do you mean literally consecutive, or simply the next row for that user as ordered by ID?
Comment: My code is giving me 1. (Bob 2 - Anna 1)
But I want it to give me 2. (Anna 3 - Anna 1)
Comment: Let me give you an example of what I want to achieve.

User    Number    Diff,
Anna    1         NULL,
Bob     2         NULL,
Bob     3         1,
Anna    4         3
Answer: If you just want to get the next number for a user, move your WHERE conditions into your ID-matching JOIN:
SELECT
    *
FROM
    my_table AS [current]
    LEFT JOIN my_table AS [next]
        ON [next].ID = (
            SELECT
                MIN(ID) -- get first ID
            FROM
                my_table
            WHERE
                ID > [current].ID  -- greater than the current
                and my_table.[User] = [current].[User] -- same user
                and my_table.[Date] = [current].[Date] -- same day
        )

Comment: The `LEAD()` and `LAG()` analytic functions in SQL Server 2012+ can be used to determine this more easily, but if you're still on SQL Server 2000 in 2014 I'm guessing you won't be upgrading any time soon.
Comment: @KyleHale It worked perfectly. Thanks!!!
This company uses SQL2000 and are planning to upgrade by mid 2015.
I'm a noob since I learnt 2008+


Changing Redis port in Docker Compose not working

Question: I have a Docker Compose file that starts two services: Redis and Redis Commander. Using the default Redis port 6379 works fine. After changing the Redis port to 6380 Redis Commander cannot connect to Redis anymore.
Error:
setUpConnection Redis error Error: connect ECONNREFUSED 172.19.0.2:6380

This is the docker-compose.yml file:
version: '3.7'
services:
  redis:
    container_name: redis
    hostname: redis
    image: sameersbn/redis:4.0.9-2
    ports:
      - "6380:6379"
    expose:
      - "6380"
    volumes:
      - type: volume
        source: redis-data
        target: /data
    restart: always
  redis-commander:
    container_name: redis-commander
    hostname: redis-commander
    image: rediscommander/redis-commander:latest
    restart: always
    environment:
      - REDIS_HOSTS=local:redis:6380
    ports:
      - "8082:8081"
volumes:
  redis-data: {}

I can connect to Redis on port 6380 using the following Node code:
import redis from 'redis'

const config = {
  host: '127.0.0.1',
  port: 6380,
  no_ready_check: true
}

const client = redis.createClient(config.port, config.host)

client.set('expireName', 'nidkil', (err, reply) => {
  if (err) {
    console.error('Error occurred:', err)
  } else {
    console.log('Response:', reply)
  }
})

If I change the port back to 6379 in the docker-compose.yml then Redis Commander can connect.
Any suggestions how I can make Redis Commander connect to Redis on port 6380?
Answer: The answer of @Mihai helpt me figure out the solution. I needed to change the port Redis is running on as well as the exposed port. This is the working Docker compose file.
version: '3.7'
services:
  redis:
    container_name: redis
    hostname: redis
    image: sameersbn/redis:4.0.9-2
    command: --port 6380
    ports:
      - "6380:6380"
    expose:
      - "6380"
    volumes:
      - type: volume
        source: redis-data
        target: /data
    restart: always
  redis-commander:
    container_name: redis-commander
    hostname: redis-commander
    image: rediscommander/redis-commander:latest
    restart: always
    environment:
      - REDIS_HOSTS=local:redis:6380
    ports:
      - "8082:8081"
volumes:
  redis-data: {}

Comment: I was just replying that. Well done! I think you can also customise only "command: --port 6380" instead of the whole entrypoint. It would be nicer in my opinion.
Comment: Thanks. I just add command `--port 6379` and it worked even use official `redis` image.
Comment: Done :-) Is more concise. Thx.
Answer: You changed the exposed port on the host. You did not change the internal port in the container. Your redis instance continues to run on the default port (6379).
Also this statement expose: - "6380" can be omitted since it is not useful.
Comment: How do I change the internal port of the container without changing the Dockerfile?
Comment: That's highly dependent on the configuration of the actual service; it might be a command-line argument or a configuration setting.  This is one of the key benefits of using Docker.  You can let the service run on its "normal" port, and because of Docker's network isolation it won't conflict with other services.
Answer: .env
REDIS_PORT=8379

docker-compose.yml
redis:
    image: redis:alpine
    command: --port ${REDIS_PORT}  // <- this line work for me
    ports:
      - '${REDIS_PORT}:${REDIS_PORT}'

Answer: The port forwarding command will map the port on the host machine to the port on the docker container. Note that the port on the left of the : refers to the port on to the host machine which is 6380 in this case however the redis on host is running on port 6380. By default redis on the container will run on port 6379. To run it on desired port command --port <<port_number>> should be used.