text:
Q: Holography versus Young's double slit In order to see interference fringes in double slit one needs the two slits to be very close (1-2 wavelengths) even using highly coherent laser. But in Holography this condition apparently does not play role. There is interference when the object is very far from the reference beam. Why is this?

A: Unfortunately, the condition you mention is not true. The simple truth is that interference is observed when highly coherent waves interact which each other. the source of the waves (be it slits, mirrors, or any other object) does not matter, as long as the interaction happens within the coherence length because only then the waves are correlated enough to each other to produce the interference.
A typical red laser has a coherence length of ~20cm. This means that if you illuminate a  Michealson interferometer with a red laser (let's say HeNe laser), the optical path difference between the two mirrors (which act like duplicate laser sources) can be as large as ~20cm, and you will still see interference patterns.
In holography, you also combine laser light from two sources: a reference beam and light scattered from the object you wish to image. Like the above example, in the optical path difference is within the coherence length (which it must be to achieve holography:), you will see interference.

A: You are wrong about that condition. For example, in his original experiment, using just Sunlight, Young divided a light ray with a card about one thirtieth of an inch thick. In a setup with two slits, that would be equivalent to a distance between the slits three orders of magnitude larger than the wavelength. I think you confuse with the width of each slit which has to be of the order of the wavelength for diffraction to happen.

A: First, you can't directly compare both experiments. In holography, interference patterns are created by overlaying a reference beam with the object beam. In off-axis holography, overlaying the beams is done with beam splitters and mirrors; in in-line holography, objects are small and often transparent, and since reference beam and object beam stem from the same light source, they will interfere.
In Young's double slit experiment, parallel light is shone through two slits, creating two (theoretically) identical beams that interfere with each other. They are parallel though, so all interference is caused by the parts diffracted to the left or right side when passing the slit. In terms of intensity, the diffracted part is only a small part of each beam, and the further you place the slits apart, the less the two beams can overlap and interfere with each other. In theory, interference will happen no matter how far the slits are apart, but not in practice because the light is not perfectly parallel or perfectly monochrome, the slits aren't cut perfectly straight, light is absorbed and scattered in the atmosphere etc, and you'd need a perfect detector to see the interference pattern.

A: The spacing of the slits and the wavelength of the light, together, determine the fringe spacing in Young's experiment.  The farther apart the slits, the closer together the fringe spacing (assuming that the fringes are viewed/recorded a fixed distance from the slits).  This is because the angle between the light coming from the two slits at any point on the recording plane is larger when the slits are farther apart, and the fringe spacing depends inversely on that angle.
In Young's double slit experiment, there will be interference regardless of the distance between the slits if the path from the light source to a slit, then to a point on the recording plane, is the same for both slits.  If the light has a relatively long coherence length (such as is provided by a laser), there will still be interference whenever the difference between those two distances is less than the coherence length of the light.
The reason the two slits are close together in Young's original experiment is that the coherence length of this light was very short, and his optical setup was very simple.  However, it's entirely possible to repeat Young's experiment by scaling everything up larger: put the point source a long distance away so the light spreads over a wide area that can cover two slits separated by a wide distance.  Far downstream, light that makes its way through the slits will spread enough to overlap, and will interfere to form widely spaced fringes.
It is also possible to modify Young's experiment to obtain very closely spaced fringes: spread the slits relatively far apart and use a pair of prisms or mirrors to tilt the beams toward each other so they overlap sooner and at a wider angle.
Bottom line:  Young's experiment is actually a very, very simple holography setup.  Just substitute a laser for the light source and add a few optical elements so the beam geometry can be controlled, and Young's experiment morphs into a modern holography setup.  If Young had realized (and pointed out) that a recording of the fringe pattern could be used to reconstruct one of the beams from the other, he might have been given credit instead of Gabor, for inventing holography.


text:
Q: How should I connect batteries in parallel? I have a pair of these Li-ion batteries. I'd like to couple them so that I get double the current. However, I realize that this could be a Bad Idea™, as the charge could flow in a loop through both batteries.
What is the best way to prevent this?
Should I add diodes in series with each battery? (if so, what type and value?)
Should I put a resistor in series with one of the batteries?
Or is there a better way?

A: The resistor solution has the main disadvantage that there can flow a (rather large) current from one battery to the other. This may reduce the life of the battery receiving the current (you're not properly "charging" it).
I would go for the diodes. If one battery's voltage is higher than the other this battery will be the only one supplying current, until both voltages are the same. From that moment both batteries will supply current.

A: Two batteries in parallel will work fine if the following are true:

*

*the batteries are of identical types

*the number of cells in each string is low (1 is best, 2-4 OK, I wouldn't do this for >4)

*the cells are matched (same age, charged + discharged together)

*the cells are in thermally similar environments -- if they're next to each other but one is next to a heat sink and the other is on top of a hot component, you'll reduce life.

A: If the load power isn't too low, you could connect the batteries in series then use a converter (i.e. a buck) to convert the power to  lower voltage / higher current. You'll need to implement some sort of undervoltage protection to shut the converter down if the input voltage gets too low. You'll lose some power in control as well as conversion.

A: Connecting 2 batteries of similar charge in parallel should not be an issue, your charger may struggle though and you may have to charge them seperately.

A: The original post hinted at a problem with parallel charging I experienced.  On of the three 12V 100Ah batteries developed a bad cell(s) and essentially dropped to 4V.  This caused the other batteries to die trying to equalize the pack.  In the end, I lost three pretty expensive batteries.
My current solution is to use a smart charger that has the capability of charging many batteries using separate leads to each battery.  That avoids the problem of parallel charging by not parallel charging.
If you are going to parallel charge two or more batteries, you need to install a device that prevents energy from backflowing from one battery to a weaker battery.  This is accomplished with a resistor (sized for your project) or a MOSFET (also sized to your project) which is installed in line with the connections between the batteries.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Designing an app with frequent JNI calls on Android I am building an Android app that integrates with a 3rd party library that is provided as a native library (.so file).
The app would need to use functionality from the native library at around 0-30 JNI calls per second.
Although the function calls are non-blocking and return almost immediately, i am wondering whether this design should be avoided to begin with, or the overhead of frequent JNI calls in practice can be used?
I have read a similar question here: What makes JNI calls slow?
But besides that, i couldn't find too many numbers regarding JNI performance.

A: On a device I looked at a couple years back, calling an empty static no-arg method in Java took 56ns, while calling the same through JNI took about 250ns.  (Calls got a bit slower in Ice Cream Sandwich -- was 200ns in Honeycomb.)
People tend to fixate on the "it's 5x as expensive" part.  What matters for your application is that the 30 JNI calls would incur less than 8 microseconds of overhead.
It's not worth worrying about unless you're calling it thousands (or tens of thousands) of times per second.


text:
Q: "Best" as a sign-off in a chat message A new colleague of mine, a native English speaker with whom I have only communicated via text, used "Best!" at the end of a chat message.

*

*Does this signify anything to the extent of "this conversation is over"? Is it rude to end a message like this without a lead-in?

*Does the usage of "Best!" allow any educated guess at what particular brand of English said colleague speaks (British, US-American, Australian, and so on)?

A: I'm a native US English speaker who has lived for long periods in Europe. I have many friends and colleagues who are also native speakers of other varieties of English.
Based on my own experience, I can tell you that "Best" is very widely used in English-speaking countries around the world and in all types of online correspondence, whether email, chats, or other forms of social media.
I haven't often seen it used with an exclamation point, but there's nothing wrong with doing that. It's a question of personal style.
I would say that using "Best" is a widely accepted, friendly but not too friendly, polite way to end any type of written communication. And to answer your second question, I don't think it offers any clue about which variant of English the author speaks.
Merriam-Webster notes that closing expressions like "Best wishes" began to be shortened to "Best" around the 1930s, and it cites correspondence by F. Scott Fitzgerald as an example. It then offers this to say about "Best" as a closing: "Certainly, there are critics of this 4-letter, elliptical valediction; however, to most its simplicity crisply connotes a sense of goodwill without sounding stuffy or disingenuous."

A: *

*It usually would not come off as ending a conversation forcefully because it's a standard, neutral-positive way to sign off. In any context where you are writing your name at the bottom, like an email, with "Sincerely, warm regards, cheers, [name]", you can use "best". The difference with an SMS is you less frequently "sign off". In this case the speaker seems to be politely signaling that the conversation is indeed over. So it could be socially negating if it was in an SMS and the person expected much longer continued interaction. In an email it would not be taken this way.

*I personally think it's slightly less common in the US but I might be wrong. I know it's common in European International English (i.e. an English speaking company based in the Netherlands or something). In the US I found the most common email signatures to be Sincerely, Cheers, Kind regards, and especially "Thanks/Thanks very much."


text:
Q: Is using an API for login validation safe Ok, so i am creating a c# win forms program that has a login form that uses a basic api i host on my website for the login validation (served over HTTPS).
So for example here is some code
    WebClient wb = new WebClient();
    wb.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.33 Safari/537.36");
    String response = wb.DownloadString("https://www.example.com?username="+userName+"&password="+password);
    if(response == "1")
    {
        //logged in
    }

I was just woundering if it is secure to use an API for login validation like i did in my example.. Thanks for reading

A: If the API owns performing tasks for an authenticated user, this is fine.
That is to say that the windows form application is a lightweight client only, but all actions that require authentication and certain authorisation levels are owned by the API. Meaning that without a valid token or similar the API simply rejects the attempt.
Please don't authenticate using query string parameters though, you should always authenticate with an API securely over HTTPS and ensure that sensitive information is hidden away in the message body of a post.
The query string parameters will be encrypted and non visible during transit but it's just bad practice to place sensitive information there. Especially passwords. Don't forget, when they hit the server on the other end, the URL is in plaintext so that it can be handled by the relevant web server pipeline such as IIS. Meaning that they will be visible in the logs and other areas too.


text:
Q: as.Date character string with month-day data Hi I am trying to determine whether my data points occurred during a proposed work season. I have this function:
### Get whether or not sighting occurred during the proposed work period
getWork <-function(w) {
    startWork <- as.Date("07-15", format = "%m-%d") #Start of stated work period
    endWork <- as.Date("02-15", format = "%m-%d") #End of stated work period

  ifelse (w >=startWork & w <= endWork, 1, 0)
  }

#convert SightDate to Month-Day
sightingsData$SightMonthDay <- format(sightingsData$SightDate, format="%m-%d")
sightingsData$workPeriod <- getWork(sightingsData$SightMonthDay) #Get Work T/F values for each date

The code for the function runs smoothly without errors, but I get an error for the output, as follows:
Error in charToDate(x) :
  character string is not in a standard unambiguous format
6. stop("character string is not in a standard unambiguous format")
5. charToDate(x)
4. as.Date.character(e1)
3. as.Date(e1)
2. `>=.Date`(w, startWork)
1. getWork(sightingsData$SightMonthDay)

However, if I change the syntax of the function to match that of creating the 'SightMonthDay' column, (i.e. startwork <- as.Date.... instead of startwork <- format....)I get an output, but all of the 'getWork' values are apparently between -1 and 0, however all of the observations are considered 0 [False] which out of over 23500 observations is not true. Here is the code to illustrate what I mean:
getWork <-function(w) {
    startWork <- format("07-15", format = "%m-%d") #Start of stated work period
    endWork <- format("02-15", format = "%m-%d") #End of stated work period
    +(w >=startWork & w <= endWork)
}

#convert SightDate to Month-Day
sightingsData$SightMonthDay <- format(sightingsData$SightDate, format="%m-%d")
sightingsData$workPeriod <- getWork(sightingsData$SightMonthDay) #Get Work T/F values for each date

And here's a little screenshot to show what I mean...

Here's a sample dataset:
       SightDate SightMonthDay workPeriod
18163 2017-11-15         11-15          0
17120 2017-10-23         10-23          0

> dput(droplevels(SampleData[1:20, ]))
structure(list(SightDate = structure(c(17485, 17462, 17469, 17417,
17871, 17294, 16712, 15069, 16576, 17416, 17515, 16407, 16399,
17298, 17164, 17244, 17464, 15628, 16388, 16598), class = "Date"),
    SightMonthDay = c("11-15", "10-23", "10-30", "09-08", "12-06",
    "05-08", "10-04", "04-05", "05-21", "09-07", "12-15", "12-03",
    "11-25", "05-12", "12-29", "03-19", "10-25", "10-15", "11-14",
    "06-12"), workPeriod = c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
    0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L)), row.names = c(18163L,
17120L, 17437L, 15597L, 23402L, 14359L, 9874L, 2902L, 8910L,
15585L, 19641L, 7769L, 7631L, 14399L, 13163L, 13447L, 17297L,
4511L, 7405L, 9113L), class = "data.frame")

Thank you for your time and help!!

A: Probably, your startWork and endWork are replaced.
getWork <-function(w) {
   endWork <- as.Date("07-15", format = "%m-%d") #Start of stated work period
   startWork <- as.Date("02-15", format = "%m-%d") #End of stated work period
   +(w >=startWork & w <= endWork)
}

and apply it to SightMonthDay.
SampleData$new_date <- as.Date(format(SampleData$SightDate, "%m-%d"), "%m-%d")
getWork(SampleData$new_date)

#[1] 0 0 0 0 0 1 0 1 1 0 0 0 0 1 0 1 0 0 0 1


text:
Q: How to prevent Pharo from executing a #startUp-Method of a class? I added a startUp-Method to one of my classes that immediatelly quits my image. Is there a way to prevent Pharo from executing that method so that I can fix it?

A: No, this is an issue of ongoing discussion. See this post on the Pharo mailing list.
Your only way to recover the image is to hack the VM, which I describe here. If you go that route, use the stack VM instead of the JIT (the same thread explains why further down).


text:
Q: Search excel/csv sheet1 for a string taken from sheet2, then change a value in same row Situation is I have a list (excel).  Need to go through that list and take each name in a column.  Then search for that name is another file (csv).  Once it's found I must change a value in the same Row as the found name, but in a column a few cells to the right.
Sub Macro1()
'
' Macro1 Macro
'
' Keyboard Shortcut: Ctrl+q
'
Dim myRange As Range

ActiveCell.Select
Selection.Copy
Set myRange = Selection
Sheets("identities").Select
ActiveWorkbook.ActiveSheet.Unprotect
Cells.Find(What:=myRange, After:=ActiveCell, LookIn:= _
    xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:= _
    xlNext, MatchCase:=False, SearchFormat:=False).Activate
ActiveCell.Offset(0, 13).Range("A1").Select
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = "TRUE"
ActiveCell.Offset(1, -13).Range("A1").Select
End Sub

The above code works to help automate the process a little bit.  I'm trying to get it to the point were it can cycle through the column on Sheet1 without me switching back and forth and running it manually on each cell.  And I should probubly build in error handeling for if it doesn't find the name it's searching for.
Thanks for your help!

A: You will need to adapt the range your are getting the original values from to reflect yours. At present I just used Range("A1:A10"), but you need to stop using select. It will spoeed the code up and make it much more readable.
Try this and amend the range to suit yours.
Dim rng As Range
Dim r As Range

   For Each r In Sheets("identities").Range("A1:A10")
        ActiveWorkbook.ActiveSheet.Unprotect
        Set rng = Cells.Find(What:=r, After:=ActiveCell, LookIn:= _
            xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:= _
            xlNext, MatchCase:=False, SearchFormat:=False)
          rng = Sheets("identities").Offset(, 13)
   Next r

Read this stackoverflow thread on not using select.
How to avoid using Select in Excel VBA macros


text:
Q: Nav.Link href in React Bootstrap not redirecting when collapsed I have an offcanvas navbar and when it's collapsed it isn't working. I'm following this tutorial from the React Bootstrap documentation:
https://react-bootstrap.github.io/components/navbar/#offcanvas
So I have this Navbar:
<Navbar collapseOnSelect sticky="top" expand="lg" className={colorChange ? 'navbar-dark bg-dark' : styles.no_color}>
      <Container fluid className={styles.nav_padding}>
        <Navbar.Brand className='navbar-brand center-brand' href="#home">
          Logo
        </Navbar.Brand>
        <Navbar.Toggle aria-controls="offcanvasNavbar-expand-lg" />
        <Navbar.Offcanvas
          id={`offcanvasNavbar-expand-lg`}
          aria-labelledby={`offcanvasNavbarLabel-expand-lg`}
          placement="end"
          className={colorChange ? 'navbar-dark bg-dark' : styles.no_color}
        >
          <Offcanvas.Header closeButton>
            <Offcanvas.Title className={colorChange ? 'text-white' : 'text-black'}>
              Menu
            </Offcanvas.Title>
          </Offcanvas.Header>
          <Offcanvas.Body>
            <Nav className="me-auto">
              {typeNavbar == "personal"
                ? <></>
                : <>
                  <Nav.Link className={styles.link} href="#home">Home</Nav.Link>
                  <Nav.Link className={styles.link} href="#mission">Our mission</Nav.Link>
                </>
              }
            </Nav>
          </Offcanvas.Body>
        </Navbar.Offcanvas>
      </Container> : <></>
      }
    </Navbar>

So as said, when it's collapsed because you are using your phone, the Nav.Links aren't redirecting even if the URL shows that it's getting the order:

Do you know how is this possible? Moreover, when it's not collapsed, it works fine. Thankss!


text:
Q: Bloquear todas las URL menos una en un dominio con Apache2 Estoy tratando de bloquear en un wordpress que tengo, las url que no sean la principal. Por ejemplo:

*

*https://www.tudominio.com aquí sí dejamos pasar

*https://www.tudominio.com/ejemplo  la bloqueamos

Y así con cualquier cosa que se escriba.
¿Cómo puedo hacerlo?

A: Esto me ha servido, ya que permite filtrar las URLs que le indicas.
    RewriteEngine on
    RewriteCond %{REQUEST_URI} !/index.php
    RewriteCond %{REQUEST_URI} !/wp-admin
    RewriteCond %{REQUEST_URI} !/wp-login.php
    RewriteCond %{REQUEST_URI} !/hola-mundo/
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} !\.(pdf|jpeg|css|gif|ico|jpg|js|png|swf|txt|svg|woff|ttf|eot)$
    RewriteRule . / [R=404,L]

Con esto dejas como ejemplo esas cuatro uris y todo lo demás, apache se encarga de bloquearlo.


text:
Q: Comparing two boolean variables in JS I`m sending my form data with JQuery .ajax(), and i want to check if every input field is filled. But when i try to compare the boolean variables it is always getting in the else{} statement.
That`s is my JQuery:
$(document).ready(function(){
    $('.form').on('submit', function(e){
        e.preventDefault();

        var formData = $('.form').serializeArray();

        $.ajax({
            url: '../php/data.php',
            type: 'POST',
            data: $(this).serialize(),
            success: function(response){
                if(response === true){
                    $('.result').html("Message sent!").css("color","green");
                } else{
                    $('.result').html("Please fill all fields").css("color","red");
                }
            }
        })
    })
});

And that`s the php:
<?php
    $flag = true;

    $data = $_POST;

    foreach ($data as $row) {
        if ($row === '') {
            $flag = false;
        }
    }
    var_dump($flag);

 ?>

The question is what am i doing wrong???

A: You should use
echo $flag;

and not the var_dump() function. This one is only used for debugging purposes and shows you some data concerning the variable you will pass to it.


text:
Q: Can't edit pages: There has been a critical error on this website. Please check your site admin email inbox for instructions I use Enfold as my theme on Wordpress. I have tried  updating plugins, disabling plug-ins, doing a malware scan, increasing php to 256M and nothing has worked. I did a debug and this is what I get in bold:
{main} thrown in /home2/impacut9/public_html/wp-includes/class.wp-dependencies.php on line 186
which refers to the second line of this code $handle_parts = explode( '?', $handle );:
foreach ( $handles as $handle ) {
$handle_parts = explode( '?', $handle );
$handle = $handle_parts[0];
$queued       = in_array( $handle, $this->to_do, true );
Is there any help for this?


text:
Q: How to avoid Cache error on django 1.11 and redis 3.0 Recently our Redis pack was updated from version 2.10.6 to version 3.0.1.
Because of that we start to have a DataError exception, raised when we try to login to Django web site.
The solution we got was to revert the update and fix the Redis version to 2.10.6, this worked fine, and according to the Redis docs, this error is expected, as they changed some encoding restrictions:

Redis-py 3.0 only accepts user data as bytes, strings or numbers (ints, longs, and floats). Attempting to specify a key or a value as any other type will raise a DataError exception.

My question, is that if this is an error with Django 1.11? And, if this is the case, how can we update to Redis 3.0, without getting that raise?

A: Django-redis does not support redis-py 3.0 yet. See this issue for more information.


text:
Q: How to pass getAttribute with response()->json to ajax result on Laravel I have small laravel function called from ajax. Then I have to return result to ajax result. For example
Public function Edit(Request $request){
        $user = User::find($request->id);
       //.........
        return response()->json($user);
}

But I have problem on 'salary' property because of It getting from getSalaryAttribute method
public function getPositionnameAttribute(){
   ...........
}

So, at the ajax result return 'undefined', that reasonable because 'salary' property does not exist. I do not need to made specific collection to handle only salary parameter.
Any advise or guidance would be greatly appreciated, Thanks.

A: You have two options:

*

*add protected $appends = ['salary'] to your model

or

*append it on run time: $user->append('salary')->toArray();
Check out the docs: https://laravel.com/docs/5.8/eloquent-serialization#appending-values-to-json

A: You need to add this attribute to $appends array.
Model
protected $appends = ['position_name'];

NOTE: The $hidden and $appends feature (written above) is for modeling of JSON data and will not effect blade access to properties and/or model renderings.
https://laravel.com/docs/8.x/eloquent-serialization#appending-values-to-json

A: Appending At Run Time add this attribute to $attributes array,
The append method. Or, you may use the setAppends method to override the entire array of appended properties for a given model instance.
return $user->append('salary')->toArray();

return $user->setAppends(['salary'])->toArray();


text:
Q: Get contact Details from contactId in android? I am using the following code to fetch the contact details in android using the contact Id. However the code works fine only on android devices version 2.3.5 and not 2.3.3 or versions above 3. Following is my code where contactId is the id of that particular contact. The execution does not move into the if (phone.moveToFirst()) {} part is there some problem in the Query? If so, then why does it work fine on version 2.3.5? Any Help will be appreciated..Thanks
public String queryAllPhoneNumbersForContact(int contactId)
{
    String[] projection = new String[] { Phone.NUMBER, Phone.TYPE };

    @SuppressWarnings("deprecation")
    Cursor phone = managedQuery(Phone.CONTENT_URI,
            projection,
            Data.CONTACT_ID + "=?",
            new String[] { String.valueOf(contactId) }, null);

    if (phone.moveToFirst())
    {
        int contactNumberColumnIndex = phone.getColumnIndex(Phone.NUMBER);
        int contactTypeColumnIndex = phone.getColumnIndex(Phone.TYPE);

        while (!phone.isAfterLast())
        {
            String number = phone.getString(contactNumberColumnIndex).trim();
            int type = phone.getInt(contactTypeColumnIndex);

            System.out.println("number" + number);
            System.out.println("Type"   + getString(Phone.getTypeLabelResource(type)));

            phone.moveToNext();
            if ((getString(Phone.getTypeLabelResource(type)).equals("Mobile")))
            {
                Log.e("WorkNo. : ", number);
                return number;
            }
        }
    }
    phone.close();
    return null;
}

A: What devices exactly doesn't work? I recommend you use the 2.2 version that works fine for the major versions and devices


text:
Q: Is Keeping a Small List of Strings as a Text File (And Reading Them in) Better Than Keeping Them in Code I have a small list of around 500 strings (all just common words). I've heard it's best practice to keep them as a file and read the strings into the code. But I'm wondering what is the downside for keeping them just in the code in the first place? This is not an opinion based question, I'm asking about the actual quantitative trade-offs between the 2 approaches.
Thank you!


text:
Q: Installing the gem system_timer on Windows Has anybody here successfully installed the system_timer gem on Windows?
I have devkit on my machine and I am able to install other native gems.
I get the following error when I install the gem.
In file included from system_timer_native.c:2:
c:/Ruby19/include/ruby-1.9.1/ruby/backward/rubysig.h:14:2: warning:
    #warning rubysig.h is obsolete
system_timer_native.c: In function `install_timer':
system_timer_native.c:28: error: storage size of 'timer_interval' isn't known
system_timer_native.c:33: warning: implicit declaration of function `sigprocmask'

The gem home page states that it doesn't work on Windows
SystemTimer  only works on UNIX platforms (Mac OS X, Linux, Solaris, BSD, …).
You can install the gem on Microsoft Windows, but you will only get a
convenience shell wrapping a simple call to timeout.rb under the cover.

I am on Ruby 1.9, Since the threading model is different in 1.9, I am wondering if gem will work in 1.9.

A: The problem isn't with Ruby's threading system, it's with the Windows kernel's timer system, I believe.

System Timer, a timer based on
  underlying SIGALRM system timers, is a
  solution to Ruby processes which hang
  beyond the time limit when accessing
  external resources. This is useful
  when timeout.rb, which relies on green
  threads, does not work consistently.

You are better off asking directly the makers of the gem whether they have support for Windows+1.9 in the pipeline (if it's possible at all).


text:
Q: How to remove dark shadow from navigation drawer? I am a beginner in android development.I am very confused of seeing this shadow above booking details.i want to know what it is? And how to fix it?
[

A: If you want to hide shadow from upper part of the drawer then ..
1) It is your actionbar drawn partially. so it is appearing as shadow.
2) to Remove that shadow , I had to apply app:insetForeground="@null" to the NavigationView in xml

A: drawerLayout.setScrimColor(getResources().getColor(android.R.color.transparent));

Try this code .


text:
Q: Looping over a dynamic list I would like to make a block of code to make a list that look something like so
result = [['a','a','a','a'],
          ['a','a','a','b'],
          ....

and so on.
as of yet I try to do it with three list like so.
lst = ['a' for x in range(num)]
item_lst = [[None,None] for x in range(num)]
char_lst = string.printable

My current plan is to make the item_lst a sort of index of lst where, item_lst[0] is the position in lst, and item_lst[1] is the position in char_lst.
later down in the code there will be a for loop that replaces the character in lst with the the character in char_lst, Based on the instructions of item_lst.
I would like to know if you
A) know of a way to make a loop to complete my ideer
or
B) have a better method of doing it
In the end, the goal would be to make a list with every printable character, in every configuration possible with the given length.

A: The solution is very simple:
import itertools
import string

num = 4
result = list(itertools.product(*([string.printable] * num)))

However, the list is gonna be very long, so this might not be what you want. Specifically, you would have a list with 100000000 elements (with 100 printable elements and num=4). You should use generators, not lists:
for lst in itertools.product(*([string.printable] * num)):
    # do something with lst


text:
Q: convert autocad shx font to true type font dears i am using Autocad 2019 and a lot of text with .SHX style, these text are in Arabic language i want to convert them into true type font, if i change font style the arabic characters become English characters.
Any idea!!
also i have an idea but i don't know if this possible or not! first change SHX to true type font, then write small script that rematch all English characters to Arabic characters as shown in screen. i know a little about Python, but don't know if Autocad support python or not.
enter image description here

A: In order to do this, you will need a routine that will translate the characters in the current text string to the correct character in the true type font.  .SHX is old school and is ASCII based. All of the characters have a decimal value of between 32 and 127 (could be 255, I do not exactly recall).  These decimal values, when displayed using a true type font equate to standard English characters.
I do not know of a routine that already does this but search for a "AutoLisp" routine (AutoCAD's default scripting language) that may do this - there are hundreds of existing AutoLisp routines.
If a routine does not already exist, one of the web sites that have AutoList routines can make a custom routine (unless you chose to make one your self - AutoLisp is a fairly easy lanugage to learn - except it Lisp based).
Web sites, for example, that have AutoLisp routines: http://www.lee-mac.com/programs.html or Jeffery Sanders or CAD Studio


text:
Q: How to use Dynamic Type in TextView inside Table View Cell I want to implement Dynamic Type in my application, so the app can adapt to user font preference. I have a Table View with 3 static cells. The first and second one has UITextField and they work fine without any problems. The third one which is a cell with UITextView doesn't scale. Dynamic Type is set to on and the font is Body.
Here's my code in my UITableViewController.
override func viewDidLoad() {
    super.viewDidLoad()

    tableView.rowHeight = UITableView.automaticDimension
    tableView.estimatedRowHeight = 100
    setupTextFieldsAndTextView()
}

func setupTextFieldsAndTextView() {
    emailTF.keyboardType = UIKeyboardType.asciiCapable
    titleTF.keyboardType = UIKeyboardType.asciiCapable
    messageTextView.keyboardType = UIKeyboardType.asciiCapable

    emailTF.returnKeyType = .next
    titleTF.returnKeyType = .next
    messageTextView.returnKeyType = .default

    emailTF.delegate = self
    titleTF.delegate = self
    messageTextView.delegate = self
}

and UITableView delegate
 override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableView.automaticDimension
}

I want to have the same design as in the iOS calendar app. Cell scale based on chosen font type but UITextView is still scrollable and the text inside is also chosen by the user. UITextView in the screen is a cell with text placeholder "Notes".

A: Few steps to be checked for the UITextView :

*

*It must be inside your cell.

*Its constraints must be set up with the cell.

*Its text style MUST be selected if you want to use the Dynamic Type feature.

*Its Automatically Adjusts Font property MUST be ticked in the Interface Builder if you want to use the Dynamic Type feature.

*Turn off the Scrolling Enabled property in the Scroll View section of the Attributes Inspector.

Once all these elements are checked, the cell height and the UITextView font size should adapt the desired size.
I suggest you take a look at this detailed summary of the WWDC 2017 video that perfectly explains how to build an app with Dynamic Type.

A: Please check this for a dynamic height of textView in tableView.
// Tableview Delegate Method
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "NotesCell", for: indexPath) as! NotesCell

    cell.txtViewNotes.tag = indexPath.row
    cell.txtViewNotes.delegate = self

    return cell;
}

// Textview Delegate Method
func textViewDidChange(_ textView: UITextView) {
        adjustFrames(textView)
}

// Custom Method
func adjustFrames(_ textView: UITextView)  {
    let indexPath = IndexPath(row: textView.tag, section: 0)
    let cell = yourTableView.cellForRow(at: indexPath) as! NotesCell

    UIView.setAnimationsEnabled(false);

    self.yourTableView.beginUpdates()
        cell.constNoteHeight.constant = textView.contentSize.height
        textView.beginFloatingCursor(at: CGPoint.zero)
        textView.endFloatingCursor()
    self.yourTableView.endUpdates()

    UIView.setAnimationsEnabled(true);

}

Notes: constNoteHeight is the height constant of textView.

A: Use GrowingTextView, For UITextView


text:
Q: Single word request: a non-changing temporal trend Is there a word for describing a non-changing temporal trend? Stasis?
E.g. expenditure on health care did not change between 2000-2020.

A: So far as I can make any sense out of the given information, the word you seem to be looking for is constant.

INVARIABLE, UNIFORM

[Merriam-Webster]
So you could say Expenditure on healthcare remained constant during 2000-2020.


text:
Q: Time zones with and without DST in PHP The more I read up on this, the more confused I get.
My plan for a project is to handle all date/time storage and calculation in UTC except when it comes to displaying that data. The problem is that the server will move to different locations with different time zone and daylight savings time information, so I'll have to implement some form of time zone selector in the UI.
But there's all kinds of exceptions to where DST happens and where it doesn't, e.g. Arizona has no DST except for the Navajo Indian Reservation. So I can't simply use the PHP list of time zone locations (e.g. 'America/Phoenix') since I don't know if the actual location of the server will be in such an area, so I'm guessing I'll have to implement a checkbox saying "Use Daylight Savings Time" and a more basic select box with simple time zone information, e.g. "CST -6" etc.
I could use the 'America/Phoenix' system to display a list of cities, but that would result in a really long list. But if I use EST/CST in my list, it won't be accurate for areas with vs. without DST, so I don't think I can do this without the "DST?" checkbox.
However, I just tried PHP's DateTime and DateTimeZone with 'CST', 'CDT', and 'CST6CDT', and all three result in the same time, both for a date in February and a date in June. I figured, CDT should be with DST, CST should be without DST, and CST6CDT should use automatic switching, but apparently it's not that simple...
So ... if I am using a list of time zones like EST/CST/PST etc. and want the ability to turn off DST via a checkbox, how would I implement that in the PHP code? How can I tell PHP to convert the time to the correct time zone WITH support for turning DST on or off?
I know the basic code for this, but not how to change DST:
$myTime = new DateTime('02/10/2013 08:00:00', new DateTimeZone('UTC'));
var_dump($myTime);  // UTC
$localTz = new DateTimeZone('America/Phoenix');  // selected by user
$myTime->setTimezone($localTz);
var_dump($myTime);  // Phoenix with local DST settings

On a different but related note, does changing the location of a Linux server cause the server's internal clock to change time zones? Will moving the server mess up the internal clock and result in incorrect UTC timestamps?

A: As somebody who spent 13 months working on a major refactor revolving around this, I can tell you: you must store user intent time and then decode that to viewer local time.
What I mean by "user intent time" is the combination of the time and the user's time zone. As DST changes, you will need to use both pieces of information to decode what time to display for a user from a different location.  I don't just mean when spring and fall changeovers happen - I mean when governments change the DST laws and the Olson tzdata database is updated.
You do have a cron job to update tzdata from PECL often, right? :)
You'll want to use - and likely extend - PHP's buggy DateTime and DateTimeZone builtins.  They're your only hope.

A: The approach you describe has been done before, and always has the same problems:

*

*Most users aren't smart enough to know whether to check the box or not.

*It doesn't make sense to even have the box, since the time zone rules have all the details of whether or not DST applies, when it applies, and by how much.

*Time zone abbreviations are ambiguous.  For example, without any other information, how do you know that CST means US Central Standard Time?  It might mean China Standard Time or Cuba Standard Time.  There is a list here that illustrates all of the variations.

*There isn't always agreement about what the abbreviation should be.  For example, is Hawaii in HST or HAST?

It is always best to use the actual IANA time zone identifier, such as America/Phoenix or America/Los_Angeles.  If you need an easier way for your users to pick the correct time zone, try a map-based picker, such as this one.
To clarify your concerns about the operating system time zone affecting PHP.

*

*If you just say new DateTime(), then yes - it will pick up the default time zone.  This can be changed with a call to date_default_timezone_set, but the initial setting comes out of the date.timezone setting in the php.ini file, or from the TZ environment variable of the OS.

*It's always better to be explicit about the time zone, so you are not affected by any of these defaults.
For example, to get the current time in Phoenix:
new DateTime(null, new DateTimeZone('America/Phoenix'))

To get it in UTC:
new DateTime(null, new DateTimeZone('UTC'))

*You can use UTC where it makes sense, but it is not a mandate.  Where it matters most is when you save/retrieve from the database, or when transmitting across an api, web service, etc.

*If you are always explicit, then the time zone of the server doesn't really matter.  Linux will sync the system bios to UTC regardless of the time zone.  Windows will sync the bios with local time, but has some internals such that you can always get the correct UTC time still. (rather ugly, but works).

*But still, it is a "best practice" to set servers to UTC time zone.  The main reason is so that you find out early that you have time-zone dependent code.  (The worst time to find out is in the middle of the night during a DST transition you didn't plan for.)


text:
Q: A very, very specific idiom for a type of sloppy victory For context, I first heard this idiom used some months ago in my workplace which deals with cinema and storytelling, so there's a chance it might be a trope and not a colloquial idiom or similar. The structure is "an X Y", like "a Pyrrhic victory" or "a dead duck."
It's meant to describe an effort where there are a string of mistakes, some of which compound into another - "a series of unfortunate events" - but at the end of it all, the job is still complete, or the victory is still had. The tonality is neutral to positive. A friend suggested "by the skin of one's teeth" which is similar but it doesn't hit the structure and the tonality is more... earnest? Whereas the one I'm thinking of is almost comical.
I'm sure you lot get questions like these all the time so I sincerely appreciate any and all help! Thank you!

A: Choice may depend on context and on the degree to which you specify a "string of mistakes", but four notions come to mind:
It is the "right outcome for the wrong reasons", a "happy accident", a fluke.

Right for the Wrong Reasons
Someone makes a conclusion based on what they perceive are facts. Their conclusion is correct but the assumed facts themselves are wrong.
TV Tropes

happy accident = when something unexpectedly good comes from what would otherwise be considered a mishap.
"The discovery of Guinness was a happy accident"
Urban dictionary

fluke = something good that has happened that is the result of chance instead of skill or planning
Cambridge dictionary

Another single word description is

serendipitous: come upon or found by accident; fortuitous:
"serendipitous scientific discoveries."
of, relating to, or suggesting serendipity. good; beneficial; favorable:
"serendipitous weather for our vacation."
Dictionary.com

A: UPDATE: Unfortunately none of the answers here quite came close, so I did a lot of internet digging. My room mate of all people wound up linking me to some old website with lists of idioms that I went through one by one - "comedy of errors" is what I was looking for!


text:
Q: How do I view auditlogs from Dialogflow in gcp Logs I activated Audit logging for the Dialog API in my GCP Project, now i want to see if a new intent was added in the logs. But on the logging monitor is nothing

A: I have enabled audit logging on my dialog flow and was able to successfully create logs in Stackdriver Logging. To do this I went on the gear menu next to my project ID > in the bottom of the General page checked the box in log settings that says: log interactions to Google Cloud.
I also had to refresh my service account access token in the same menu next to the service account name. the service account is also the log writer its possible that it's token is outdated.


text:
Q: I am getting function name in the form of a string from the backend i need to add it to onClick event of a button in react I am getting function name in the form of a string from the backend i need to add it to onClick event of a button in react but getting error ReactJS: Expected onClick listener to be a function, instead got type string how can i add the string to onClick function
response object from backend :
[
{option : {onClickFunc : "getReleaseNotes"}}
],

React on front end
<div onClick={option.onClickFunc}>
</div>

error on click :
ReactJS: Expected onClick listener to be a function, instead got type string

A: You can use eval
eval(option.onClickFunc)();

or add getReleaseNotes to an object and then get it with accessor
myFunctions[option.onClickFunc]();

Look at this post How to execute a JavaScript function when I have its name as a string for more options.


text:
Q: how can the slopes be calculated using a covariance matrix? I am very new to the concept of regression. While going through an R output for a multiple regression I came across a set of estimates for the slope and got interested to solve for the same. for 2 independent variables the formula derived from  the covariance matrix works fine but the trouble starts while solving it for more than 2 variables.
Can some one help me with how the formula is extended in case of more than 2 IVs?
Sorry for this naive question.But I am very curious about the fact.
The formula that I have been following is-
β1=Cov(y,x1)var(x2)−Cov(y,x2)Cov(x1,x2)/var(x1)var(x2)−Cov(x1,x2)2
For three IVs, does the following formula make any sense?
β1=Cov(y,x1)var(x2)var(x3)−Cov(y,x2)Cov(y,x3)Cov(x1,x2)Cov(x1,x3)cov(x2,x3)/var(x1)var(x2)var(x3)−{Cov(x1,x2)Cov(x2,x3)Cov(x1,x3)}2
It will be of huge relief if someone could correct me. Thank YOU.


text:
Q: How to turn on/off Azure virtual machine via Azure management api (rest) I want to create a start/stop Azure VM bot for myself. What I want to do is to have a slack/telegram bot that listens to messages and starts/stops my VM by commands /start/stop. What REST api command should I use to do that?
What is needed:
Some sample code in C# that calls azure management API to start deallocated virtual machine
Some reference where I can get values for API method parameters (e.g. subscription id, resource id, etc).
Also
I have read this question, but it didn't help me to understand how to deal with authorization and where to get those parameters.
I am creating that bot using C# language.

A:
calls azure management API to start deallocated virtual machine

Virtual Machines REST API lists the operations on virtual machines. To start a virtual machine, you can try this API:
POST https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Compute/virtualMachines/{vm}/start?api-version={apiVersion}

where I can get values for API method parameters (e.g. subscription id, resource id, etc).

You can find {subscriptionId} and { resourceGroup} on Azure portal.

how to deal with authorization

You can check this article to get started with Azure REST operations and request authentication. And you can refer to the following code to acquire an access token.
string tenantId = "{tenantId}";
string clientId = "{clientId}";
string clientSecret = "{secret}";
string subscriptionid = "{subscriptionid}";

string authContextURL = "https://login.windows.net/" + tenantId;
var authenticationContext = new AuthenticationContext(authContextURL);
var credential = new ClientCredential(clientId, clientSecret);
var result = await authenticationContext.AcquireTokenAsync(resource: "https://management.azure.com/", clientCredential: credential);

if (result == null)
{
    throw new InvalidOperationException("Failed to obtain the JWT token");
}

string token = result.AccessToken;

Besides, this article explained how to create AD application and service principal that can access resources, please refer to it.


text:
Q: How would I query for a relationship between these two nodes? If I have a graph that looks like so for nodes (p) and (e):
(p:Person)-[r:WorksFor]->(e:Employer)

And I have the following data:
(Person {name: Andrew})-[r:WorksFor]->(Employer {name: Google})
(Person {name: James})-[r:WorksFor]->(Employer {name: Google})
(Person {name: James})-[r:WorksFor]->(Employer {name: Apple})
(Person {name: Evan})-[r:WorksFor]->(Employer {name: Apple})

How can I query between (Person {name: Evan}) through each relationship and get to (Person {name: Andrew}) returning each employer and person along the way with an arbitrary number of employers and persons in-between?
Ideally the above would return a chain that looked like:
(Andrew)->(Google)->(James)->(Apple)->(Evan)

Thank you for your help.
(EDIT) Addendum:
The following seems to work but only if the players are separated by only two degrees, is there a way to make this completely variable length?
MATCH
(p:Person {name: "Andrew"})-->(e:Employer)<--(p3:Person)-->(e2:Employer)<--(p2:Person {name: "Evan"})
RETURN *

A: You want variable-length pattern matching.
Depending on your graph you can define the relationships to traverse or leave off the type. We can omit the direction to specify that we don't care about the direction of relationships to traverse:
MATCH path = (p:Person {name: "Andrew"})-[:WorksFor*]-(p2:Person {name: "Evan"})
RETURN path

If you want the nodes in the path, you can return nodes(path) to get that list.
If you only want the shortest path between these two, you can match to both then match using the shortestPath function:
MATCH (p:Person {name: "Andrew"}), (p2:Person {name: "Evan"})
MATCH path = shortestPath((p)-[:WorksFor*]-(p2))
RETURN path


text:
Q: When will Raj and Vikram meet? Here's a fun little question I encountered along one of my many mathematical adventures:

Raj and Vikram are two travelers in ancient India, walking along the Silk road. On the first day of travel, Raj travels 5 yojanas, and on each successive day travels 3 yojanas more than the previous day. Vikram started at the same place and travels the same path, but started 5 days earlier, and travels 7 yojanas a day. On which day of Raj's travel will the two of them meet?
Details and assumptions:
  A yojana is an ancient Indian unit of measure.
  The silk road does not cross itself. Raj and Vikram will meet only if they have travelled the same distance. If they meet at any point on the 123rd day (say at 12:34pm), then your answer is that they meet on the 123rd day.

My approach:
Let us first consider Raj.
From the question, Raj covers an initial 5 yojanas and covers 3 yojanas per each succeeding day.
The total distance covered by Raj can be considered as an Arithmetic Progression,
$$ 5,\space 8,\space 11,\space 14,\space 17,\space 20,\space 23,\space ...$$
Let the the initial distance be $a$, the constant addition of distance be $d$ and let total distance be $a_n$ on the $n^{th}$ day,
$$\implies a_n = a + (n-1)\cdot d $$
Since $a = 5$ and $d = 3$,
$$\implies a_n= 5+(n-1)\cdot 3 = 3n + 2$$
So, on the $n^{th}$ day Raj meets Vikram at a distance of $3n+2$ yojanas.
Now let's consider Vikram.
Vikram started 5 days prior to when Raj started his journey and on each day he traveled 7 yojanas. Let the total distance traveled by Vikram be $x$.
$$\implies x = \frac{7 \text{ yojanas}}{1\text{ days}} * 5 \text{days} = 35 \text{ yojanas}$$
So, for Raj to get to that distance,
$$\implies 3n+2 = 35$$ $$\implies n = \frac{35 - 2}{3} = 11$$
Thus, Raj and Vikram meet on the $11^{th} \text{ day}$.

But the provided answer is the $7^{th}$ day. Where have I gone wrong? Is there an error in my logic? and most importantly, is there a faster way of doing this question?

A: You forgot to consider their total distance traveled, and also interpreted the statement "Vikram started ... 5 days earlier" differently than the author intended.
You are correct that the distance Raj travels each day can be represented as an arithmetic progression, namely $a_n = 2 + 3 n$.
However, the total distance Raj has covered at the end of the $n$-th day is $$ R_n = \sum_{k = 1}^n a_k = 2 \sum_{k = 1}^n 1 + 3 \sum_{k = 1}^n k = 2 n + 3 \cdot \frac{1}{2} n (n + 1) = \frac{1}{2} n (7 + 3 n). $$
On the contrary, at the end of the first day of Raj's travels, Vikram has already traveled $7 \cdot 6 = 42$ yojana; then $7$ each day afterwards. The total distance Vikram has traveled on the $n$-th day of Raj's travels is thus $$ V_n = 42 + 7 \cdot (n - 1) = 35 + 7 n. $$
These can be listed as
$$ R_n = 5, 13, 24, 38, 55, 75, 98, \ldots $$
$$ V_n = 42, 49, 56, 63, 70, 77, 84, \ldots $$
Thus we can see that at the end of the $6$th day of Raj's travels, Raj has traveled $75$ yojanas, while Vikram has traveled $77$ yojanas. Thus they will meet up on the $7$th day.

A: Just to put another approach out there...
Simply consider the relative pace of Raj and Vikram. After the 0th day, Vikram has traveled 35, which is the total distance Raj will have to make up. This is when Raj starts traveling, and his relative pace to Vikram can be written:
$-2, 1, 4, 7, 10, 13, 16, ... $

The distance that Raj makes up can be written as $\sum_{n=1}^{N}{-2 + 3(n-1)} = -2N + 3N(N-1)$. Setting this equal to 35, we get $N = \frac{7+\sqrt{49 + 3*4*70}}{6} \approx 6.13$. And if we round up, we get 7. I think this is correct.


text:
Q: Active page on top of menu I have a language switcher, but the active language is not in the top but its always English, how to make so that the currently chosen language is at top of the menu?

        Actuall language:
        ENGLISH

GERMAN

LATVIEŠU

RUSSIAN

A: i think tou have to use as
<select>
<option>GERMAN</option>
<option selected >LATVIEŠU</option>
<option>RUSSIAN</option>
</select>


text:
Q: Cakephp 3.9 Multiple Associations with the Same Table I am working on Cakephp 3.9 and I have 3 tables in my application.
CREATE TABLE `leads` (
 `id` int(10) NOT NULL AUTO_INCREMENT,
 `first_name` varchar(100) NOT NULL,
 `last_name` varchar(100) NOT NULL,
 `created_dt` datetime NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1

CREATE TABLE `clients` (
 `id` int(10) NOT NULL AUTO_INCREMENT,
 `lead_id` int(10) NOT NULL,
 `first_name` varchar(100) NOT NULL,
 `last_name` varchar(100) NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1

CREATE TABLE `contacts` (
 `id` int(10) NOT NULL AUTO_INCREMENT,
 `lead_id` int(10) NOT NULL,
 `first_name` varchar(100) NOT NULL,
 `last_name` varchar(100) NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1

There is a one-to-one relation between the Leads, Clients, and Contacts tables.
I also have a Users table:
CREATE TABLE `users` (
 `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
 `username` varchar(50) DEFAULT NULL,
 `password` varchar(255) DEFAULT NULL,
 `created` datetime DEFAULT NULL,
 `modified` datetime DEFAULT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1

... and a leads_users table
CREATE TABLE `leads_users` (
 `lead_id` int(10) NOT NULL,
 `user_id` int(10) NOT NULL,
 `user_type` enum('Opener','Closer') NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin

In my application, the users can be associated with the leads as Openers and Closers. There can be multiple openers and multiple closers for a lead. I have defined my models as below:
class LeadsTable extends Table
{
    public function initialize(array $config)
    {
        $this->hasOne('Contacts');

        $this->hasOne('Clients');

        $this->belongsToMany('Users', [
            'className' => 'Users'
        ])
            ->setConditions(['LeadsUsers.user_type' => 'Opener'])
            ->setProperty('openers');

        $this->belongsToMany('Users', [
            'className' => 'Users'
        ])
            ->setConditions(['LeadsUsers.user_type' => 'Closer'])
            ->setProperty('closers');
    }
}

class ClientsTable extends Table
{
    public function initialize(array $config)
    {
        $this->belongsTo('Leads');
    }

}

class ContactsTable extends Table
{
    public function initialize(array $config)
    {
        $this->belongsTo('Leads');
    }

}

class UsersTable extends Table
{
    public function initialize(array $config)
    {
        $this->belongsToMany('Leads');
    }

}

Now in the Leads controller, I am trying to find all the leads, their contacts, clients, openers, and closers by using the below line of code.
$result = $this->Leads->find('all')->contain(['Contacts', 'Clients', 'Users']);

With this, I am getting the closers but not the openers. In the LeadsTable, if I comment out the closers association then I am getting the openers. So looks like the second association is overwriting the first one.
If I change the LeadsTable association to below:
class LeadsTable extends Table
{
    public function initialize(array $config)
    {
        $this->hasOne('Contacts');

        $this->hasOne('Clients');

        $this->belongsToMany('Openers', [
            'className' => 'Users'
        ])
            ->setConditions(['LeadsUsers.user_type' => 'Opener'])
            ->setProperty('openers');

        $this->belongsToMany('Closers', [
            'className' => 'Users'
        ])
            ->setConditions(['LeadsUsers.user_type' => 'Closer'])
            ->setProperty('closers');
    }

}

I am getting the below error:

The Users association is not defined on Leads.

Please let me know what am I doing wrong.
Thank you in advance.

A: You're getting this error because you have to change your controller query as well.
$result = $this->Leads->find('all')->contain(['Contacts', 'Clients', 'Closers','Openers']);

A: So I ended up changing my database a bit and that fixed it.
CREATE TABLE `leads_openers` (
 `id` int(10) NOT NULL AUTO_INCREMENT,
 `lead_id` int(10) NOT NULL,
 `opener_id` int(10) NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1

CREATE TABLE `leads_closers` (
 `id` int(10) NOT NULL AUTO_INCREMENT,
 `lead_id` int(10) NOT NULL,
 `closer_id` int(10) NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1

and then I changed my models like below:
<?php

namespace App\Model\Table;

use Cake\ORM\Table;

class OpenersTable extends Table
{
    public function initialize(array $config)
    {
        $this->setTable('users');
        $this->setPrimaryKey('id');

        $this->belongsToMany('Leads', [
            'joinTable' => 'leads_openers',
        ]);
    }
}

<?php

namespace App\Model\Table;

use Cake\ORM\Table;

class ClosersTable extends Table
{
    public function initialize(array $config)
    {
        $this->setTable('users');
        $this->setPrimaryKey('id');

        $this->belongsToMany('Leads', [
            'joinTable' => 'leads_closers',
        ]);
    }
}

<?php

namespace App\Model\Table;

use Cake\ORM\Table;

class LeadsTable extends Table
{
    public function initialize(array $config)
    {
        $this->addBehavior('Timestamp');

        $this->belongsToMany('Openers', [
            'joinTable' => 'leads_openers',
        ])
            ->setProperty('openers');

        $this->belongsToMany('Closers', [
            'joinTable' => 'leads_closers',
        ])
            ->setProperty('closers');
    }
}

and then in the controller, I am doing this:
$leads = $this->Leads->find('all')
                ->where(['Leads.status IN' => $search_condition_lead])
                ->contain(['Contacts', 'Openers', 'Closers']);


text:
Q: How to get OpenCV wasm face detector on React In react, need the following to be downloaded only on demand and how to achieve the same.
       wasmBinaryFile: 'https://huningxin.github.io/opencv.js/build/wasm/opencv_js.wasm',
      preRun: [function() {
        Module.FS_createPreloadedFile('/', 'haarcascade_frontalface_default.xml', 'https://raw.githubusercontent.com/opencv/opencv/master/data/haarcascades/haarcascade_frontalface_default.xml', true, false);
      }],
      _main: function() {opencvIsReady();}
    };

Here is the simple javascript code for the same - https://codesandbox.io/s/wasm-face-detector-12w0gd?file=/index.html


text:
Q: The original question says : Prove that $19\mid(2^{(2^{(6n+2)})}+3)$ $\forall$ $n \in N_0.$ I simplified the problem as writing it first as $2^{2^{6n+2}}+3\equiv 0(mod 19)$ finally ending till $2^{2^{6n+2}}\equiv 2^4(mod 19)$.I cannot figure out how to deal with the exponents with the same base on both sides of the congruence.

A: By Fermat's little theorem,
$2^{18}\equiv 1\pmod{19}$.
So $2^{18k+4}\equiv 2^4\equiv -3\pmod{19}$ for any integer $k$. You can check that $18$ is the multiplicative order of $2$ although actually we don't need it.
Now, we want to find the residue of $4^{3n+1}$ modulo $18$.
$4^{3n+1}\equiv 64^n\cdot 4\equiv 10^n\cdot 4\pmod{18}$
You can check regardless of whether $n$ is even or odd, $4^{3n+1}\equiv 4\pmod{18}$.
So $2^{4^{3n+1}}+3\equiv 2^{18k+4}+3\equiv 2^4+3\equiv 0\pmod{19}$.


text:
Q: AlertDialog not closing when ok button is clicked- C# xamarin
Hi all having two buttons in a listview . when i click the reject button Alertdialog will come and there i have to enter reason .. after entering the reason on OK click AlertDialog should dismiss .
every thing is saved to DB ..but alert dialog is not closing ... instead after entering three times its closed .. i have attcahed my code below .
      btnReject.Click += delegate
            {
                var currentItem = item;
                Console.WriteLine(position);

                AlertDialog.Builder alert = new AlertDialog.Builder(this.context);
                LayoutInflater inflater = Application.Context.GetSystemService(Context.LayoutInflaterService) as LayoutInflater;
                View viewdialog = inflater.Inflate(Resource.Layout.RejectJobsAlertDialog, null);
                EditText getreason = viewdialog.FindViewById<EditText>(Resource.Id.Reason);
                alert.SetTitle("Reject Reason ");
                alert.SetView(viewdialog);
                alert.SetPositiveButton("Ok", (senderAlert, args) =>
                {

                    item.RejectedReason = getreason.Text;
                    sharedasproxy.MobileJobdetailsUpdate(item, BASE_URL + "/xxxxx");
                    Toast.MakeText(this.context, "success!", ToastLength.Short).Show();
                    btnReject.Visibility = ViewStates.Invisible;
                    btnAccept.Visibility = ViewStates.Visible;

                    dialog.Cancel();
                });

                alert.SetNegativeButton("Cancel", (senderAlert, args) =>
                {
                    Toast.MakeText(this.context, "Cancelled!", ToastLength.Short).Show();
                    CloseDialog();
                });

                dialog = alert.Create();

                dialog.Show();

            };

A: *

*Make sure, the button click event is not attached multiple times.

*Instead of writing delegate, call a method in the click event.

Try something like below,
 if (!btnReject.HasOnClickListeners)
    {

btnReject.Click += delegate
            {
                var currentItem = item;

                AlertDialog.Builder alert = new AlertDialog.Builder(this.context);
                LayoutInflater inflater = Application.Context.GetSystemService(Context.LayoutInflaterService) as LayoutInflater;
                View viewdialog = inflater.Inflate(Resource.Layout.RejectJobsAlertDialog, null);
                EditText getreason = viewdialog.FindViewById<EditText>(Resource.Id.Reason);
                alert.SetTitle("Reject Reason ");
                alert.SetView(viewdialog);
                alert.SetPositiveButton("Ok", (senderAlert, args) =>
                {

                    item.RejectedReason = getreason.Text;
                    sharedasproxy.MobileJobdetailsUpdate(item, BASE_URL + "/xxxxx");
                    Toast.MakeText(this.context, "success!", ToastLength.Short).Show();
                    btnReject.Visibility = ViewStates.Invisible;
                    btnAccept.Visibility = ViewStates.Visible;
                    dialog.Cancel();
                });

                alert.SetNegativeButton("Cancel", (senderAlert, args) =>
                {
                    Toast.MakeText(this.context, "Cancelled!", ToastLength.Short).Show();
                    CloseDialog();
                });

                dialog = alert.Create();
                dialog.Show();

            };
}


text:
Q: Is it possible to use two different strokestyles on same path in canvas? Is it possible to create a path in canvas of which the lines are stroked differently? For example so you could draw a box being green on the inside, with 4 different colored edges. I've included some code, but that does not work, because it draws the path twice (first time unfinished path, second time the whole path).
JavaScript
window.onload = function()
{
    canvas = document.getElementById("canvas1");
    if (canvas.getContext)
    {
        ctx = canvas.getContext("2d");
        ctx.beginPath();
        ctx.save();
        ctx.moveTo(0, 0);
        ctx.strokeStyle = "rgb(255, 0, 0)";
        ctx.lineTo(100, 100);
        ctx.stroke();
        ctx.strokeStyle = "rgb(0, 0, 255)";
        ctx.lineTo(200, 100);
        ctx.stroke();
        ctx.restore();
    }
}

HTML
<canvas id = "canvas1" width = "400" height = "400">
    Your browser does not support the HTML5 canvas tag.
</canvas>

A: I think you'll have to use two paths.
    ctx = canvas.getContext("2d");
    ctx.beginPath();
    ctx.moveTo(0, 0);
    ctx.lineTo(100, 100);
    ctx.strokeStyle = "rgb(255, 0, 0)";
    ctx.stroke();
    ctx.beginPath();
    ctx.moveTo(100, 100);
    ctx.lineTo(200, 100);
    ctx.strokeStyle = "rgb(0, 0, 255)";
    ctx.stroke();


text:
Q: How to share links to different pages on iframe? I have an iframe tab which holds php page with various links inside (like "News", "Photos" etc.). Is it possible to generate a facebook link which leads directly to certain link inside the iframe? By facebook link I mean link that will keep you on facebook, open your iframe tab and view certain page on that iframe. The thing is that all I can do now is to link only to my iframe tab which has address like http://www.facebook.com/mypage/app_someid. Then I will land on my default page tab url. But I want to land on different one. Any tips on this one?

A: Passing an app_data parameter to the tab URL is passed back to your application as part of the signed_request parameter  in FB's post call to include your content. Use that parameter after de-signing it to then decide what to show and what not to.
Your URLs will become like:

http://www.facebook.com/mypage/app_someid?app_data=showViewX
  http://www.facebook.com/mypage/app_someid?app_data=showViewY

and then in your code:
// Get Signed Request
$app_data = $signed_request['app_data'];
if($app_data === "showViewX") {
  // Show one view
} else {
  // show others..
}

Currently, the app_data param is not sent if the user just liked the page when he lands on it with an app_data param. The bug on FB has been filed at https://developers.facebook.com/bugs/172963266154996 and we are all hoping for an early resolution.


text:
Q: How to Make Button Merge with Border (Image Attached) I would like to make box like this image
With The Following Requirement:

*

*The Button Is Still in Border Line

*Height is Fixed, So All The boxes Height is the same
EDIT: My Last Tried Code
CSS
.catalog {
    border: 2px solid #f0bf3c;
    height: 600px;
    width: 350px;
    margin-bottom: 65px;
    float: left;
    margin-right: 25px;
}
.read-more {
    font-family: trickpony;
    height: 34px;
    padding: 9px 30px;
    background-color: #f0bf3c;
    border-radius: 4px;
    text-decoration: none;
    color: black;
    margin-left: 40px;
    margin-top: 78px;
    position: absolute;
}

HTML

Header Title
Header Title

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam suscipit condimentum gravida. Aliquam erat volutpat. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Sed nec diam luctus, fringilla massa quis, pharetra est. Sed semper rhoncus turpis, id ullamcorper est facilisis vel. Mauris bibendum nisi sit amet pellentesque dignissim. Mauris at elit luctus, placerat sem ut, faucibus ante. Curabitur fringilla metus vel lobortis elementum. Nullam id sagittis ligula. Morbi volutpat mauris ut nunc consectetur, in mollis massa feugiat.

        Read More

Thank You Very Much..
PS: I already tried with top, and left property but it just moved when the text is not the same as first boxes..

A: Hope this is what you want to achieve:

    .catalog {
        border: 2px solid #f0bf3c;
        height: 600px;
        width: 350px;
        margin-bottom: 65px;
        float: left;
        margin-right: 25px;
        position: relative; /* to use position: absolute on .read-more */
    }

    .read-more {
        font-family: trickpony;
        height: 34px;
        line-height: 34px; /* to center text vertically */
        padding: 0 30px; /*remove top/bottom padding to keep the height of 34px */
        background-color: #f0bf3c;
        border-radius: 4px;
        text-decoration: none;
        color: black;
        position: absolute; /* relative to catalog (position: relative) */
        bottom: -17px; /* half height (34px) */
        right: 20px;
    }

Header Title
Header Title

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam suscipit condimentum gravida. Aliquam erat volutpat. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Sed nec diam luctus, fringilla massa quis, pharetra est. Sed semper rhoncus turpis, id ullamcorper est facilisis vel. Mauris bibendum nisi sit amet pellentesque dignissim. Mauris at elit luctus, placerat sem ut, faucibus ante. Curabitur fringilla metus vel lobortis elementum. Nullam id sagittis ligula. Morbi volutpat mauris ut nunc consectetur, in mollis massa feugiat.

        Read More

A: *

*First you need to set position: relative; to .catalog so that
the absolute button will not get out of the .catalog

*Set bottom and right for the .read-more

*You can remove unwanted css of .read-more, I have commented that
unwanted code

.catalog {
    border: 2px solid #f0bf3c;
    height: 600px;
    width: 350px;
    margin-bottom: 65px;
    float: left;
    margin-right: 25px;
    position: relative;
}
.read-more {
    font-family: trickpony;
    /* height: 34px; */
    padding: 9px 30px;
    background-color: #f0bf3c;
    border-radius: 4px;
    text-decoration: none;
    color: black;
    /* margin-left: 40px; */
    /* margin-top: 78px; */
    position: absolute;
    bottom: -17px;
    right: 10px;
}

Header Title
Header Title

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam suscipit condimentum gravida. Aliquam erat volutpat. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Sed nec diam luctus, fringilla massa quis, pharetra est. Sed semper rhoncus turpis, id ullamcorper est facilisis vel. Mauris bibendum nisi sit amet pellentesque dignissim. Mauris at elit luctus, placerat sem ut, faucibus ante. Curabitur fringilla metus vel lobortis elementum. Nullam id sagittis ligula. Morbi volutpat mauris ut nunc consectetur, in mollis massa feugiat.

        Read More


text:
Q: Ember-data model relationships with array I am having a hard time to understand how the model relationships works in ember-data. I understand the concept one to many or one to one or many to many, but I don't understand how to use it properly..
My API is sending me this data :
{
    gameweek: [
        {
          commonID: '23',
          content: 'blablabla',
          game: [
              {
                   commonID: '23',
                   gameID: 4,
                   title: 'first game'
              },
              {
                   commonID: '23',
                   gameID: 8,
                   title: 'second game'
              }
          ]
        },
        {
          commonID: '24',
          content: 'blebleble'
          game: [
              {
                   commonID: '24',
                   gameID: 12,
                   title: 'another game'
              }
          ]
        }
    ]
}

As you can see I receive an array that contain some data and an other array.
I don't really know if how I should create my models, should I have just one model ? or multiple like this ? (correct me if its wrong) :
//gameweek.js
import DS from "ember-data";

export default DS.Model.extend({
    commonID:       DS.attr('string'),
    title:          DS.attr('string'),
    games:          DS.hasMany('game')
});

//game.js
import DS from "ember-data";

export default DS.Model.extend({
    commonID:         DS.attr('string'),
    title:            DS.attr('string'),
    gameweek:         DS.belongsTo('gameweek')
});

I would like to be able to save my arrays in the store and keep the relationships between them.
If I do a this.store.find('gameweek', {commonID: '23'} ); I would like to get also all of the game that are related the gameweek. (the commonID would be the same if they are related).
Do I have to create a custom serializer ?
So many questions, thanks for you help !
=============================
UPDATE :
I tried to extend the DS.RESTSerializer like this :
export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
    extractArray: function( store, type, record ) {
        var gameweek = record.predictions;
        gameweek.forEach(function( entry ) {
            var data = entry.games.map(function(game) {
                return game.gameID;
            });
            entry.games = data;
        });
        record = { prediction: gameweek };
        return this._super( store, type, record );
    }
});

This is mainly replacing my game array by an array of gameID, the new array looks like this :
{
        gameweek: [
            {
              commonID: '23',
              content: 'blablabla',
              game: ["4", "8"]
            },
            {
              commonID: '24',
              content: 'blebleble'
              game: ["12"]
            }
        ]
    }

But I get this error :
Error: Assertion Failed: Unable to find transform for 'integer'
I am not sure what to do here.
===================================
UPDATE2:
I tried this too :
//serializers/gameweek.js

import DS from "ember-data";

export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
    primaryKey: 'gameWeekID',
    attrs: {
       game: { embedded: 'load' }
    },
    extractArray: function( store, type, record ) {
        // The array of object isn't at the root structure of the record
        var record = record.predictions;
        record = { prediction: record };
        return this._super( store, type, record );
    }
});

//serializers/game.js
import DS from "ember-data";

export default DS.RESTSerializer.extend({
    primaryKey: 'gameID'
});

I got this error :
Error: Assertion Failed: Ember Data expected a number or string to represent the record(s) in the "games" relationship instead it found an object. If this is a polymorphic relationship please specify a "type" key. If this is an embedded relationship please include the "DS.EmbeddedRecordsMixin" and specify the "games" property in your serializer's attrs object.

A: In ember you dont save arrays as models you save objects as models. Ember data expects data back in a certain way so you will need to either do this server side or do it with a serializer.
You can save relationships no problem if your models are set clearly.
In the code below taken from embers site your model is a post. so when you query for a post this is what should be returned. The post has a relationship with comments. posts have many comments and comments belong to posts. In the post model there is the id for each comment that is related to that post and then the comments are included as a separate array. http://guides.emberjs.com/v1.12.0/models/the-rest-adapter/#toc_sideloaded-relationships
{
  "post": {
    "id": 1,
    "title": "Node is not omakase",
    "comments": [1, 2, 3]
  },

  "comments": [{
    "id": 1,
    "body": "But is it _lightweight_ omakase?"
  },
  {
    "id": 2,
    "body": "I for one welcome our new omakase overlords"
  },
  {
    "id": 3,
    "body": "Put me on the fast track to a delicious dinner"
  }]
}

The related model files for the above structure are
app/models/post.js
export default DS.Model.extend({
  title: DS.attr('string'),
  comments: DS.hasMany('comment')
});

app/models/comment.js
export default DS.Model.extend({
  body: DS.attr('string'),
  post: DS.belongsTo('post')
});

I dont know if its just my head or its the end of the day but the above naming and structure layout is very confusing. Can you include a bit more detail or make the details less generic, it might help with trying to figure the data out.

A: You should have separate models for gameweek and game. Ember Data works better with more granular models, rather than trying to deal with model fields which are raw objects. This will make it easy to extend the game model in the future with additional functionality, such as computed properties and validators. So your proposed model structure is fine.
To make this work with your current JSON structure, however, you're going to have to declare that game is embedded. To do that
// serializers/gameweek.js
import ApplicationSerializer from './application';
import DS from 'ember-data';
export default ApplicationSerializer.extend(DS.EmbeddedRecordsMixin, {
    attrs: {
        games: { embedded: 'load' }
    }
});

We inherit from ApplicationSerializer as best practice so that if it specifies things they are inherited by this model-specific serializer.
In addition, Ember Data is going to insist on a unique id for each game, so it has a way to identify it in the store. If gameId is unique, you can use that as is, but you'll have to let Ember Data know, by saying
// serializers/game.js
import ApplicationSerializer from './application';
import DS from 'ember-data';
export default ApplicationSerializer.extend({
    primaryKey: 'gameId'
});

Once you do this, you will no longer refer to the id as gameId; you will refer to it as id, and you do not need to, and should not, declare it as part of your model.


text:
Q: jQuery - how to make a horizontal splitter to be shown at a middle even when the screen been re-sized first of all I'm using this plugin - jQuery Splitter .
Now what I'm trying to do is to make the splitter been shown at the middle also when the height of the screen had changed.
In order to do so I've used the next code -

    <title></title>

    <link href="jquery.splitter.css" rel="stylesheet" />

                    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla sed dolor nisl, in suscipit justo. Donec a enim et est porttitor semper at vitae augue. Proin at nulla at dui mattis mattis. Nam a volutpat ante. Aliquam consequat dui eu sem convallis ullamcorper.

            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla sed dolor nisl, in suscipit justo. Donec a enim et est porttitor semper at vitae augue. Proin at nulla at dui mattis mattis. Nam a volutpat ante. Aliquam consequat dui eu sem convallis ullamcorper. Nulla suscipit, massa vitae suscipit ornare, tellus est consequat nunc, quis blandit elit odio eu arcu. Nam a urna nec nisl varius sodales. Mauris iaculis tincidunt orci id commodo. Aliquam non magna quis tortor malesuada aliquam eget ut lacus. Nam ut vestibulum est. Praesent volutpat tellus in eros dapibus elementum. Nam laoreet risus non nulla mollis ac luctus felis dapibus. Pellentesque mattis elementum augue non sollicitudin. Nullam lobortis fermentum elit ac mollis. Nam ac varius risus. Cras faucibus euismod nulla, ac auctor diam rutrum sit amet. Nulla vel odio erat, ac mattis enim.

Currently, if let's say I moved the splitter to a cretin position and then I've changed the screen height, the splitter stays at it's position.
Any idea what am I doing wrong? Or maybe what can I do in order to make it work?
Thanks in advance for any kind of help.

A: Your code looks OK.
You can try this, though it's more of a tidy-up than a fix.
jQuery(function($) {
    $(window).on('resize', function() {
        var height = $(window).height();
        console.log(height);
        $('#foo').height(height).split({ orientation:'horizontal', limit:50 });
        $('#b').height(height / 2);
    }).trigger('resize');
});

If it works initially but not after a resize, then you have to conclude that splitter can't be re-invoked. Maybe apply to the author for an improvement or find a way to destroy splitter before re-invoking.


text:
Q: I am finding it difficult to do relative Import in Django application I am relatively new to django and am finding it difficult to do basic module referencing.
Even thou I have searched through couple of links I still don't get it.
I have been here: Relative Import For the Billionth Time and I still don't get it
Here is my folder structure
main
main/main
main/main/urls.py
main/sub_main
main/sub_main/views.py

In my urls module I have a line
from ..sub_main import views

However, I keep getting the error: ImportError: attempted relative import beyond top-level package
Is there something am missing?


text:
Q: Java: If statement not producing result that I am expecting for simple user authentication When running below program I'm thinking that it should print out "Authentication successful" if I input
"john smith" as user name and "12345" as userID, but instead it just comes back with "Authentication failed". I am calling this method in the Main class. Any suggestions?
package com.company;

import java.util.Scanner;

public class Account {

    public String userNameInput;
    public String userIDInput;
    public String userName = "john smith";
    public String userID = "12345";

    public void userDetails(){
        Scanner userInput = new Scanner(System.in);

        System.out.println("Please enter user name:");
        userNameInput = userInput.next().toLowerCase();

        System.out.println("Please enter user ID:");
        userIDInput = userInput.next();

        if(userNameInput.equals(userName) && userIDInput.equals(userID)){
            System.out.println("Authentication successful");
        } else{
            System.out.println("Authentication failed!!");
        }

    }
}

A: Change next() to nextLine() in userNameInput = userInput.nextLine().toLowerCase();

package com.company;

import java.util.Scanner;

public class Account {

    public String userNameInput;
    public String userIDInput;
    public String userName = "john smith";
    public String userID = "12345";

    public void userDetails(){
        Scanner userInput = new Scanner(System.in);

        System.out.println("Please enter user name:");
        userNameInput = userInput.nextLine().toLowerCase();

        System.out.println("Please enter user ID:");
        userIDInput = userInput.next();

        if(userNameInput.equals(userName) && userIDInput.equals(userID)){
            System.out.println("Authentication successful");
        } else{
            System.out.println("Authentication failed!!");
        }

    }
}


text:
Q: Spring 4 java configuration, separated wars for front/backend, setting home page for localhost:port/myAppsName/ I am currently working on a project which is separated into frontend (html5, jquery, css) and backend (Spring4 mvc with java config -no web.xml-, exposing rest for the view to consume it), each of which has its own pom that depends on the same parent pom.
Project's tree structure
When I compile the main project, 2 wars are generated (front and backend), which I later deploy in tomcat 7.
Backend is working fine (i've already tested it with psotman) and frontend works fine also if I open the html from outside tomcat (when I open index.html from a folder on my computer). However when I deploy the frontend war together with te backend war in tomcat and enter "localhost:8080/myAppsName/", http eror 404 is thrown. I understand that the html can't be found in order to render the index page.
frontend tree structure
Backend AppConfig.java:
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "org.fedelaper.spring")
public class AppConfig {

    @Bean
    public ViewResolver internalResourceViewResolver() {
        InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver();
        internalResourceViewResolver.setPrefix("/frontend/");
        internalResourceViewResolver.setSuffix(".html");
        return internalResourceViewResolver;
    }

}

Backend AppInitializer.java:
    @SuppressWarnings("unchecked")
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @SuppressWarnings("rawtypes")
    @Override
    protected Class[] getRootConfigClasses() {
        return new Class[] { AppConfig.class };
    }

    @SuppressWarnings("rawtypes")
    @Override
    protected Class[] getServletConfigClasses() {
        return null;
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }

}

I DO have a web.xml in project frontend which is actually empty:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

</web-app>

My question is:
- How should I set index.html to be the default home page of my app when entering localhost:8080/myAppsName?

A: Just update your frontend modules web.xml file with welcome-file-list.
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<welcome-file-list>
    <welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>


text:
Q: How to retrieve the file previews used by windows explorer in Windows vista and seven? I am developing a Delphi documents management application, so somehow I am giving the user some functionality similar to windows explorer.
I would like to know if there is a way to get the preview used by windows explorer. For example windows explorer creates a small thumbnail for a pdf document for example, and displays it when the user chooses to view "big icons". Is there a way to retrieve that preview?
MyTImage := GiveMePreviewForFile('C:\Test\File.pdf');

A: @user193655, using the IExtractImage  interface is the way to go, this interface exposes methods that request a thumbnail image from a Shell folder
you can find a very complete sample in this site and the source code is here.
check this image

A: Take a look at the docs for IExtractImage.  Basically you use IShellFolder with IExtractImage to get the picture you are looking for.


text:
Q: How to fix module fuse not found error? I used to be able to mount a NTFS formatted drive (read only) on my Ubuntu Linux (9.04) Sheevaplug. I was chasing the impossible dream of being able to mount it for both read and write and somehow messed up my computer system. Now I can't even get it mounted read only:
root@debian:~# modprobe fuse
FATAL: Module fuse not found.
root@debian:~# mount /dev/sda1 /mnt/drobo/
FATAL: Module fuse not found.
fuse: device not found, try 'modprobe fuse' first

How can I get it working again? I'm new to Linux.

A: FUSE is required by the ntfs-3g driver, and should be in the repositories.
To revert to the kernel ntfs driver, use mount -t ntfs or remove the ntfs-3g package entirely.


text:
Q: \pgfplotsset{compat=1.17} not working despite texlive newest version (2019.20200218-1) My system is Ubuntu 20.04 and I am trying to compile a LaTeX file with newer tikz features
\usepackage{tikz}
\usepackage{pgfplots}
\pgfplotsset{compat=1.17}

but it complains with

! Package pgfplots Error: Sorry, 'compat=1.17' is unknown in this
context. Please use at most 'compat=1.16'.

and if I ignore this then it compiles but is missing certain plots.
If I change the line to
\pgfplotsset{compat=1.16}
then it does not compile at all, tons of errors.
My question: How do I get pgfplots version 1.17?
I clearly only have version 1.16 on my system,
because
/usr/share/doc/texlive-doc/latex/pgfplots/pgfplots.pdf
starts with Manual for Package pgfplots 2D/3D Plots in LATEX, Version 1.16
 sudo apt install texlive

tells me
texlive is already the newest version (2019.20200218-1).

and
 sudo apt install pgf

Package pgf is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source
E: Package 'pgf' has no installation candidate

and at
https://github.com/pgf-tikz/pgfplots
there are no installation instructions (I can clone the git repository alright) and it says helpfully
Please take a look at doc/latex/pgfplots/pgfplots.pdf and doc/latex/pgfplots/pgfplotstable.pdf.

but these files do not exist, not in
https://github.com/pgf-tikz/pgfplots/tree/master/doc/latex/pgfplots

or anywhere else in the repository.
I can try to upgrade to pgfplots 1.17 manually somehow, by copying the directories from the git repository to /usr/share/texlive/texmf-dist/, but would obviously prefer a proper and safer method.
Any help is appreciated.

A: Ubuntu 20.04:
θ64° [romano:~] % grep version $(kpsewhich pgfplots.revision.tex)
\gdef\pgfplotsversion{1.16}
\gdef\pgfplotsversiondatetime{2018-03-28 20:42:04 +0200}
\xdef\pgfplotsversiondate{\expandafter\pgfplots@glob@TMPa\pgfplotsversiondatetime\relax}

So the version that comes with Ubuntu 20.04 is 1.16
To install locally a new version: simply go to CTAN, download the *.tds.zip file, and unpack it under ~/texmf (if you didn't change your default TeX paths).


text:
Q: How to retrieve all registered email addresses in gmail? I use this method to get email addresses:
ContentResolver cr = SelectFile.this.getContentResolver();
            Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
            if (cur.getCount() > 0) {
                while (cur.moveToNext()) {
                    String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
                    Cursor cur1 = cr.query(
                            ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
                            ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
                            new String[]{id}, null);
                    while (cur1.moveToNext()) {
                        //to get the contact names
                        String name=cur1.getString(cur1.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                        String email = cur1.getString(cur1.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
                        ItemEmailSuggestion item = new ItemEmailSuggestion(email,name,id);
                        emailsContacts.add(item);
                        Log.i("CONTACTS",email+" "+name);
                    }
                    cur1.close();
                }
            }

(source Get only email address from contact list Android)
in order to propose a list of mail according to the input in an editText.
My implementation works, but the list of mail addresses obtained is much less provided compared to the mails registered in the Gmail application.
Why?
Of course permissions are granted correctly (READ_CONTACT).
I have unfortunately no more terminal under kitkat, but it seems to remember that this was not the case and that the list was comparable to that of Gmail.
Currently tested under android 21,22,23,24.
thank you in advance

A: Not all emails stored on the device belong to real contacts with names, you can try querying for all emails directly from the Emails table, and if that works, your can fill in names for those that have names in a second query.
        cr.query(Email.CONTENT_URI,null, null, null, null);
        if (cur.getCount() > 0) {
            while (cur.moveToNext()) {
              String email = cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
              Log.i("CONTACTS",email);
           }
           cur.close();
        }


text:
Q: Hive: how to get global ordering with sort by order by has only one reducer, so slow.I'm trying to find a fast way.sort by sorts in each reducer,then how can we get global ordering?
I got this by search engine:
select * from
(select title,cast(price as FLOAT) p from tablename
distribute by time
sort by p desc
limit 10 ) t
order by t.p desc
limit 10;

Then try to validate it.
1.Get right answer in my hive table.There are 215666 records in the table named tablename.
SELECT title,cast(price as FLOAT) p
from tablename
WHERE dt='2020-03-08'
and price IS NOT NULL
ORDER BY p DESC
LIMIT 10
;

2.Use the searched clause.
set hive.execution.engine=mr;
set mapred.reduce.tasks=5;
SELECT title,cast(price as FLOAT) p
from tablename
WHERE dt='2020-03-08'
and price IS NOT NULL
DISTRIBUTE BY title
SORT BY p desc
LIMIT 10
;

The result is the same as the right answer!
Here are my questions:
1.Why only return 10 lines? There are 5 reducer, each reducer returns 10, should be 5*10=50?
2.If should return 10 lines, why the result is global ordering? This 10 line is not from the same reducer ? The limit is random, it cannot get global order in 5 reducer.
3.If should return 10 lines, the outer part in the searched clause is redundant?
select * from
(
) t
order by t.p desc
limit 10;

A: Consider using total order partitioner, see https://cwiki.apache.org/confluence/display/Hive/HBaseBulkLoad#HBaseBulkLoad-PrepareRangePartitioning for details (just ignore part with HBase)


text:
Q: C# New Expression in LINQ I wrote a code and used LINQ for fun which shows Sum of even and odd numbers. My code is working well but i feel like i could do it much better than this
Click here for image.
        static void Main(string[] args)
    {

        Func<int, int, IEnumerable<int>> NumberRange =
            (startPoint, endPoint) =>
            Enumerable
            .Range(Math.Min(startPoint, endPoint), Math.Abs(startPoint - endPoint) + 1);

        Func<double, double, bool> IsDivisible =
            (value, divisor) =>
                (value % divisor)
                .Equals(0);

        Action<IEnumerable<object>> DisplayItems =
            (data) =>
            {
                Console
                    .WriteLine(String.Join(Environment.NewLine, data.Select(n => n)));
            };

        Func<bool, string> GetState =
            (key) =>
                key.Equals(true) ? "even" : "odd";

        var query =
            NumberRange(1, 20)
                .GroupBy(item => IsDivisible(item, 2))
                .Select(group => new
                {
                    Type = GetState(group.Key),
                    Sum = group.Sum()
                })
                .Select(group => new
                {
                    Output = string.Format("Sum of {0} numbers is {1}", group.Type, group.Sum)
                }
                .Output
                );

        DisplayItems(query);

        Console
            .Read();

    }

Is there any optimization for new expression ? Thanks.

A: Try this, it's simpler:
    static void Main(string[] args)
    {

        int startPoint = 0, endPoint = 20;

        List<int> data = new List<int>();
        int i = startPoint;
        while (i <= endPoint)
        {
            data.Add(i);
            i++;
        }
        Console.WriteLine(string.Format("Sum of even numbers is {0} \r\n", data.Where(x => x % 2 == 0).Sum().ToString()));

        Console.WriteLine(string.Format("Sum of odd numbers is {0} \r\n", data.Where(x => x % 2 != 0).Sum().ToString()));

        Console.ReadLine();
    }


text:
Q: Help to draw a dashed line in OpenGl I am trying to draw a dashed line in OpenGl using a texture equally spaced along the path as the dashes.  I can get a solid line, but that wont work for this project.
Could someone help point me in the right direction?

A: Dotted or dashed line in OpenGL is called stippled.
glPushAttrib(GL_ENABLE_BIT);
# glPushAttrib is done to return everything to normal after drawing

glLineStipple(1, 0xAAAA);  # [1]
glEnable(GL_LINE_STIPPLE);
glBegin(GL_LINES);
glVertex3f(-.5,.5,-.5);
glVertex3f(.5,.5,-.5);
glEnd();

glPopAttrib();

0xAAAA is the parameter you want to experiment with.
(Sourced from here)

A: The best way would be to use glBegin(GL_POINTS); and spread out the points in a linear fashion.

A: A dashed line is just a series of colinear line segments with gaps in between.  If you want texturing, you can emit a bunch of quads.  You can control the texture coordinates so that each dash is a piece of the texture, or each dash encompasses the whole texture, or any other repetition pattern you like.
What have you tried so far?  Show the code that's not working and the output graphic it creates.  Then explain what you want to be different.


text:
Q: Selenium waitForPageToLoad end condition I have a java selenium script where I am making a call to com.thoughtworks.selenium.DefaultSelenium.waitForPageToLoad(String). Which condition in the browser is selenium waiting for that will tell it that the page is done loading?

A: Selenium is waiting for a pageLoad event to be fired by the browser. If you look in the source for selenium, I think the logic for waitForPageToLoad can be found in selenium-browserbot.js.