text:
Q: Should a local class defined inside a method be thrown as Exception? It is possible to throw function local class as exception. Is this good or not?
My intention was to explain exception context over exception class type.
class A {
    void method1() throws IOException {
        class Method1IOException extends IOException {
        }
        throw new Method1IOException();
    }

    void method2() throws IOException{
        class Method2IOException extends IOException{
        }
        throw new Method2IOException();
    }
}

A: Assuming extends is a typo for throws in your method declarations here.
You cannot throw an Exception unknown within that scope, which would be the local scope of your method (vs the instance of your class A in this case).
So either your local Exceptions extend RuntimeException, or your throws clause must throw a general Exception (or Throwable).
Anyway, I wouldn't recommend this practice, unless you are never re-using the local Exception - and even then...
Context should be expressed programmatically within the message, and automatically within the stack trace, but in this case it will only add some noise to your stack trace.


text:
Q: Midpoints of Cevians In triangle $\triangle ABC$, $D$ and $E$ lie on sides $CA$ and $AB$ such that $BE = 6$ and $CD = 10$. Let $M$ and $N$ be the midpoints of segments $BD$ and $CE$, respectively. If $MN = 7$, then what is the measure of $\angle BAC$?
I'm not sure how to start this, I can't find any similar or parallel lines in the figure. I can construct the trapezoids but I do not know how to utilize them.

A: If $A=E=D$, then triangle $MAN$ has sides $3$, $5$ and $7$. From the cosine rule it follows that
$$
\cos\angle MAN={3^2+5^5-7^2\over 2\cdot 3\cdot 5}=-{1\over2},
\quad\text{that is:}\quad \angle MAN=\angle BAC=120°.
$$
This is a particular case, but the problem implies that the same solution must hold also in the general case.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Javascript localStorage replaces data instead of appending data to the existing ones I want to make new div's with localStorage. It is working good except when I reload the page and click again to the bag button, the div's which I have made previously get replaced by the new ones. I want it to add new div's after the previously added div's. Any answers will be appreciated!    Thank you so much!

var addtobagbtn = document.getElementsByClassName('ovla-addtobag');

var tles = document.getElementsByClassName('prod-title');

for ( i = 0; i <addtobagbtn.length; i++) {
    var button = addtobagbtn[i];

    button.addEventListener('click', function() {
        var button = event.target;
        var shopitem = button.parentElement.parentElement;

        var bagitems = document.getElementsByClassName('bagitems')[0];
        var imgsrc = shopitem.getElementsByClassName('prod-img')[0].src;

        appendbag();

        function add(imgsrc) {
        bagitems.insertAdjacentHTML("afterbegin",`

<button title="Remove From Bag" class="fas fa-times dltbag"></button>

Girlfriend Regular Jeans

H&M

$24.99

Dark denim blue

12

0706016003

<button class="far fa-heart movetofavbtn" title="Move To Bag"></button>Qty: <input type="number" value="1" name="indbagqty"title="Select Quantity" class="indbagqty bagrowfld" id="indbagqty">Total: <input type="text" title="Total Price" class="indbagtotalprice bagrowfld" name="indbagtotalprice" readonly>

    `)
}

function appendbag() {
    add(imgsrc);

    localStorage.setItem("getbag",JSON.stringify( bagitems.innerHTML));

}
    });

}
@import url('https://fonts.googleapis.com/css?family=Josefin+Sans|Muli|Noto+Sans+HK|Noto+Sans+SC|Quicksand|Sedgwick+Ave|Open+Sans+Condensed|Lato|Darker+Grotesque|Dosis|Roboto&display=swap');

*{
    padding:0;
    margin:0;
    box-sizing: border-box;

}
body{
    background-color: rgb(255, 255, 255);
    width:100%;
    margin:0;
    padding:0;
}

/*product patge wrapper*/

.signup-banner{
text-transform: uppercase;
position: relative;
padding:20px 0px;
background-color: rgb(211, 210, 210);
text-align: center;
font-family: 'Dosis',sans-serif;
text-emphasis: 10;
}
.banfrm{
    display:inline-block;
    margin:10px;
}

.banbtn{
    background-color: #1a1a1a;
    color:rgb(184, 184, 184);
    width:100px;
    height:30px;
    border:none;
    border-radius: 2px;
    -webkit-border-radius: 2px;
    -moz-border-radius: 2px;
    -ms-border-radius: 2px;
    -o-border-radius: 2px;
}

.prdpg-wrapper{
grid-area: pdwr;
display:grid;
grid-template-columns: repeat(5,1fr);
grid-template-areas:
"prodgrid prodgrid prodgrid prodgrid prodgrid"
;
}

/*product page wrapper ends*/

/*leftbar*/

.prdpg-lftbar::-webkit-scrollbar{
    width:2px;

}

.prdpg-lftbar::-webkit-scrollbar-thumb{
    background-color: #777777;
    border-radius: 2px 0px;
    -webkit-border-radius: 2px 0px;
    -moz-border-radius: 2px 0px;
    -ms-border-radius: 2px 0px;
    -o-border-radius: 2px 0px;
}

.prdpg-lftbar{
    position:fixed;
    padding:200px 10px 0px 30px;
    grid-area: lftbar;
    display:none;
    height:100%;
    background-color: #fff;
    z-index:1;
    top:60px;

}
.prdpg-lftbar:hover{
overflow:scroll;

}
.lftbarul{
    list-style:none;
}

.super-menuli-lftbar-title{
    font-family:'Dosis',sans-serif;
    font-weight: bold;
    font-size:14px;
  }

.super-menuli-lftbar{
    font-size:14px;
}

.super-lftbar-menua{
    text-decoration:none;
    color:rgb(59, 59, 59);
    font-family:'Dosis',sans-serif;
}
/*left bar ends*/

/*prod-grid*/

.prod-grid{
    grid-area: prodgrid;
    display:grid;/*
    grid-template-columns: repeat(auto-fit,minmax(200px,1fr));*/
    grid-template-columns: repeat(2,48%);
    grid-template-rows:auto;
    grid-auto-flow:row;
    grid-gap:10px;
    justify-content: center;
    align-items:center;

}

@media screen and (max-width:319px){
    .prod-grid{
    grid-template-columns: repeat(1,95%);
    }
}
@media screen and (min-width:768px){
    .prod-grid{
    grid-template-columns: repeat(3,33%);
    }
}
@media screen and (min-width:1024px){
    .prod-grid{
    grid-template-columns: repeat(4,24%);
    }
}

.prod-img{
    width:100%;
    cursor: pointer;
    width:100%;
}
.prod-card{
    width:100%;
    display:block;

}
.prod-head{
    position:relative;
}

 .prod-info{
    width:100%;
}

.prod-titlea{
    color:#1a1a1a;
    text-decoration:none;
}

.prod-titlea:hover{
color:#6a6a6a;
text-decoration: underline;
}

/*card design*/

.ovla-fav{
    outline:none;
    border:none;
    position:absolute;
    background-color: #fff;
    bottom:15px;
    right:15px;
    width:30px;
    height:30px;
    border-radius:50%;
    cursor:pointer;
    box-shadow: 0px 0px 4px #000;
    font-size:16px;color:#ed4956;

}

#fav-saved{

    position:absolute;
    top:9px;
    right:8px;
    z-index: -1;
    color: #ed4956;

}

.ovla-addtobag{
    outline:none;
    border:none;
    position:absolute;
    background-color: #fff;
    bottom:50px;
    right:15px;
    width:30px;
    height:30px;
    text-align: center;
    line-height:25px;
    border-radius:50%;
    cursor:pointer;
    color: #3a3a3a;
    box-shadow: 0px 0px 4px #000;
    font-size:16px;

    transition: visibility .1s ease;
    -webkit-transition: visibility .1s ease;
    -moz-transition: visibility .1s ease;
    -ms-transition: visibility .1s ease;
    -o-transition: visibility .1s ease;
}

.prod-img:hover ~ .ovla-addtobag{
visibility:visible;
}
.ovla-addtobag:hover{
    visibility:visible;
}

.prod-leg{
    position: relative;
    text-align:center;

}
.prod-title{
    font-family:'Dosis',sans-serif;
    font-size:1rem;
}
.prod-price{
    font-family:'Dosis',sans-serif;
}

/*prod hover elements*/

.fa-plus{
    position:absolute;
    top:11px;
    left:9px;
    color:#fff;
    font-size:.5rem;
}

.btmbtn{
    margin-top:15px;
    height:30px;
    width:50%;
    border:none;
    background-color: #1a1a1a;
    color:rgb(180, 180, 180);
    cursor:pointer;
    border-radius:2px;
    outline:none;
    font-family:'Dosis',sans-serif;
    text-align:center;
    line-height:30px;
    -webkit-border-radius:2px;
    -moz-border-radius:2px;
    -ms-border-radius:2px;
    -o-border-radius:2px;
}
.btmbtn:hover{
    background-color: #2a2a2a;
}
.btmbtn:active{
    background-color: #2a2a2a;
}

/*prod hover elements ends*/

/*card design ends*/

/*prod grid-ends*/

/*media queries*/
@media screen and (min-width:1024px){
    .ovla-addtobag{
        visibility:hidden;
    }
    .signup-banner{
        margin:20px 1px;
    padding:100px 200px;

        right:-20.5%;
        width:78.7%;
    }
    .prdpg-wrapper{
        display:grid;
        grid-template-columns: repeat(5,1fr);
        grid-template-areas:
        "lftbar prodgrid prodgrid prodgrid prodgrid"
        ;
        }

        .prdpg-lftbar{
            display:block;
        }
}

/*media queries ends*/

@import url('https://fonts.googleapis.com/css?family=Josefin+Sans|Muli|Noto+Sans+HK|Noto+Sans+SC|Quicksand|Sedgwick+Ave|Open+Sans+Condensed|Lato|Darker+Grotesque|Dosis|Roboto&display=swap');

*{
    padding:0;
    margin:0;
    box-sizing: border-box;

}
body{
    background-color: rgb(255, 255, 255);
    width:100%;
    margin:0;
    padding:0;
}

/*global variableglobal variableglobal variableglobal variableglobal variableglobal variableglobal variableglobal variableglobal variableglobal variableglobal variableglobal variableglobal variableglobal variableglobal variableglobal variableglobal variableglobal variableglobal variableglobal variableglobal variableglobal variableglobal variableglobal variableglobal variableglobal variableglobal variableglobal variableglobal variableglobal variableglobal variableglobal variableglobal variableglobal variableglobal variableglobal variableglobal variableglobal variableglobal variableglobal variableglobal variable*/

.bag-wrapper{
    position:relative;
    display:grid;
    grid-template-columns: 100%;
    grid-template-rows: auto;
    margin-left:1rem;

}

.bagpgtitle{
    width:100%;
    font-family: 'Dosis',sans-serif;
    text-align:center;
    font-size: 40px;
    font-weight:bolder;
    padding:20px;
}

.bagrow{
    display:grid;
    grid-template-columns: 1fr 2fr;
    grid-template-rows: 1fr .8fr;
    grid-template-areas:
    "baghd baghd"
    " bagleg bagleg"
    ;
    row-gap: 20px;
    width:100%;
    border-bottom:1px solid rgb(195, 195, 195);
    margin-top:20px;

}

.bagrowhead{
    grid-area:baghd;
    width:150px;
    position:relative;
    padding:5px;

}
.bagprdimg{
width:100%;
}

.bagprdtitle{
    font-weight:bold;

}
.dltbag{
    float:right;
    font-size:20px;
    padding:2px;
    background-color: #fff;
    color: #adadad;
    border:none;
    margin-top:2px;
    margin-right:5px;
    outline:none;
}
.dltbag:hover{

    color:#fd4141 ;
}
.movetofavbtn{
    border:none;
    font-size:1rem;
    padding:6px;
    background-color: #fff;
    outline:none;
    color:#ed4956;
    border-radius: 50%;
    -webkit-border-radius: 50%;
    -moz-border-radius: 50%;
    -ms-border-radius: 50%;
    -o-border-radius: 50%;
}

.movetofavbtn:hover{
    background-color: #ffcace;
}

.bagrowleg{
    grid-area:bagleg;
    font-family:'Dosis',sans-serif;
}

.indbagqty{
    width:60px;
    border:none;
    border-bottom:1px solid #ccc;
    font-family: 'Dosis',sans-serif;

}

.indbagtotalprice{
    border:none;
    border-bottom:1px solid #ccc;
    width:60px;
    font-family:'Dosis',sans-serif;

}

.bagbuy{
    padding:3rem 1rem 1rem 0rem;
}

.bagbuytitle{
    font-family: 'Dosis',sans-serif;
    font-size:20px;
    font-weight: bold;
    color: #424242;
    padding-bottom:15px;
}
.bagnav{
    padding:10px 0;
    justify-content:space-between;
    font-family:'Dosis',sans-serif;

}
.bagchk{
    width:100px;
    float:right;
    margin-right:10px;
    text-align:right;
    font-family:'Dosis',sans-serif;
    border:none;
}

.bagchkoutbtn{
    background-color: #525252;
    width:100%;
    height:50px;
    float:center;
    text-transform: uppercase;
    font-family:'Dosis',sans-serif;
    font-synthesis: style;
    letter-spacing: 2px;
    border:none;
    color: #ccc;
    margin-top:20px;
}

/*media queries*/

@media screen and (min-width:500px){
    .bagrow{
        width:50%;

    }
}

@media screen and (min-width:768px){
    .bagrow{
        display:flex;
    }
    .bagrowhead{
      width:160px;
    }
.bagbuy{
    position:fixed;
    background-color: rgb(255, 255, 255);
    right:18%;
    top:190px;
    width:35%;
    padding: 50px;
    overflow:scroll;
    height:100%;
    word-wrap: wrap;
}
.bagbuy::-webkit-scrollbar{
    visibility: none;;
}
}
@media screen and (min-width:1024px){
    .bagrow{

        width:30%;
        display:flex;

    }
    .rmvbagrow{
        margin:0;
        padding:0;
    }
}

@media (min-width:767px) and (max-width:769px){
.bagrowbtnbr{
    display:block;
}
.bagrowfld{
    float:right;
}
.rowtotalprice{
}
.clstot{
margin-top:10px;
}
}
<!DOCTYPE html>

Go To Get

                             <button class="far fa-heart ovla-fav" id="ovla-fav" ></button>

                         <button class="ovla-addtobag" name="ovla-addtobag" id="ovla-addtobag" title="Add To Shopping Bag">bag</button>

Sweatshirt shorts

£8.99

                             <button class="far fa-heart ovla-fav" id="ovla-fav" ></button>

                         <button class="ovla-addtobag" name="ovla-addtobag" id="ovla-addtobag" title="Add To Shopping Bag">bag</button>

Sweatshirt shorts

£8.99

                             <button class="far fa-heart ovla-fav" id="ovla-fav" ></button>

                         <button class="ovla-addtobag" name="ovla-addtobag" id="ovla-addtobag" title="Add To Shopping Bag">bag</button>

Sweatshirt shorts

£8.99

A: I have tested this on my local and I guess the following fix is what you're looking for
var addtobagbtn = document.getElementsByClassName('ovla-addtobag');

var tles = document.getElementsByClassName('prod-title');

for (i = 0; i < addtobagbtn.length; i++) {
    var button = addtobagbtn[i];

    button.addEventListener('click', function() {
        var button_target = event.target;
        var shopitem = button_target.parentElement.parentElement;

        var bagitems = document.getElementsByClassName('bagitems')[0];
        var imgsrc = shopitem.getElementsByClassName('prod-img')[0].src;

        appendbag(imgsrc, bagitems);

    });

}

function add(imgsrc, bagitems) {
    bagitems.insertAdjacentHTML("afterbegin", `

<button title="Remove From Bag" class="fas fa-times dltbag"></button>

Girlfriend Regular Jeans

H&M

$24.99

Dark denim blue

12

0706016003

<button class="far fa-heart movetofavbtn" title="Move To Bag"></button>Qty: <input type="number" value="1" name="indbagqty"title="Select Quantity" class="indbagqty bagrowfld" id="indbagqty">Total: <input type="text" title="Total Price" class="indbagtotalprice bagrowfld" name="indbagtotalprice" readonly>

`);
}

function appendbag(imgsrc, bagitems) {
    add(imgsrc, bagitems);

    localStorage.setItem("getbag", JSON.stringify(bagitems.innerHTML));

}

The problem was you were using the variable name "button" twice in same scope and wrote the functions add() and appendbag() inside for loop. They should be outside the loop.


text:
Q: Schedule jobs in database with nodejs I have a web application, where users can schedule different jobs.
I'am not sure how to proceed with this.
All the nodejs schedulers out there basically reads the schedule from within the code. I can of course implement this cron like schedule to be read from a database, but I'am not sure if its the most effective way?
If I back the solution with a database I would need to query that database, let say each second, to see if there is any schduled jobs that needs to be handled. I can't read them once a day, because new jobs might be added on a regular basis.
Keeping them in memory dosen't seem very efficient either?
Am I looking for a different kind of technology to handle this, than a scheduler+database?
We are talkning around 10.000 jobs for the time being (as a maximum). They are mostly related to sending emails and/or giving notifications within the application itself.


text:
Q: Router scene property for color header good morning friends, some property to assign the title in the header a different color from the background color of the whole scene?
Something like the image attached to them.
Header Color


text:
Q: Print more than one page with Printable on Java I need to print more than one page on my application, but when I try to print it I get only one page printed, or the same page printed 5 times, for example.
I put the code below:
MyPrintableTable mpt = new MyPrintableTable();
PrinterJob job = PrinterJob.getPrinterJob();
//PageFormat pf = job.defaultPage();
job.setPrintable(mpt);
job.printDialog();
try
{
    job.print();
}
catch (PrinterException e)
{
    // TODO Auto-generated catch block
    e.printStackTrace();
}

"MyPrintableTable" class:
class MyPrintableTable implements Printable
{
    public int print(Graphics g, PageFormat pf, int pageIndex)
    {
        if (pageIndex != 0)
           return NO_SUCH_PAGE;
        Graphics2D g2 = (Graphics2D) g;
        g2.setFont(new Font("Serif", Font.PLAIN, 16));
        g2.setPaint(Color.black);
        int x = 100;
        int y = 100;
        for(int i = 0; i < sTable.size(); i++)
        {
            g2.drawString(sTable.get(i).toString(), x, y);
            y += 20;
        }
        return PAGE_EXISTS;
    }
}

If I change the "pageIndex !=0" condition, I have more pages printed, but all with the same text.
I want to print all my text, that has a three page lenght, but I only can print the first one, o print three times the first one.
Can someone help me?

A: Here is a test program that demonstrates the principles I previously suggested in comments. It is based on ideas from Printing a Multiple Page Document, as well as on the code in the question. In a real program I would probably calculate linesPerPage rather than compiling in a number.
public class Test {
  public static void main(String[] args) {
    MyPrintableTable mpt = new MyPrintableTable();
    PrinterJob job = PrinterJob.getPrinterJob();
    // PageFormat pf = job.defaultPage();
    job.setPrintable(mpt);
    job.printDialog();
    try {
      job.print();
    } catch (PrinterException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}

class MyPrintableTable implements Printable {
  private int linesPerPage = 20;
  private List<String> sTable = new ArrayList<String>();
  {
    for (int i = 0; i < 100; i++) {
      sTable.add("Line" + i);
    }
  }

  public int print(Graphics g, PageFormat pf, int pageIndex) {
    if (pageIndex * linesPerPage >= sTable.size())
      return NO_SUCH_PAGE;
    Graphics2D g2 = (Graphics2D) g;
    g2.setFont(new Font("Serif", Font.PLAIN, 16));
    g2.setPaint(Color.black);
    int x = 100;
    int y = 100;
    for (int i = linesPerPage * pageIndex; i < sTable.size()
        && i < linesPerPage * (pageIndex + 1); i++) {
      g2.drawString(sTable.get(i).toString(), x, y);
      y += 20;
    }
    return PAGE_EXISTS;
  }
}


text:
Q: finding $f(x,y)$ that satisfies tangent-plane equation Q: Give an example for a function $f(x,y)$ continious partial derivatives that satisfies that following:

*

*$z=f(x,y)$ is not a plane

*$z=f(x,y)$ passes through the point $(6,4,3)$

*The tangent plane to the surface $z=f(x,y)$ at the point $(6,4,3)$ is
$$
 -4(x-6) +1(y-4) +z -3 = 0
\\~\\
$$
My take:
By looking at the tangent plane equation we can tell that:
$$
G(x) = f(x,y) -z \\ ~\\
\nabla G(6,4,3) = (-4,1,1)
$$
And I don't know how to procceed any further than that.
I can think about countless random options, but what is the way to tackle this problem?

A: From algebraic geometry I'm used to the tangent cone strategy for finding the tangent plane (or line) of a variety given implicitly by one (or, say, two) polynomial equation(s). In its simplest form this method amounts to writing a polynomial around a point (or translating to the origin) and investigating the polynomial there. If your point is on the variety (read surface) the constant term vanishes. The zero set of the linear terms give the tangent plane, etc. The flip side of this is that if you have the tangent plane you can add higher order terms around the point to get surfaces that have this plane as tangent plane. And if you don't add terms of higher order in $(z-3)$ it will still be expressible in polynomials as $z=f(x,y).$
One of the simpler ways of answering your question is then
$$(x-6)^2+(y-4)^2-4(x-6) +1(y-4) +1(z-3) = 0.$$


text:
Q: How to make my uiimageview static when i have a scrollview associated with it I am creating a music application which has more than 12 songs made of 12 tabs .i have added a uiview to my main view and to that uiview i have added imageview which keeps on changing after every 5 seconds. Below that uiview i have added another uiview and imageview and to that my tabs are called dynamically.Scrollview is applied to my tabs .but when i scroll my tabs it gets applied to the whole main view and the imageview that changes after every 5 seconds also scrolls with my tabs that is a problem.Only my tabs should get scrolled and my imageview that changes after every 5 secs should remain static.Please anybody help me regarding this problem.It is urgent.

A: You can simply add you imageview to view that contains scrollview instead of adding it to scrollview.


text:
Q: ClojureScript & Om: Best practice for writing document.hash I have a "Hello, World!" app in ClojureScript using Om (generated from the "Chestnut" lein template).
The goal is to have it set up such that:

*

*The document.location.hash value reflects changes to the (:route app-state) vector.

*The (:route app-state) vector reflects changes to the document.location.hash value.

*The app re-renders when (:route app-state) changes.

Note that I intend for the (:route app-state) vector to be the only source of truth for the app about the app's current state.  One mechanism of changing it is by the user modifying the url.
Where and how should I attach this behavior to Om?

Here's my "Hello, World!" app.
(ns demo.core
  (:require [om.core :as om :include-macros true]
            [om.dom :as dom :include-macros true]
            [clojure.string :as string]))

(defonce app-state (atom {:text "Hello, World!"
                          :route ["some" "app" "route"]}))

(defn update-location-hash [app owner]
  (reify
    om/IRender
    (render [_]
      (set! js/window.location.hash
            (string/join "/" (flatten ["#" (:route app)])))
            (dom/div nil ""))))

(om.core/root
  update-location-hash
  app-state
  {:target (. js/document (getElementById "app"))})

(defn main []
  (om/root
    (fn [app owner]
      (reify
        om/IRender
        (render [_]
          (dom/h1 nil (:text app)))))
    app-state
    {:target (. js/document (getElementById "app"))}))

This successfully writes the document.hash on page load.  Eventually this will be a single-page app that uses hash navigation to make view changes.
This feels dirty to me because of having to return a DOM element in the (render ) function of update-location-hash that doesn't have any purpose other than to fulfill the requirements of the render function.

A: Ok, I figured out what I needed.  It seems pretty clean to me and works.
For completeness, I would just need to add an on-page-load type listener that checks for the hash and a renderer that renders state changes to the hash.  That should be pretty straight-forward (based on my prior code above).
(ns demo.core
  (:require-macros [cljs.core.async.macros :refer [go]])
  (:require [goog.events :as events]
            [goog.events.EventType :as EventType]
            [cljs.core.async :as async :refer [>! <! put! chan]]
            [om.core :as om :include-macros true]
            [om.dom :as dom :include-macros true]
            [clojure.string :as string]))

;; Not sure what this does.
(enable-console-print!)

(defn listen
  "An event listener factory.  Given an element and an event type, return a
  channel that can be polled for event outputs."
  [el type]
  (let [out (chan)] (events/listen el type #(put! out %)) out))

(defonce app-state
  (atom {:text "Hello, World!"
         :mouse [0 0]
         :route ["some" "app" "route"]}))

(defn url-to-route
  "Given a url, parse the hash value as an app route.  In general, the
  resultant route has these properties:

  * route components are split on a solidus
  * empty components are ignored (nill or all-whitespace)

  A route like this:

    ['foo' 'bar' 'baz']

  will be produced by all of the following urls (and others):

    http://my-app.com/#/foo/bar/baz
    http://my-app.com/#foo/bar/baz
    http://my-app.com/#/foo// /bar//baz
    http://my-app.com/#/ / / /foo/bar////baz"
  [url]
  ;; Split the url at a hash followed by zero or more slashes and
  ;; whitespace.  Then take anything after the hash and split it on one or
  ;; more slashes (ignoring whitespace).
  (string/split (second (string/split url #"#[/\s]{0,}" 2)) #"[/\s]+"))

(defn layout
  "The central application layout component.  This registers global event
  listeners and renders the application's root DOM nodes."
  [app owner]
  (reify
    om/IWillMount
    (will-mount [_]
      ;; Handle various events.  When an event is triggered, format the
      ;; response.
      (let [;; Listen for changes to the mouse position
            mouse-chan (async/map
                         (fn [event] [(.-clientX event) (.-clientY event)])
                         [(listen js/window EventType/MOUSEMOVE)])

            ;; Listen for changes to the URL's hash
            hash-chan (async/map
                        (fn [event] (url-to-route (-> event .-event_ .-newURL)))
                        [(listen js/window EventType/HASHCHANGE)])]
        ;; Watch the stream and update the application state whenever
        ;; anything changes.
        (do
          (go (while true (om/update! app :route (<! hash-chan))))
          (go (while true (om/update! app :mouse (<! mouse-chan)))))))

    om/IRender
    (render [_]
      (dom/div
        nil
        (dom/div nil (when-let [route (:route app)] (pr-str (:route app))))
        (dom/div nil (when-let [pos (:mouse app)] (pr-str (:mouse app))))
        (dom/h1 nil (:text app))))))

(defn main []
  (om/root
    layout
    app-state
    {:target (. js/document (getElementById "app"))}))


text: Q: Two Entity with Common identifier @id in HIbernate I am Using Spring3+Hibernate 3.0. I Have two beans (@Entity) Projects And Participants. I want both beans(Projects and Participants) should have common @ID identifier it means projects and participants table will have common primary key. How Can I use @embededID or @Embedable to achieve that? Thanx in Advance.


text:
Q: Negative hash value in code of Rabin-Karp Algorithm I was understanding the Rabin-Karp Algorithm from this website: https://www.geeksforgeeks.org/rabin-karp-algorithm-for-pattern-searching/
They had the following code in C++ for the algorithm:
#include <bits/stdc++.h>
using namespace std;

// d is the number of characters in the input alphabet
#define d 256

/* pat -> pattern
    txt -> text
    q -> A prime number
*/
void search(char pat[], char txt[], int q)
{
    int M = strlen(pat);
    int N = strlen(txt);
    int i, j;
    int p = 0; // hash value for pattern
    int t = 0; // hash value for txt
    int h = 1;

    // The value of h would be "pow(d, M-1)%q"
    for (i = 0; i < M - 1; i++)
        h = (h * d) % q;

    // Calculate the hash value of pattern and first
    // window of text
    for (i = 0; i < M; i++)
    {
        p = (d * p + pat[i]) % q;
        t = (d * t + txt[i]) % q;
    }

    // Slide the pattern over text one by one
    for (i = 0; i <= N - M; i++)
    {

        // Check the hash values of current window of text
        // and pattern. If the hash values match then only
        // check for characters on by one
        if ( p == t )
        {
            /* Check for characters one by one */
            for (j = 0; j < M; j++)
            {
                if (txt[i+j] != pat[j])
                    break;
            }

            // if p == t and pat[0...M-1] = txt[i, i+1, ...i+M-1]
            if (j == M)
                cout<<"Pattern found at index "<< i<<endl;
        }

        // Calculate hash value for next window of text: Remove
        // leading digit, add trailing digit
        if ( i < N-M )
        {
            t = (d*(t - txt[i]*h) + txt[i+M])%q;

            // We might get negative value of t, converting it
            // to positive
            if (t < 0)
            t = (t + q);
        }
    }
}

/* Driver code */
int main()
{
    char txt[] = "GEEKS FOR GEEKS";
    char pat[] = "GEEK";

      // A prime number
    int q = 101;

      // Function Call
      search(pat, txt, q);
    return 0;
}

What I didn't understand was this block of code:
            // We might get negative value of t, converting it
            // to positive
            if (t < 0)
            t = (t + q);

How can t ever be negative? What we subtract from t is always less than t and then we add something to it so where does the possibility of t beign negative even come from?
I tested the code without this if statement and it didn't work properly. The exepected output was :
Pattern found at index 0
Pattern found at index 10

But I got:
Pattern found at index 0

A: Aki Suihkonen has it; with a positive modulus, the result is either zero or has the same sign as the dividend, whereas Rabin--Karp assumes that the result will always be nonnegative.
For example, if we do
t = 3
t = (t + 5) % 7
t = (t - 5) % 7

then the values are
(3 + 5) % 7 == 1
(1 - 5) % 7 == -4

which if we add 7 makes 3 as desired.

A: t can indeed be negative.

*

*As we are taking modulo q in each step, the value of t can be between 0 to q-1.

*So, txt[i]*h can be greater than the old value of t. Making (t - txt[i]*h) negative.

*Which can possibly result in (d*(t-txt[i]*h)+txt[i+M]) being negative.

*In C++, when we try to perform modulus on negative numbers, it returns a negative value. For example,

(-5) % 3 = -2

*As a result, if (d*(t-txt[i]*h)+txt[i+M]) is negative, (d*(t-txt[i]*h)+txt[i+M])%q will also be negative. Thus, resulting in t (new) being negative.

[Note that, the modulo operation is handled differently in different language. For example, in Python, the modulo of a negative number gives a positive and valid result. So, we don't need to handle this case in Python.]
For better insight, you can run this slightly modified code that shows the value of each part of the calculation for each iteration i.
Code

#include <bits/stdc++.h>
using namespace std;

// d is the number of characters in the input alphabet
#define d 256

/* pat -> pattern
    txt -> text
    q -> A prime number
*/
void search(char pat[], char txt[], long long int q)
{
    long long int M = strlen(pat);
    long long int N = strlen(txt);
    long long int i, j;
    long long int p = 0; // hash value for pattern
    long long int t = 0; // hash value for txt
    long long int h = 1;

    // The value of h would be "pow(d, M-1)%q"
    for (i = 0; i < M - 1; i++)
        h = (h * d) % q;

    // Calculate the hash value of pattern and first
    // window of text
    for (i = 0; i < M; i++)
    {
        p = (d * p + pat[i]) % q;
        t = (d * t + txt[i]) % q;
    }

    // Slide the pattern over text one by one
    for (i = 0; i <= N - M; i++)
    {

        // Check the hash values of current window of text
        // and pattern. If the hash values match then only
        // check for characters on by one
        if ( p == t )
        {
            /* Check for characters one by one */
            for (j = 0; j < M; j++)
            {
                if (txt[i+j] != pat[j])
                    break;
            }

            // if p == t and pat[0...M-1] = txt[i, i+1, ...i+M-1]
            if (j == M)
                cout<<"[Pattern Found] at index "<< i<<endl;
        }

        // Calculate hash value for next window of text: Remove
        // leading digit, add trailing digit
        if ( i < N-M )
        {
            cout << "i = " << i << endl;
            cout << "------------------------------------------" << endl;
            cout << "t                          :" << t << endl;
            cout << "txt[i]*h                   :" << txt[i]*h << endl;
            cout << "t-txt[i]*h                 :" << t - txt[i]*h << endl;
            cout << "d*(t-txt[i]*h)             :" << d*(t - txt[i]*h) << endl;
            cout << "(d*(t-txt[i]*h)+txt[i+M])  :" << (d*(t - txt[i]*h) + txt[i+M]) << endl;
            cout << "(d*(t-txt[i]*h)+txt[i+M])%q:" << (d*(t - txt[i]*h) + txt[i+M])%q << endl;

            t = (d*(t - txt[i]*h) + txt[i+M])%q;

            // We might get negative value of t, converting it
            // to positive
            if (t < 0)
                t = (t + q);

            cout << "new_t                      :" << t << endl;
            cout << "------------------------------------------" << endl;
        }
    }
}

/* Driver code */
int main()
{
    char txt[] = "GEEKS FOR GEEKS";
    char pat[] = "GEEK";

      // A prime number
    long long int q = 101;

      // Function Call
      search(pat, txt, q);
    return 0;
}

Output
[Pattern Found] at index 0
i = 0
------------------------------------------
t                          :27
txt[i]*h                   :355
t-txt[i]*h                 :-328
d*(t-txt[i]*h)             :-83968
(d*(t-txt[i]*h)+txt[i+M])  :-83885
(d*(t-txt[i]*h)+txt[i+M])%q:-55
new_t                      :46
------------------------------------------
i = 1
------------------------------------------
t                          :46
txt[i]*h                   :345
t-txt[i]*h                 :-299
d*(t-txt[i]*h)             :-76544
(d*(t-txt[i]*h)+txt[i+M])  :-76512
(d*(t-txt[i]*h)+txt[i+M])%q:-55
new_t                      :46
------------------------------------------
i = 2
------------------------------------------
t                          :46
txt[i]*h                   :345
t-txt[i]*h                 :-299
d*(t-txt[i]*h)             :-76544
(d*(t-txt[i]*h)+txt[i+M])  :-76474
(d*(t-txt[i]*h)+txt[i+M])%q:-17
new_t                      :84
------------------------------------------
i = 3
------------------------------------------
t                          :84
txt[i]*h                   :375
t-txt[i]*h                 :-291
d*(t-txt[i]*h)             :-74496
(d*(t-txt[i]*h)+txt[i+M])  :-74417
(d*(t-txt[i]*h)+txt[i+M])%q:-81
new_t                      :20
------------------------------------------
i = 4
------------------------------------------
t                          :20
txt[i]*h                   :415
t-txt[i]*h                 :-395
d*(t-txt[i]*h)             :-101120
(d*(t-txt[i]*h)+txt[i+M])  :-101038
(d*(t-txt[i]*h)+txt[i+M])%q:-38
new_t                      :63
------------------------------------------
i = 5
------------------------------------------
t                          :63
txt[i]*h                   :160
t-txt[i]*h                 :-97
d*(t-txt[i]*h)             :-24832
(d*(t-txt[i]*h)+txt[i+M])  :-24800
(d*(t-txt[i]*h)+txt[i+M])%q:-55
new_t                      :46
------------------------------------------
i = 6
------------------------------------------
t                          :46
txt[i]*h                   :350
t-txt[i]*h                 :-304
d*(t-txt[i]*h)             :-77824
(d*(t-txt[i]*h)+txt[i+M])  :-77753
(d*(t-txt[i]*h)+txt[i+M])%q:-84
new_t                      :17
------------------------------------------
i = 7
------------------------------------------
t                          :17
txt[i]*h                   :395
t-txt[i]*h                 :-378
d*(t-txt[i]*h)             :-96768
(d*(t-txt[i]*h)+txt[i+M])  :-96699
(d*(t-txt[i]*h)+txt[i+M])%q:-42
new_t                      :59
------------------------------------------
i = 8
------------------------------------------
t                          :59
txt[i]*h                   :410
t-txt[i]*h                 :-351
d*(t-txt[i]*h)             :-89856
(d*(t-txt[i]*h)+txt[i+M])  :-89787
(d*(t-txt[i]*h)+txt[i+M])%q:-99
new_t                      :2
------------------------------------------
i = 9
------------------------------------------
t                          :2
txt[i]*h                   :160
t-txt[i]*h                 :-158
d*(t-txt[i]*h)             :-40448
(d*(t-txt[i]*h)+txt[i+M])  :-40373
(d*(t-txt[i]*h)+txt[i+M])%q:-74
new_t                      :27
------------------------------------------
[Pattern Found] at index 10
i = 10
------------------------------------------
t                          :27
txt[i]*h                   :355
t-txt[i]*h                 :-328
d*(t-txt[i]*h)             :-83968
(d*(t-txt[i]*h)+txt[i+M])  :-83885
(d*(t-txt[i]*h)+txt[i+M])%q:-55
new_t                      :46
------------------------------------------


text:
Q: Output Checked Items in Javascript Using Confirm() I am trying to output the selected checked items from my list (I am using checkboxes) on the alert message on my page. Essentially, when the user hits the Delete button, I want a confirmation box to pop up and show the user which items they have selected to confirm it's correct (in this case, Serial Numbers). By default, all checkboxes are false (unchecked). If a checkbox is checked, the checkbox variable = true. Below is the function I wrote to do this:
function validateDeleteForm() {
        var checkboxs=document.getElementsByName("pickSerial");
        var okay=false;

        for(var i=0,l=checkboxs.length;i<l;i++)
        {
            if(checkboxs[i].checked)
            {
                okay=true;
            }
        }
        if(okay)
            {
                if (confirm("Do you want to delete the selected Serial Number(s) from casting? Hit OK to Delete or CANCEL to re-select: " + this.checkboxs ) == true) { // this will delete selected serial numbers and display
                    return true;
                }
                //return true;
                else { // this will cancel the delete dialogue and allow user to re-select
                    return false;
                }
            }

        else {
            alert("You have at least one line to be checked");
            return false;
        }
    }

Does anyone see what I am doing wrong? I have tried referencing the checked items doing checkboxs[i].value, this.checkboxs[i], and calling the checkboxs variable but they all show as undefined.
Here is a screenshot of the output currently.
Thank you for any help.

A: Using querySelectorAll you can right away select all of the checked elements. There is no need to have to loop to find the check ones with this. You can then turn the html collection into an array to get all of the values. You can then use that array to display the info to the use.
const cbs = Array.from(document.querySelectorAll('[name="pickSerial"]:checked'));
const serials = cbs.map(function (cb) { return cb.value; });
if (serials.length) {
  console.log(serials.join(",");
}

A: Adding to your solution, you can create an array to track checked items and then when printing, just use that array
Sample
const checked = [];
// When you are setting okay = true, push that value in checked
checked.push(checkboxs[i].value)

// Now when you are showing it in confirm box just join the array
confirm('text ' + checked.join(', '))

Hope that helps.


text:
Q: Non-orthogonal projection of line segment I've posted an image below of the task I'm trying to accomplish. I have a right triangle, $R + r, d, R$, where $R + r$ is the hypotenuse. Then, I draw another (dotted) line labeled $R'$ at an angle $\phi$ with respect to the hypotenuse that touches the x -axis. $X$ is the perpendicular line from the hypotenuse to $R'$, at a distance of $R$ down along the hypotenuse. $Y$ is the perpendicular distance from the origin to where $R'$ touches the x-axis. Basically, I want to derive a relation between $x$ and $y$ that uses all of the variables defined in the figure.

I believe derived a relation between the two, but I don't think it's right because it fails at $\phi = 0, \theta = 0$. I've used three relations:
\begin{align}\tan(\phi) &= \frac{X}{R}\\
\tan(\phi + \theta) &= \frac{D}{R-H}\\
\tan\!\left(\frac{\pi}{2} - \theta - \phi\right) &= \frac{H}{Y}
\end{align}
I've defined $H$ to be the vertical distance from the origin to where $R'$ intersects $R$. From these, I've derived the relation to be: $$ Y = \frac{\frac{X}{\tan(\phi)} - \frac{D}{\tan(\phi + \theta)}}{\tan(\frac{\pi}{2} - \phi - \theta)} $$
One of the biggest reasons I think I'm wrong is because the angle $\phi$ isn't defined with respect to the $x$- or $y$-axis. Letting me know if I'm on the right track or which one of my assumptions is incorrect would be of great help.

A: We have $Y + D = \dfrac { R }{\tan (\theta ' - \phi)}$ and $D = \dfrac {R}{\tan \theta '}$.
Y can be found by subtracting the two, provided R and the angles are known.
Assuming that X is the line marked as high-lighted.
Then, X = $R \tan \phi$. X and Y can then be related by eliminating R.


text:
Q: Modified coupon collector problem - calculating variance We have $n$ different types of coupons in the box. Probability of drawing coupon of $j$th type from the box does not change and is equal to $p_j$. Find the expected value and variance of number of types in randomly chosen set of $k$ coupons.
I've managed to find the expected value, but I cannot calculate the variance. This is what I've got so far.
Let $X_i = \begin{cases}
      0, & \text{if}\ \text{the $i$th coupon was not found in $k$ selections} \\
      1, & \text{otherwise}
    \end{cases}$
We have $X = \sum_{i=1}^{n} X_i$ and $E[X_i] = 1 \times Pr(X_i = 1) + 0 = 1 - (1 - p_i)^k$. $E[X] = E[\sum_{i=1}^{n}X_i] = \sum_{i=1}^nE[X_i] = n - \sum_{i=1}^{n}(1 - p_i)^k$.
Now let's calculate variance. $\text{Var}\left[X\right] = E[X^2] - (E[X])^2$. Since I've managed to calculate $E[X]$ the only problem is to obtain $E[X^2]$.
So $E[X^2] = E[(\sum_{i=1}^{n}X_i)^2] = \sum_{i=1}^{n}E[X_i^2] + 2\sum_{1 \leq i < j \leq n}E[X_iX_j]$.
The first summand is quite straightforward, but the second one certainly not. Could you suggest me any solution?


text:
Q: How to delete an element from a struct array in c++ lets say i have a structure like this:
struct customer{
    int c1;
    int c2;
    int c3;
};
customer phone[10];

phone[0].c1 = 1;
phone[0].c2 = 1;
phone[0].c3 = 1;

phone[1].c1 = 2;
phone[1].c2 = 2;
phone[1].c3 = 2;

so my question is how to remove phone[1] from the struct array?
thanks in advance.

A: The best you can do is to overwrite it.
This is a built-in array. So the other elements are not initialized. In the same way, once you write something to one of the elements it stays there until the array goes out of scope or you write something else there.
It would be best to do the same with a std::vector:
#include <iostream>
#include <vector>

int main()
{
    struct customer {
        int c1;
        int c2;
        int c3;
    };
    customer phone[10];

    phone[0].c1 = 1;
    phone[0].c2 = 1;
    phone[0].c3 = 1;

    phone[1].c1 = 2;
    phone[1].c2 = 2;
    phone[1].c3 = 2;

    std::vector<customer> phonev{{1,1,1},{2,2,2}};
    phonev.erase(phonev.begin()+1);

    return 0;
}

Then you can erase an element.


text:
Q: Centering the widgets within a StackLayout in Kivy I'm trying to center the widgets within a StackLayout horizontally, but I'm both a newb and not very good at math, and can't wrap my head around the correct formula.  Each widget within the StackLayout is 128 pixels wide, and the spacing between each widget is 20 pixels.  Here's what I have:
padding: ((root.width - ((int((root.width - ((int(root.width / 128) - 1) * 20)) / 128) - 1) * 20)) % 128) / 2, 0, 0, 0
spacing: 20

It works well to a point.  For instance, when the window width is any amount up to 255 pixels, it centers a single 128 pixel widget perfectly per row.  But once the window is resized to 256 pixels wide, each widget is then positioned hard left with a padding of 0.  As I increase the width of the window from 256 to 275, padding will increase in turn.  At 276 pixels wide the widgets snap back to the hard left position with a padding of 0, and a 2nd widget is then placed on each row (which is good and how it should work).
Plugging a value into the formula, I can see why this happens, but I'm just not sure how to fix it.  Any help would be appreciated.  Thanks.

A: This is easier to achieve with a GridLayout. It will look like this for different size buttons and spacing of 20:

The trick is to put two dummy widgets to fill the spaces on the sides (since default size_hint is 1,1):

Code Example
You would need to run the below example with the size parameter to control the size of the window (alternatively you can use the mouse to shrink it):
python gridlayout.py --size=500x30

And you need two files. First, the gridlayout.kv:
<GridLayout>:
    rows: 1
    spacing: 20

    Widget:
    Button:
        text: 'A'
        size_hint: None, 1
        width: 25
    Button:
        text: 'B'
        size_hint: None, 1
        width: 50
    Button:
        text: 'C'
        size_hint: None, 1
        width: 25
    Widget:

And second, the python code gridlayout.py:
import kivy

from kivy.app import App
from kivy.uix.gridlayout import GridLayout

class GridLayoutApp(App):
    def build(self):
        return GridLayout()

if __name__=="__main__":
    GridLayoutApp().run()


text:
Q: Add sorted json back to json object How to add sorted json('sortedJson') back to the whole json('jObj') below? Or is there an alternative to do the below?
 Json:
        {
          "Information": [
            {
              "FieldName": "Area04",
              "Draft": "Unknown",
            },
            {
              "FieldName": "Area02",
              "Draft": "Unknown",
            },
            {
              "FieldName": "Area01",
              "Draft": "Unknown",
            },
            {
              "FieldName": "Area03",
              "Draft": "Unknown",
            }
          ],
          "OtherInfo": []
        }

    Code:
        static void Main(string[] args)
          {
            string _json = "{'Information': [{'FieldName': 'Area04','Draft': 'Unknown'},{'FieldName': 'Area02','Draft': 'Unknown'},{'FieldName': 'Area01','Draft': 'Unknown'},{'FieldName': 'Area03','Draft': 'Unknown'}],'OtherInfo': []}";
            var jObj = JsonConvert.DeserializeObject<Informat>(_json);
            var test1 = jObj.Information.OrderBy(x => x.FieldName);
            var sortedJson = JsonConvert.SerializeObject(test1);
           //Add code to merge 'sortedJson' to '_json'
          }

    Class:
    public class Informat
    {
        public Information[] Information { get; set; }
        public object[] OtherInfo { get; set; }
    }

    public class Information
    {
        public string FieldName { get; set; }
        public string Draft { get; set; }
    }

I dont know how to add the sorted json back to whole json. Could you please help me with this?

A: Here's an example using Array.Sort()
var jObj = JsonConvert.DeserializeObject<Informat>(_json);
Array.Sort(jObj.Information, (x, y) => x.FieldName.CompareTo(y.FieldName));
var sortedJson = JsonConvert.SerializeObject(jObj);


text:
Q: Standardise Oracle date across clients in Java Resultset In my Java code, I'm selecting/fetching an Oracle DATE column using ResultSet and getTimestamp() method, and converting this to time-in-milli-seconds. The problem is the time-in-milli-seconds varies across the machines I'm running it on. For example, if the actual timestamp is 1511213580 ms, on machine1 this is 1511262180 ms and on machine2 it is 1511233380 ms.
I've read this post Is java.sql.Timestamp timezone specific? and understand that Timestamp uses the machine's equivalent timezone to store this data.
My question is, how do I standardise the timestamps to display/read the same across clients? I do not have access to the code that persists the timestamps. On the machines that run this fetch-from-db program, I'm using additional shell scripts to compare the time-in-milli-seconds with the current time from the machine.
Here are my code snippets:
Timestamp timestamp = rset.getTimestamp(i);
if (timestamp != null)
    timeInSeconds = timestamp.getTime()/1000;

A: tl;dr
myResultSet.getObject( … , Instant.class )
           .isBefore( Instant.now() )

Details
As has been discussed many times on Stack Overflow, you should:

*

*Store your date-time values in UTC.

*Never depend on the JVM's current default time zone.

*Avoid the terrible legacy date-time classes such as Date, Calendar, and the java.sql.* classes.

*Use only the java.time rather than the legacy date-time classes they supplant.

*Use a driver compliant with JDBC 4.2 or later to retrieve java.time objects.

*Avoid tracking time as a count-from-epoch, using objects instead.

I'm not an Oracle user, but it appears that DATE is a legacy type, lacks any concept of time zone. I suggest using the standard TIMESTAMP WITH TIME ZONE instead.
An Instant is a moment on the timeline, always in UTC, with a resolution of nanoseconds.
Instant instant = myResultSet.getObject( … , Instant.class ) ;
Boolean isPast = instant.isBefore( Instant.now() ) ;

While I advise against tracking time as a count from epoch, if you insist, you can extract a count of milliseconds since the epoch of 1970-01-01T00:00:00Z. Beware of data loss as you are truncating any microseconds or nanoseconds that may be present.
long millis = instant.toEpochMilli() ;

About java.sql.Timestamp, these objects  are always in UTC. This confusing legacy class, badly designed as a hack, is now legacy and should be avoided. Replaced by java.time.Instant.

The problem is the time-in-milli-seconds varies across the machines I'm running it on. For example, if the actual timestamp is 1511213580 ms, on machine1 this is 1511262180 ms and on machine2 it is 1511233380 ms.

That makes no sense as java.sql.Timestamp will contain the same count from epoch in UTC across machines. I suspect the clocks of those alternate machines have been set to the wrong time, perhaps intentionally as a misguided attempt to handle time zone adjustment.
In that case you have a mess on your hands. The only workaround is to test each machine, calculate the delta between true UTC time and that particular machine's incorrect clock. Then add or subtract that amount when obtaining data from that machine. Obviously risky as you never know when that confused sysadmin will attempt another adjustment hack.
The real solution is to: keep all servers in UTC and set to true accurate clock time, handle date-time values with java.time classes, and store moments in a column of type TIMESTAMP WITH TIME ZONE.


text:
Q: In Bash scripting, how can I add a variable into a variable name? So take the following script as an example:
PROFILE1=profileName
SERVER1=serverName
PROFILE2=profile2Name
SERVER2=server2Name

VAR_$PROFILE1_$SERVER1=/home/$PROFILE1/$SERVER1/data
VAR_$PROFILE1_$SERVER2=/home/$PROFILE1/$SERVER2/data
VAR_$PROFILE2_$SERVER1=/home/$PROFILE2/$SERVER1/data

echo "$VAR_$PROFILE1_$SERVER1"

That is the basics of what I am attempting to accomplish. This may not be the best way to go about it, but for someone who is fairly new to bash scripting this was my first thought on how to do it.
I need to be able to only change one location in my script file and be able to add new "VAR_..." as needed for the system I am on.
Is this even possible? If not then if you understand what I am attempting to accomplish could you suggest an alternative?

A: You can use eval declare for this (thanks Glenn Jackman for pointing in the good direction!):
$ declare VAR_${PROFILE1}_${SERVER1}="hello"
$ echo $VAR_profileName_serverName
hello

In your case:
declare VAR_${PROFILE1}_${SERVER1}=/home/$PROFILE1/$SERVER1/data
declare VAR_${PROFILE1}_${SERVER2}=/home/$PROFILE1/$SERVER2/data
declare VAR_${PROFILE2}_${SERVER1}=/home/$PROFILE2/$SERVER1/data

Note the use of VAR_${PROFILE1}_${SERVER1}. The curly brackets tell what's the exact name of the variable, because otherwise VAR_$PROFILE1_$SERVER1 would look for a variable named PROFILE1_, etc.
As echo VAR_${PROFILE1}_${SERVER1} returns VAR_profileName_serverName, then you can make use of the variables, using the following:
$ var="VAR_${PROFILE1}_${SERVER1}"
$ echo ${!var}
/home/profileName/serverName/data

Note that ${!var} is a variable indirection, that fetches the variable whose name is in the $var variable.

A: If you have bash version 4, use an associative array:
declare -A data
data=(
  [$PROFILE1,$SERVER1]=/home/$PROFILE1/$SERVER1/data
  [$PROFILE1,$SERVER2]=/home/$PROFILE1/$SERVER2/data
  [$PROFILE2,$SERVER1]=/home/$PROFILE2/$SERVER1/data
)
for key in "${!data[@]}"; do
    printf "%s\t%s\n" "$key" "${data[$key]}"
done
echo "${data[$PROFILE1,$SERVER2]}"

profileName,server2Name /home/profileName/server2Name/data
profileName,serverName  /home/profileName/serverName/data
profile2Name,serverName /home/profile2Name/serverName/data
/home/profileName/server2Name/data

A: You mean this?
ABC="ahoj\$UNSETVAR"
echo $ABC
UNSETVAR=now_it_is_set
eval "DEV=$ABC"
echo $DEV

Output will be:
ahoj$UNSETVAR
ahojnow_it_is_set


text:
Q: How to get some text values in python below text format I have sentences like
// string1 = value1
// string2 = value2.....

so on, how can I get only "values" using python

A: print [line.split('=',1)[-1].strip() for line in s.splitlines()]

A: >>> strs="""
// string1 = value1
// string2 = value2
"""
>>> [x.split('=')[1].strip() for x in strs.split('\n') if x.strip()]
['value1', 'value2']


text:
Q: Derivation of the polytropic process equation for an adiabatic process I am trying to derive $$pV^\gamma - p_0V_0^\gamma = 0$$ from the first law of thermodynamics and the ideal gas law. I thought of two seemingly identical ways, which yield different results. Maybe someone can tell me where I went wrong.
For an adiabatic process, there is no heat transfer. $$\delta Q = 0$$
This is substituted into the first law of thermodynamics.
$$ dU = \delta Q + \delta W = \delta W$$
Now the inner energy and mechanical work can be written as
$$ \frac{f}{2}n R dT = - p dV.$$ Interchanging the ideal gas law yields
$$p = \frac{nRT}{V}.$$
Plugging that in gives us
$$ \frac{f}{2}n R dT = - \frac{nRT}{V} dV.$$
Which is equivalent to
$$ \frac{-f}{2} \frac{dT}{T}= \frac{dV}{V}.$$
We can now integrate the whole equation from the initial temperature and volume to the final temperature and volume.
$$ \frac{-f}{2} \int_{T_0}^{T} \frac{dT'}{T'}= \int_{V_0}^{V} \frac{dV'}{V'}.$$
$$ \left(\frac{T}{T_0} \right)^{\frac{-f}{2}} = \frac{V}{V_0}$$
Substituting in the ideal gas law for two different temperatures
$$T_0 = \frac{p_0V_0}{nR}$$
$$T = \frac{pV}{nR}$$
and interchanging gives us the correct result.
$$  \frac{p}{p_0} = \left( \frac{V}{V_0} \right)^{-(\frac{2}{f}+1)} = \left( \frac{V}{V_0} \right)^{-\gamma}$$.
So much for the prelude!
Why is it not possible to use the ideal gas law directly in the first step of the derivation?
The derivative of the ideal gas law with respect to the pressure p reads
$$dpV = nRdT$$
With the help of this derivative, the inner energy can be expressed as
$$dU = \frac{f}{2}n R dT = \frac{f}{2} V dp.$$
If we put this inner energy back into the first law and integrate from initial to final conditions we get
$$dU = \delta W = -pdV = \frac{f}{2}dpV$$
$$\frac{p}{p_0} = \left( \frac{V}{V_0} \right)^{-\frac{2}{f}} = \left( \frac{V}{V_0} \right)^{1-\gamma}$$
This is obviously not the same. I would be rather happy if someone could tell me where I made the mistake, which leads to this contradiction.


text:
Q: To Update blindly or to Update Where? I have a table that holds information about cities in a game, you can build one building each turn and this is recorded with the value "usedBuilding".
Each turn I will run a script that alters usedBuilding to 0, the question is, which of the following two ways is faster and does it actually matter which way is used?
UPDATE cities SET usedBuilding = 0;
UPDATE cities SET usedBuilding = 0 WHERE usedBuilding = 1;

A: In general, the 2nd case (with the WHERE) clause would be faster - as it won't cause trigger evaluation, transaction logging, index updating, etc. on the unused rows.
Potentially - depending on the distribution of 0/1 values, it could actually be faster to update all rows rather than doing the comparison - but that's a pretty degenerate case.
Since ~95% of your query costs are I/O, using the WHERE clause will either make no difference (since the column is not indexed, and you're doing a table scan) or a huge difference (if the column is indexed, or the table partitioned, etc.). Either way, it doesn't hurt.
I'd suspect that for the amount of data you're talking, you won't notice a difference in either execution plans or speed - which makes it academic at best, premature optimization at worst. So, I'd advise to go with whatever logically makes sense for your app.

A: If usedBuilding is indexed, it will be quicker to use the where clause since it will only access/update rows where usedBuilding is true.
If it's not indexed, you'd be doing a full table scan anyway, so it wouldn't make much (any?) difference.

A: Try both ways in a loop a few thousand times and time them!
It probably depends on: how many records are actually in this table, and whether they all fit in memory or have to be paged to disk. How many buildings are at value 1 before you run the update (I'm guessing this might be 1).
It doesn't matter which way is used, but the shortest one's probably got the least that can go wrong with it. Code that you don't write can't have bugs.

A: How often are these turns happening? How many rows do you expect to have in this table? If the answers are 'less than once a second' and 'less than 10000', just stop worrying.
Unless if you happen to have some sort of academic interest in this, of course.

A: It seems like there would be a lower number of transactions to make the "UPDATE cities SET usedBuilding = 0;" execute than the more specific query.  The main reason I can think of against this would be if you had more than one state to your column. If its merely a boolean then it would be fine, but you may want to spend some time thinking if that will always be the case.
Indexing could also cause the execution plan to be more efficient using the WHERE clause.

A: The best way to get a definitive answer would be to profile using a lot of sample data under differing scenarios.

A: indexing won't help you at all unless you have something like maybe 2% of the usedBuilding = 1 values.
however these 2 statements are logically different and can mean totally different things.
but if for your case they are the same then use the one without the where clause.

A: How many rows exactly will you have? I suspect that for a smallish online game, you really don't care.
If you're doing several updates to the "cities" table, it might be a good idea to do them all in one UPDATE statement if possible.
Making any change to a row probably takes just as much I/O as writing the entire row (except of course updating indexed columns also requires index writes), so you lose out by making several UPDATEs which hit lots of rows.
But if you have, say, <1000 rows, you really don't care :)


text:
Q: How to make text normal and not italic in frame? How can you make the text normal in the frame below and not italic?

\documentclass[a4paper]{article}
\usepackage{mdframed}
\usepackage{ntheorem}
\definecolor{superlightred}{HTML}{F5F5F5}
\theoremstyle{nonumberplain}
\newmdtheoremenv[backgroundcolor=superlightred, ntheorem]{example}{}[]

\begin{document}

\begin{example}[2014.1]
This is an example and here is a lot of text.  \\ \\
\textbf{a)} Find the relationship between the components.
\end{example}

\end{document}

A: Just add \theorembodyfont{\upshape] right after \theoremstyle. This being said, I think it is better to use the empty theorem style. I also improved a bit the code, using an enumerate environment with the suitable parameters using enumitem, so that you only have to type \item to obtain the correct counter, automatically formatted.
You even have the possibility, with enumitem, to create your own dedicated list, say examples with these parameters set  in the preamble, with the code:
\documentclass[a4paper]{article}
\usepackage{xcolor}
\usepackage{enumitem}
\usepackage{mdframed}
\usepackage{ntheorem}
\definecolor{superlightred}{HTML}{F5F5F5}
\theoremstyle{empty}%
\theorembodyfont{\upshape}
\newmdtheoremenv[backgroundcolor=superlightred, ntheorem]{example}{}
\newlist{examples}{enumerate}{1}% <- max depth
\setlist[examples]{label=\alph*), font=\bfseries, wide=0pt, leftmargin=*, topsep=4pt}

\begin{document}

\begin{example}[2014.1]
This is an example and here is a lot of text.
\begin{examples}
\item
Find the relationship between the components.
\end{examples}
\end{example}

\end{document}

A: As indicated in ntheorem's documentation, the font of the theorem body can be changed using the \theorembodyfont command.
\documentclass[a4paper]{article}
\usepackage{mdframed}
\usepackage{ntheorem}
\usepackage{xcolor}
\definecolor{superlightred}{HTML}{F5F5F5}
\theoremstyle{nonumberplain}
\theorembodyfont{\normalfont}
\newmdtheoremenv[backgroundcolor=superlightred, ntheorem]{example}{}

\begin{document}

\begin{example}[2014.1]
This is an example and here is a lot of text.  \\ \\
\textbf{a)} Find the relationship between the components.
\end{example}

\end{document}

A: You can also use \theoremstyle{definition} before the \newmdtheoremenv command. (However, it gave a slight error: Unknown theoremstyle `definition'. I used it together with \newtheorem{theorem}{Theorem} without error.)


text:
Q: How can I use four finger drag and switch between workspaces with my touchpad on Ubuntu? Is there any way to make Ubuntu 16.04 know when i drag with 4 fingers on my touchpad or other gestures and do specific actions?

A: Yes, this is possible with Touchégg.
This is an open source script you install onto your machine via the command line. There is an alternative GUI but I have not used that.
Once installed you can execute touchegg from the command line and it will tell you which touch devices you have.
After this you can edit the configuration file, mentioned in the instructions, to tell Touchégg what to do with 4 finger actions (among others).


text:
Q: Extract HTTP Status Code from java.io.IOException How is it possible (if at all) to get the HTTP status code from a java.io.IOException in java
?

A: I'm assuming this is about an IOException thrown by a URLConnection.
Three possibilities to handle this, depending on your restrictions.
1) Cast your URLConnection to a HttpURLConnection and call getResponseCode
If you have access to the connection object, you can get the status code using this code:
int statusCode = (HttpURLConnection)theConnection).getResponseCode();

2) Use a HttpURLConnection instead of an URLConnection in the first place
If you can do this, it would be the best solution, because an URLConnection doesn't throw on error status codes. You can just call getResponseCode and check the status without getting any exception first.
3) Parse the exception message itself
The IOException's message usually looks like this:
Server returned HTTP response code: 403 for URL: http://something

So you can just use a regex (or simple string manipulation) to get the response code out of there.
Note that for status 404, the message doesn't look like this and a FileNotFoundException is thrown. I'm not sure if there are any other status codes throwing "special" exceptions like this, but watch out for this.
Example code demonstrating methods 2 & 3:
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class HelloWorld {
    public static void testUrl(String urlString) throws MalformedURLException {
        URLConnection conn = null;
        System.out.println("Testing URL " + urlString);
        try {
            URL url = new URL(urlString);
            conn = url.openConnection();

            // Just to make the exception happen
            conn.getInputStream();

            System.out.println("Success!");
        } catch(IOException ex) {
            System.out.println("Error!");
            System.out.println();

            // Method 2 with access to the URLConnection object
            // (Method 1 would have been having the connection as HttpURLConnection from the beginning.)
            int responseCode = 0;
            System.out.println("Trying method 2 to get status code");

            try {
                if(conn != null) {
                    // Casting to HttpURLConnection allows calling getResponseCode
                    responseCode = ((HttpURLConnection)conn).getResponseCode();
                } else {
                    System.out.println("conn variable not set");
                }
            } catch(IOException ex2) {
                System.out.println("getResponseCode threw: " + ex2);
            }

            System.out.println("Status code from calling getResponseCode: " + responseCode);
            System.out.println();

            // Method 3 without access to the URLConnection object
            responseCode = 0;
            System.out.println("Trying method 3 to get status code");

            // First we try parsing the exception message to see if it contains the response code
            Matcher exMsgStatusCodeMatcher = Pattern.compile("^Server returned HTTP response code: (\\d+)").matcher(ex.getMessage());
            if(exMsgStatusCodeMatcher.find()) {
                responseCode = Integer.parseInt(exMsgStatusCodeMatcher.group(1));
            } else if(ex.getClass().getSimpleName().equals("FileNotFoundException")) {
                // 404 is a special case because it will throw a FileNotFoundException instead of having "404" in the message
                System.out.println("Got a FileNotFoundException");
                responseCode = 404;
            } else {
                // There can be other types of exceptions not handled here
                System.out.println("Exception (" + ex.getClass().getSimpleName() + ") doesn't contain status code: " + ex);
            }

            System.out.println("Status code from parsing exception message: " + responseCode);
            System.out.println();
        }

        System.out.println("-------");
        System.out.println();
    }

    public static void main(String []args) throws MalformedURLException {
        testUrl("https://httpbin.org/status/200");
        testUrl("https://httpbin.org/status/404");
        testUrl("https://httpbin.org/status/403");
        testUrl("http://nonexistingsite1111111.com");
    }
}

Output of the example code:
Testing URL https://httpbin.org/status/200
Success!
-------

Testing URL https://httpbin.org/status/404
Error!

Trying method 2 to get status code
Status code from calling getResponseCode: 404

Trying method 3 to get status code
Got a FileNotFoundException
Status code from parsing exception message: 404

-------

Testing URL https://httpbin.org/status/403
Error!

Trying method 2 to get status code
Status code from calling getResponseCode: 403

Trying method 3 to get status code
Status code from parsing exception message: 403

-------

Testing URL http://nonexistingsite1111111.com
Error!

Trying method 2 to get status code
getResponseCode threw: java.net.UnknownHostException: nonexistingsite1111111.com
Status code from calling getResponseCode: 0

Trying method 3 to get status code
Exception (UnknownHostException) doesn't contain status code: java.net.UnknownHostException: nonexistingsite1111111.com
Status code from parsing exception message: 0

-------


text:
Q: Why does the javascript onchange event not fire if autocomplete is on? I have a textbox with an onchange event. Why does this event not fire when the user uses the autocomplete feature to populate the textbox?
I am working with Internet Explorer. Is there a standard and relatively simple solution to workaround this problem, without me having to disable the autocomplete feature?

A: Building on Tim C's answer, here is the simple jquery I came up with to handle this for all text boxes on a page:
$("input[type=text]").bind("focus change",function(){
    this.previousvalue = this.value;
}).blur(function(){
    if (this.previousvalue != this.value){
        $(this).change();
    }
})

If you don't care about onchange firing multiple times, you can make it simpler:
$("input[type=text]").blur(function(){
    $(this).change();
})

A: I just found that using jQuery 1.4 to set change event can solve this issue.  It seems the easiest solution to this issue if you are already familiar with jQuery.

A: I just turn Autocomplete off for the text boxes I need to fire a text change event
'Turn off Auto complete
'(it needs to fire the text change event)
 txtYourTextBox.Attributes.Add("AutoComplete", "off")

Just put that in the page load.
Alternately, you can add the attribute to your markup on the input element or the entire form:
<input type=text autocomplete=off>

or
<form autocomplete=off>

A: Last time I had that issue, I ended up using the onpropertychange event for Internet Explorer instead. I read about that here on MSDN: it is the recommended way to get around it.

A: I've encountered this annoying feature before and my solution at the time was to use the onfocus event to record the current value of the text box, and then use the onblur event to check whether the current value now matches the value saved during onfocus. For example
<input type="text" name="txtTest" value="" onfocus="this.originalvalue=this.value" onblur="if (this.value != this.originalvalue) alert('Test has changed')"/>

A: I found that the following jQuery (v1.10+) JavaScript does work in the case of text being auto-completed for HTML text input fields. This was tested to work reliably at least in Safari 6.1.1 on Mac OS X 10.8.5, but should work in other compliant browsers also:
$("input:text[id=text_field_id]").bind("focus change keyup blur", function(event) {
// handle text change here...
});

It seemed the addition of the blur event handler was the key to making this work, although the other event handlers help ensure that the event handler is called any time the text changes, whether due to an edit or new input by the browser's auto-complete feature.
Simply replace the "input:text[id=text_field_id]" code above with the relevant selector for your desired text input field, or if using the id attribute to refer to your field, replace text_field_id with your text field's id attribute value.


text:
Q: Typo3 error 'There is no column with name 't3ver_oid' on table 'tx_news_domain_model_news'.' I updated all dependencies according to this post but still get the same error.
Since I'm new to TYPO3 I don't know what else I can do.
Can somebody help me with this problem?

A: if you have a composer based typo3 installation you need to add the requirements to composer.json and not ext_emconf.php as in newer typo3 version composer is the only truth in loading order.
and ext_emconf.php is only considered if you running a non composer installation


text:
Q: Set-DefaultScaffolder : Cannot get an instance of EnvDTE.DTE when debugging T4Scaffolding.Core Nuget package - Advanced Powershell debugging I am trying to debug T4Scaffolding.Core Nuget package from outside Visual Studio 2012.
I am using Powershell ISE with Powershell 3.0 installed and run under CLRVersion 4.0.30319.
I first import several Nuget related items:
- Profile.ps1
- nuget.psm1
- NuGet.Cmdlets.dll
I am also setting the current location to set-location "\ClassLibrary1\"
and obtained the only DTE instance currently running (I previously opened MySolution in VS 2012 that has a class library and an asp.net MVC 4 application in it)
$dte = [runtime.interopservices.marshal]::GetActiveObject("visualstudio.dte")

I skipped importing Get-Project cmdlet from NuGet.Cmdlets.dll binary module, so I can create my own cmdlets: Get-Project
that gets my MVC project this way:
$project = $dte.Solution.Projects.Item("MvcApplication1\MvcApplication1.csproj")

I am able to step into init.ps1:
  \packages\T4Scaffolding.Core.1.0.0\tools\init.ps1
but the code fails when executing:
Set-DefaultScaffolder -Name CustomTemplate -Scaffolder T4Scaffolding.CustomTemplate -SolutionWide -DoNotOverwriteExistingSetting

Set-DefaultScaffolder : Cannot get an instance of EnvDTE.DTE
At line:1 char:1
+ Set-DefaultScaffolder -Name CustomTemplate -Scaffolder T4Scaffolding.CustomTempl ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (:) [Set-DefaultScaffolder], InvalidOperationException
+ FullyQualifiedErrorId : T4Scaffolding.Cmdlets.SetDefaultScaffolderCmdlet

I also tried pointing to my $project name (omitting -SolutionWide) with the same results.:
Set-DefaultScaffolder -Name CustomTemplate -Scaffolder T4Scaffolding.CustomTemplate -Project ($project).Name -DoNotOverwriteExistingSetting

I could observe that EnvDTE.dll is loaded into Powershell ISE environment by using:
[System.Threading.Thread]::GetDomain().GetAssemblies()

Hopefully someone will be interested in achieving the same goal (stepping line by line through init.ps1 and install.ps1 of a Nuget package outside Visual Studio).
Thanks,
Rad
Stack Overflow: question I used as a starting point

A: I got same error message:
Set-DefaultScaffolder : Cannot get an instance of EnvDTE.DTE

but in different scenario. I was using scaffold in VS2015, installed T4Scaffolding.Core. Then I found the solution from this link

By installing Windows Management Framework 4.0 the error is gone and my scaffold works again.
Hopes this can help.


text:
Q: Change variable values through getter Typescript Angular 2 I'm trying to change the value in a Variable if the recieved content from a Json is empty. My approach is it to alter my getter Method. For some reasons it seems like the getter Method doesn't get called and it changes nothing, even though I make a call on it. Maybe you Guys can help me.
Here I try to customise my getter, but at runtime it doesn't get used:
export class Chart {
   private _options: any;

   get options(): any {
     if (this._options){
        this._options = {rotation: Math.PI, circumference: Math.PI};
        return this._options;
     } else {
        console.log(this._options);
        return this._options;
     }
   }
}

And here is my component.ts class where I try to use this Variable:
import {Component, Input, OnInit} from '@angular/core';
import {Chart} from "../main-content/entity/dashboard-config-fetcher";

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

  @Input()
  chart: Chart;

  public options: any;

  constructor() { }

  ngOnInit() {
    this.options = this.chart.options;
    }
}

Thanks in Advance

A: If i understood you correctly I think ur missing a !
if (this._options) --> if(!this.options)

Otherwise you will return undefined if there is nothing stored in the _options variable


text:
Q: angularJS -npm-debug.log Beginner:
Trying to set up my work environment with angular yeoman and grunt following this tutorial:
Learn realtime web apps
I'm on the first steps. As I run this command:
sudo npm install -g grunt-cli

I get this error:

Please include the following file with any support request:
  /Users/jose/development/angularBlog/npm-debug.log

and then it is all errors after that..hope someone can orient me a bit.
thanks,
jose


text:
Q: How to send an authentication email in django? How can I use the django email framework that after a user registers, I send him a special link that will confirm his account. I know there are question about how to send emails, but please help me with authentication.

A: Forms.py
from django.db.models import Q
from django.core.exceptions import ObjectDoesNotExist
from django.contrib.auth.models import User
from django import forms
from django.contrib.auth import authenticate

class LoginForm(forms.Form):
    email = forms.CharField()
    password = forms.CharField(
        widget=forms.PasswordInput(render_value=False)
        )

    def clean(self):
        user = self.authenticate_via_email()
        if not user:
            raise forms.ValidationError("Sorry, that login was invalid. Please try again.")
        else:
            self.user = user
        return self.cleaned_data

    def authenticate_user(self):
        return authenticate(
            username=self.user.username,
            password=self.cleaned_data['password'])

    def authenticate_via_email(self):
        """
            Authenticate user using email.
            Returns user object if authenticated else None
        """
        email = self.cleaned_data['email']
        if email:
            try:
                user = User.objects.get(email__iexact=email)
                if user.check_password(self.cleaned_data['password']):
                    return user
            except ObjectDoesNotExist:
                pass
        return None

Views.py
def LoginRequest(request):
    form = LoginForm(request.POST or None)
    if request.method == 'POST' and form.is_valid():
        user = form.authenticate_user()
        login(request, user)
        return HttpResponseRedirect(reverse('Hello'))

    return render(request, 'login.html',{'form': form})

A: The code below is explained in the post by Farhadur Reja Fahim. TO gain deeper knowledge of the code visit his post Email COnfirmation
settings.py
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'youremail@gmail.com'
EMAIL_HOST_PASSWORD = 'yourpassword'
EMAIL_PORT = 587

token.py
from django.contrib.auth.tokens import PasswordResetTokenGenerator
from django.utils import six
class TokenGenerator(PasswordResetTokenGenerator):
    def _make_hash_value(self, user, timestamp):
        return (
            six.text_type(user.pk) + six.text_type(timestamp) +
            six.text_type(user.is_active)
        )
account_activation_token = TokenGenerator()

forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class SignupForm(UserCreationForm):
    email = forms.EmailField(max_length=200, help_text='Required')
    class Meta:
        model = User
        fields = ('username', 'email', 'password1', 'password2')

views.py
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.contrib.auth import login, authenticate
from .forms import SignupForm
from django.contrib.sites.shortcuts import get_current_site
from django.utils.encoding import force_bytes, force_text
from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode
from django.template.loader import render_to_string
from .tokens import account_activation_token
from django.contrib.auth.models import User
from django.core.mail import EmailMessage
def signup(request):
    if request.method == 'POST':
        form = SignupForm(request.POST)
        if form.is_valid():
            user = form.save(commit=False)
            user.is_active = False
            user.save()
            current_site = get_current_site(request)
            mail_subject = 'Activate your blog account.'
            message = render_to_string('acc_active_email.html', {
                'user': user,
                'domain': current_site.domain,
                'uid':urlsafe_base64_encode(force_bytes(user.pk)),
                'token':account_activation_token.make_token(user),
            })
            to_email = form.cleaned_data.get('email')
            email = EmailMessage(
                        mail_subject, message, to=[to_email]
            )
            email.send()
            return HttpResponse('Please confirm your email address to complete the registration')
    else:
        form = SignupForm()
    return render(request, 'signup.html', {'form': form}

def activate(request, uidb64, token):
    try:
        uid = force_text(urlsafe_base64_decode(uidb64))
        user = User.objects.get(pk=uid)
    except(TypeError, ValueError, OverflowError, User.DoesNotExist):
        user = None
    if user is not None and account_activation_token.check_token(user, token):
        user.is_active = True
        user.save()
        login(request, user)
        # return redirect('home')
        return HttpResponse('Thank you for your email confirmation. Now you can login your account.')
    else:
        return HttpResponse('Activation link is invalid!')

acc_active_email.html
{% autoescape off %}
Hi {{ user.username }},
Please click on the link to confirm your registration,
http://{{ domain }}{% url 'activate' uidb64=uid token=token %}
{% endautoescape %}

urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
    url(r'^$', views.home, name='home'),
    url(r'^signup/$', views.signup, name='signup'),
    url(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
        views.activate, name='activate'),
]


text:
Q: Cannot access nas from wired network but with wifi yes I please need help to understand one problem that is driving me crazy.
I have at home a lan network and recently i had to change router, so i put one that i already had: an Archer D7 from tp-linlk with the last firmware.
When i changed router, i had to change also position to it, so i arranged cables to make little order in that room.
I have a buffalo linkstation connected with cable to router. I has smb 2.0 enabled.
I have an old HP desktp PC with windows 10 freshly installed (it had Windows 7 but when i updated it hoping to solve this problem) and my laptop with windows 10 too. The dekstop pc is connected with cable.
From both pc if i type \nas\ (or the ip 192.168.2.6), i type username and password and then:

*

*using Wifi (integrated on my laptop, with an usb dongle on pc desktop) i can see folders and i can browse them

*using wired connection, after insert my credentials (correct) i can see only 1st level of shared folders, but i can't browse them.
it stays there long time without any error but "working" cursors. If i switch to wifi, it enters inside folders.

Here everything i tried:

*

*change cable

*change port on router

*update pc desktop to windows 10

*change the rj connectors to nas and dekstop cables

*leave connected only the nas and 1 pc

*tried with my laptop (as i noticed the problem on my desktop pc, so i tried with my laptop)

*disable wifi guest network on router

*disable smb 1 on pc

*disable ipv6 on pc

*uninstall and reinstall network adapter on

*disable windows firewall and defender (i still have not installed any antivirus)

*change dns server to 192.168.2.1 and 8.8.8.8

*access with ip instead of nas' name

*allow everything in advanced sharing center for all profiles

*sharing a folder from my laptop it is accessible from the desktop one (it works)

*on nas share a folder browsable by anyone (i can't go inside it)

*tried to use Wireshark but i don't know what to search

I finished ideas about what problem can be and what to do.
If you please have any suggestion i will appreciate it.
Thank you very much
Have a nice day

A: I am faced with a similar issue on a win11 home Asus laptop. On the two other computers on the network, all my NAS show up in Ethernet, on this it does not. It also will not appear on wifi unless I type in the NAS name, on Ethernet it returns an error typing the NAS name.
On both wifi and Ethernet, I can ping the address and it returns with no errors.
I attempted the reset and after rebooting, the Ethernet no longer finds ANY of the NAS's on the network. Wifi still works, but I still have to access the NAS by entering the address into the address bar, it does not display in the 'network' list.


text:
Q: Best practice for SharePoint vanity url/redirection My employer uses MOSS 2007 for our company intranet.  It runs solely on secure http and is also exposed to the outside world via ISA.  I currently have a request to add a forwarding URL to our site so that something like the following will occur:
intranet.mycompany.com/vanityname
redirects to ->
intranet.mycompany.com/somedeeplink/default.aspx
I fully expect this sort of thing will become more popular with our users as time goes on.  So I am looking for a solution that scales.  I have read various articles about creating a /site/ with forwarding meta tags or a forwarding SharePoint page type.  I've also seen some that talk about adding virtual directories, etc directly in IIS.  All these solutions seem to be overkill and inevitably take up more memory or processing time on the web servers.
I am currently leaning towards writing an http module that can be configured in the web.config and perform redirects.  I wanted to get feedback to see if anyone else has done something similar in SharePoint 2007 and had any suggestions.  Again, I'd like to implement something that scales without making major changes later on and is going to put minimal processing burden on our web servers.  Thanks!

A: Ive implemented url redirecting with MOSS using the HTTP module route. I documented the code I used and what parameters worked the best for me here;
http://scaredpanda.com/2008/08/url-rewriting-with-sharepoint-moss-2007/
Take a look and let me know if this helps you and if you have any questions.
Update: The link above is no longer valid, so here text from the page that I used for URL redirect.
After messing around for a little bit it, I came up with a good way to do it. When I was looking for examples on the web there were a lot of people saying that it couldnt be done. But in the end it actually didn't take much to implement it. Here's an HttpModule that I wrote to do the work.
The key pieces are the this.app.BeginRequest += new EventHandler(app_BeginRequest) which
steps in front of the request and allows the module to get its redirect on.
And HttpContext.Current.RewritePath(redirect, false); will push the necessary headers n such forward so that the receiving .aspx page will understand how to correctly post back.
using System;
using System.Data;
using System.Data.SqlClient;
using System.Reflection;
using System.Collections;
using System.Text;
using System.Web;
using System.Web.Caching;
using System.Web.SessionState;
using System.Security.Cryptography;
using System.Configuration;
using System.Threading;
using System.IO;
using System.Security;
using System.Security.Principal;

namespace ScaredPanda
{
    public sealed class RewriteHttpModule : IHttpModule
    {
        HttpApplication app = null;
        ///
        /// Initializes the httpmodule
        ///
        public void Init(HttpApplication httpapp)
        {
            this.app = httpapp;
            this.app.BeginRequest += new EventHandler(app_BeginRequest);
        }

        public void app_BeginRequest(Object s, EventArgs e)
        {
            try
            {
        //determine if the income request is a url that we wish to rewrite.
        //in this case we are looking for an extension-less request
                string url = HttpContext.Current.Request.RawUrl.Trim();
                if (url != string.Empty
                    && url != "/"
                    && !url.EndsWith("/pages")
                    && !url.Contains(".aspx")
                    && url.IndexOf("/", 1) == -1)
                {
                    //this will build out the the new url that the user is redirected
                    //to ie pandas.aspx?pandaID=123
                    string redirect = ReturnRedirectUrl(url.Replace("/", ""));

            //if you do a HttpContext.Current.RewritePath without the 'false' parameter,
                    //the receiving sharepoint page will not handle post backs correctly
            //this is extremely useful in situations where users/admins will be doing a
                   //'site actions'  event
                   HttpContext.Current.RewritePath(redirect, false);
                }
            }
            catch (Exception ex)
            {
                //rubbish
            }
        }
    }
}

A: Have you looked into Alternate Access Mappings?
http://technet.microsoft.com/en-us/library/cc263208.aspx

A: If you are open to paying for a solution.  Have a look:
NOT FREE -> http://www.muhimbi.com/Products/SharePoint-URL-Shortener.aspx

A: Depending on the number of redirects you might want to implement an HTTP module as stated) but how about checking out
FREE -> http://www.codeplex.com/sharepointsmart404

A: Use the URL Rewrite feature in IIS. (I believe it's an IIS 7 extension)
http://www.iis.net/download/urlrewrite


text:
Q: My purge command keeps getting rate limited This is my purge command and although it works fine it keeps getting rate limited after I purge 30 massages or more.
@commands.command()
async def purge(self, ctx, num):
   '''
   Clears messages.
   '''
   embed = discord.Embed(title="**MESSAGES PURGED**", description=" ", color=0x0059ff)
   async for message in ctx.channel.history(limit=int(num) + 1):
   await message.delete(delay=0.5)
   await ctx.send(embed=embed)

Any help is appreciated

A: I looked at your code and I understood that you are using a difficult path to create a purge command. Discord.py library has a coroutine called purge whose job is just to delete messages. Rather than using a loop and various other methods, it would be better to use it.

I created a purge command first which has the following code:
@nucleobot.command()
@commands.has_permissions(manage_messages=True)
async def purge(ctx, limit: int):
    await ctx.message.delete()
    await asyncio.sleep(1)
    await ctx.channel.purge(limit=limit)
    purge_embed = discord.Embed(title='Purge [!purge]', description=f'Successfully purged {limit} messages. \n Command executed by {ctx.author}.', color=discord.Colour.random())
    purge_embed.set_footer(text=str(datetime.datetime.now()))
    await ctx.channel.send(embed=purge_embed, delete_after=True)

How does this code work?

*

*The command usage is deleted, i.e., !purge 10 would be deleted when sent into the chat.

*It would pause for 1 second due to await asyncio.sleep(1). You would need to import asyncio in order to use it. (You might know that already :D)

*The number of messages your entered are cleared from the channel using await ctx.message.delete(limit=limit) (This is a discord.py coroutine)

*purge_embed is the embed variable which is used to send the embed after the deletion. I have used datetime module to add the time of the command completion on the embed. (You need to import datetime as well, but only if you want to use it. If not then remove the footer code.)
This would make up your complete and working purge command. :D

Examples with images.
I created a new channel and added 10 messages with numbers from 1 to 10 as shown below:

Then I entered the command in the message box and it was like (I know it was not needed but never mind):

After I sent this message and the command was executed, the purge successful embed was posted by the bot:

I was glad I could help. Any doubts of confusions are appreciated. Ask me anytime. :D
Thank You! :)


text:
Q: Trouble querying documents using CosmosDB SDK V3 I am trying to update a document in my CosmosDB so I want to find the id of the existing document using the following query
string seasonDocumentId = null;

            FeedIterator setIterator = container.GetItemQueryStreamIterator(
                "SELECT * FROM c where c.brand = 'hm' and c.DocumentType = 'Seasons'",
               requestOptions: new QueryRequestOptions()
               {
                   PartitionKey = new PartitionKey("hm"),
                   MaxConcurrency = 1,
                   MaxItemCount = 1
               });

            while (setIterator.HasMoreResults)
            {
                using (ResponseMessage response = await setIterator.ReadNextAsync())
                {
                    using (StreamReader sr = new StreamReader(response.Content))
                    using (JsonTextReader jtr = new JsonTextReader(sr))
                    {
                        JsonSerializer jsonSerializer = new JsonSerializer();
                        SeasonInformation seasons = jsonSerializer.Deserialize<SeasonInformation>(jtr);
                        seasonDocumentId = seasons.id;
                        int i = 0;
                    }
                }
            }

The problem is that I always get NULL value for seasonDocumentId even though I know the actual query is correct and returns value if I use the Data Explorer to run the query so I must be missing something in the stream conversions but I cannot put my finger on what I am doing wrong.
Model looks like this
class SeasonInformation
    {
        public string id { get; set; }
        [JsonProperty("brand")]
        public string Brand { get; set; }
        public string IntegrationSource { get; set; }
        public string DocumentType { get; set; }
        public string UpdatedDate { get; set; }
        public string UpdatedDateUtc { get; set; }
        public string UpdatedBy { get; set; }
        public JObject OriginalData { get; set; }
    }

Actual document in CosmosDB looks like this
{
    "id": "f05182d2-0a18-4cc4-b2df-585ad0464abb",
    "brand": "hm",
    "IntegrationSource": "HAPI",
    "DocumentType": "Seasons",
    "UpdatedDate": "3/12/2019 20:02:42",
    "UpdatedDateUtc": "2019-12-03T13:02:42.01Z",
    "UpdatedBy": "HAPI_HM_Seasons",
    "OriginalData": {
        "corporateBrandId": 0,
        "current": "201910"
    },
    "_rid": "xxx==",
    "_self": "dbs/HwVmAA==/colls/xxx=/docs/xxx==/",
    "_etag": "\"3e00bdf8-xxx-0c00-xxx-5de65cef0000\"",
    "_attachments": "attachments/",
    "_ts": 15753xxxx78159
}

A: I implement a simple console app for you and it could get id successfully for you , try the code below :
using Microsoft.Azure.Cosmos;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace cosmosDBSDKV3
{
    class Program
    {
        static void Main(string[] args)
        {
            var dbName = "<db name>";
            var containerName = "<container name>";

            CosmosClient client = new CosmosClient("<cosmos db url>", "<key here>");
            Database database = client.GetDatabase(dbName);
            Container container = database.GetContainer(containerName);

            ItemFeed(container).GetAwaiter().GetResult();

            Console.ReadKey();
        }

        private static async Task ItemFeed(Container container)
        {
            FeedIterator<SeasonInformation> setIterator = container.GetItemQueryIterator<SeasonInformation>(
                "SELECT * FROM c where c.brand = 'hm' and c.DocumentType = 'Seasons'",
               requestOptions: new QueryRequestOptions()
               {
                   PartitionKey = new PartitionKey("hm"),
                   MaxConcurrency = 1,
                   MaxItemCount = 1
               });

            List<SeasonInformation> seasonInformations = new List<SeasonInformation>();

            // SQL

            while (setIterator.HasMoreResults)
            {
                int count = 0;
                foreach (SeasonInformation item in await setIterator.ReadNextAsync())
                {
                    count++;
                    seasonInformations.Add(item);
                }
            }

            foreach (SeasonInformation item in seasonInformations) {
                Console.WriteLine(item.id);
                Console.WriteLine(item.Brand);
            }

        }

        class SeasonInformation
        {
            public string id { get; set; }
            [JsonProperty("brand")]
            public string Brand { get; set; }
            public string IntegrationSource { get; set; }
            public string DocumentType { get; set; }
            public string UpdatedDate { get; set; }
            public string UpdatedDateUtc { get; set; }
            public string UpdatedBy { get; set; }
            public JObject OriginalData { get; set; }
        }
    }

}

In my cosmos db , this is my query result :

Code result :

Hope it helps .


text:
Q: How to remove black borders of youtube embed video from ? I tried making the youtube embed video's right and left black borders using  to disappear but it still does not, and tried looping with loop=1 and does not loop either.
I wouldn't mind the video itself going off screen, preferably contained inside the screen without borders. I just want the visual itself to fully cover the screen and have the black borders on left and right to disappear, and also put it on loop as well.

What could I be doing wrong?
Here is the code:

.nonClickingContainer {
  width: 100vw;
  height: 100vh;
  position: relative;
}
.catVideo {
  height: calc(100vh + 50px);
  width: 100%;
}

A: Follow this link How to make a YouTube embedded video a full page width one?. If you don't understand just Add a ID to your iframe something like video

and then add this JavaScript code to your JS file
$(function(){
$('#video').css({ width: $(window).innerWidth() + 'px', height: $(window).innerHeight() + 'px' });

$(window).resize(function(){
$('#video').css({ width: $(window).innerWidth() + 'px', height: $(window).innerHeight() + 'px' });
  });
});

and remove those css code from your css file
.nonClickingContainer {
  width: 100vw;
  height: 100vh;
  position: relative;
}
.catVideo {
  height: calc(100vh + 50px);
  width: 100%;
 }

Sorry I forget to tell you that you need to call jQuery if you not already called it.