text:
Q: How to use Rnw and bib files in Lyx? I am writing for publication in Transportation Research Board. Someone un-officially created a LaTeX template for the journal (here). The template consists of 3 files with these extensions:

*

*.bib

*.rnw

*.bst

How can I get started with using these files in Lyx?

A: I just came accross a similar problem but I am using Texmaker. Yet you might find a way to transfer it to another software. After several trials, here is what I came with:

*

*Install R

*In your editor, you should be able to customize the build options. Add this command:
"C:/Program Files/R/R-3.1.1/bin/x64/R.exe" CMD Sweave %.Rnw

(if you are with a 64x, check the version of R as the directory changes with it)
"C:/Program Files/R/R-3.1.1/bin/R.exe" CMD Sweave %.Rnw

esle.

*Run the command, it will output a .tex file

*Use your .tex file as usual. You might get an error like Sweave.sty not found.

*To remove this error you need to add the path:
"C:\Program Files\R\R-3.1.1\share\texmf"

to your LaTeX distribution. If MikTeX, open settings as admin > root > add.
However, I can't get the wordcount working for now.
Cheers,


text:
Q: Автоматический запуск приложения при его аварийном завершении Есть приложение, написанное на Qt. Оно должно будет крутиться на сервере. приложение на данный момент не стабильное, бывает падает. Нужно что бы кто-то(что-то) отслеживало его падение и запускало процесс снова, автоматически.
Предложите свои варианты.

A: Если приложение не требует наличия визуального интерфейса (или он реализован отдельным модулем) - запустите его как службу и используйте штатный механизм рестарта службы при проблемах.

A: Масса вариантов: глючное приложение создает Mutex, а следящее его проверяет с нужной периодичностью. Приложение упало, мьютекс исчез - запускаем заново.
Следящий процесс проверяет наличие глючного по имени, перебирая все процессы с некоторой периодичностью.
Третий - DebugAPI, но это значительно сложнее.

A: В командной строке:
for /l %q in (0) do start /wait notepad.exe

под bat'ник надо немного подправить.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why does this nested SVG not work in Firefox? I'm creating a contact sheet that displays all the icons in a library. I've built it using nested SVGs. Here's a minimal version:
<svg xmlns="http://www.w3.org/2000/svg" version="1.1"
    xmlns:xlink="http://www.w3.org/1999/xlink"
    xmlns:svgjs="http://svgjs.dev/svgjs" viewBox="0 0 200 200">
    <svg id="sheet_core" width="200" height="200" x="0" y="0">
        <svg width="200" height="200" x="0" y="0">
            <symbol id="piece" viewBox="-2.5 -2.5 105 105">
                <circle r="50" cx="50" cy="50" data-playerfill="true" fill="#ffffff" stroke-width="5" stroke="#000000"></circle>
            </symbol>
            <use href="#piece" x="25" y="25" transform="matrix(0.75,0,0,0.75,6.25,6.25)"></use>
            <text x="0" y="192.1015625" svgjs:data="{"leading":"1.3"}">piece</text>
        </svg>
    </svg>
</svg>

This works fine in Chrome and Opera, but does not work in Firefox.
You should see this: https://ibb.co/VT8SSSd.
But in Firefox, I get this: https://ibb.co/5L7PP22.
If I inspect the code, the <symbol>s are greyed out, suggesting they are not being referenced, when they very clearly are right afterwards. I also tried moving all the symbols into a global <defs>, but that didn't work either. Any ideas how to tweak this so it will work in Firefox too?
These SVG browser differences are maddening, I've got to say.

A: Once I loaded the SVG on my website so I could test in some different environments, it suddenly started working. My suspicion is there's some weird CSPF happening, perhaps only on my end. But the SVG does not appear to be the fundamental problem.
As you were.


text:
Q: Crossfade images with jQuery Hi I'm trying to accomplish a crossfade effect for my banner images on my homepage. I'm doing this with jQuery and the fading effect is working fine.
This is my  code:

As I said this is working fine however I've got one issue.  In order for this to work I need to apply position:absolute to the .banner-test img class. Now I've also got another div within the .banner-test class to display some text on top of the banner image.
The code looks like this :

Sample Text

And the css for the #text :
 #text {
position:absolute;
bottom:35px ;
left:10px;
width:70% ;
background-color:#104E8B;
font-size:1em;
color:white;
opacity:0.95;
filter:alpha(opacity=95); /* IE transparency */
}
.text1 {
padding:13px;
margin:0px;
}
.banner-test {
  display: block;
  position: relative;
}

So if I apply absolute positioning to the image it messes up the layout with the text (everything is pushed to the top of the page).
Can anybody think of a workaround for this?
EDIT
https://jsfiddle.net/ztrez888/1/embedded/result/ this is the fiddle - if position absolute is applied to the .banner-test img the text disappears

A: You said: (everything is pushed to the top of the page)
Its because your wrapper element .banner-test doesn't have a static height set. so when you apply a absolute position to the images in it .banner-test get shrink to height of the #text .text1.
Either set a height in the css:
.banner-test {
  display: block;
  position: relative;
  height:200px; /* <--put the height of img */
}

or calculate it with jQuery:
$(document).ready(function(){
    var arr = $('.banner-test img').map(function(){ // get the heights of imgs in array
                  return $(this).height();
             }).get(),
       h   = Math.max.apply(Math, arr); // find out the greatest height in it.

    $('.banner-test').css('height', h); // set the height here.
    // run every 7s
    setInterval('cycleImages()', 7000); // then cycle the images.
});

cycleImages() is been called in the setInterval and you have bannerImages() function on the page. I am assuming you have this cycleImages() function.

Updates:
  #text {
    position: absolute;
    bottom: 30px;
    left: 10px;
    width: 100px;
    background-color: #104E8B;
    font-size: 1em;
    color: white;
    opacity: 0.95;
    filter: alpha(opacity=95);
    /* IE transparency */
    z-index: 5;  /* <----change these here*/
    left: 10%;
    top: 0;
  }

Updated fiddle


text:
Q: How to add "WITH" clause to SELECT query with sqlbuilder I am using Java and SQLBuilder from healthmarketscience.sqlbuilder and I am trying to add WITH clause to my SELECT query dynamiclly.
My current query build with:
selectQuery.addJoins(SelectQuery.JoinType.LEFT_OUTER, Table.joinToQuery);

The expected result should be:
LEFT OUTER JOIN Table WITH(table_convert_subselect=1) ON (...)


text:
Q: How do i put text after an image slider This is the code

Mahatma Gandhi

    <input type="radio" name="r" id="r1" checked>
    <input type="radio" name="r" id="r2">
    <input type="radio" name="r" id="r3">
    <input type="radio" name="r" id="r4">
    <input type="radio" name="r" id="r5">

1969-1948

"An eye for eye only ends up making the whole world blind."

Biography

//This part here is not coming after the slider

  Mohandas Karamchand Gandhi (2 October 1869 – 30 January 1948) was an Indian lawyer, anti-colonial nationalist, and political ethicist, who employed nonviolent resistance to lead the successful campaign for India's independence from British rule, and in
  turn inspired movements for civil rights and freedom across the world. The honorific Mahātmā first applied to him in 1914 in South Africa, is now used throughout the world. Born and raised in a Hindu family in coastal Gujarat, western India, Gandhi
  trained in law at the Inner Temple, London, and was called to the bar at age 22 in June 1891. After two uncertain years in India, where he was unable to start a successful law practice, he moved to South Africa in 1893 to represent an Indian merchant
  in a lawsuit. He went on to stay for 21 years. It was in South Africa that Gandhi raised a family, and first employed nonviolent resistance in a campaign for civil rights. In 1915, aged 45, he returned to India. He set about organising peasants, farmers,
  and urban labourers to protest against excessive land-tax and discrimination. Assuming leadership of the Indian National Congress in 1921, Gandhi led nationwide campaigns for easing poverty, expanding women's rights, building religious and ethnic amity,
  ending untouchability, and above all for achieving Swaraj or self-rule. The same year Gandhi adopted the Indian loincloth, or short dhoti and, in the winter, a shawl, both woven with yarn hand-spun on a traditional Indian spinning wheel, or charkha,
  as a mark of identification with India's rural poor. Thereafter, he lived modestly in a self-sufficient residential community, ate simple vegetarian food, and undertook long fasts as a means of self-purification and political protest. Bringing anti-colonial
  nationalism to the common Indians, Gandhi led them in challenging the British-imposed salt tax with the 400 km (250 mi) Dandi Salt March in 1930, and later in calling for the British to Quit India in 1942. He was imprisoned for many years, upon many
  occasions, in both South Africa and India. Gandhi's vision of an independent India based on religious pluralism was challenged in the early 1940s by a new Muslim nationalism which was demanding a separate Muslim homeland carved out of India. In August
  1947, Britain granted independence, but the British Indian Empire was partitioned into two dominions, a Hindu-majority India and Muslim-majority Pakistan. As many displaced Hindus, Muslims, and Sikhs made their way to their new lands, religious violence
  broke out, especially in the Punjab and Bengal. Eschewing the official celebration of independence in Delhi, Gandhi visited the affected areas, attempting to provide solace. In the months following, he undertook several fasts unto death to stop religious
  violence. The last of these, undertaken on 12 January 1948 when he was 78, also had the indirect goal of pressuring India to pay out some cash assets owed to Pakistan. Some Indians thought Gandhi was too accommodating. Among them was Nathuram Godse,
  a Hindu nationalist, who assassinated Gandhi on 30 January 1948 by firing three bullets into his chest. Gandhi's birthday, 2 October, is commemorated in India as Gandhi Jayanti, a national holiday, and worldwide as the International Day of Nonviolence.
  Gandhi is commonly, though not formally, considered the Father of the Nation in India, and was commonly called Bapu.

This is how it looks like

A:

.left,.right{
width:100%;
float:left;
}

Mahatma Gandhi

      <input type="radio" name="r" id="r1" checked>
      <input type="radio" name="r" id="r2">
      <input type="radio" name="r" id="r3">
      <input type="radio" name="r" id="r4">
      <input type="radio" name="r" id="r5">

1969-1948

"An eye for eye only ends up making the whole world blind."

Biography

  //This part here is not coming after the slider

    Mohandas Karamchand Gandhi (2 October 1869 – 30 January 1948) was an Indian lawyer, anti-colonial nationalist, and political ethicist, who employed nonviolent resistance to lead the successful campaign for India's independence from British rule, and in
    turn inspired movements for civil rights and freedom across the world. The honorific Mahātmā first applied to him in 1914 in South Africa, is now used throughout the world. Born and raised in a Hindu family in coastal Gujarat, western India, Gandhi
    trained in law at the Inner Temple, London, and was called to the bar at age 22 in June 1891. After two uncertain years in India, where he was unable to start a successful law practice, he moved to South Africa in 1893 to represent an Indian merchant
    in a lawsuit. He went on to stay for 21 years. It was in South Africa that Gandhi raised a family, and first employed nonviolent resistance in a campaign for civil rights. In 1915, aged 45, he returned to India. He set about organising peasants, farmers,
    and urban labourers to protest against excessive land-tax and discrimination. Assuming leadership of the Indian National Congress in 1921, Gandhi led nationwide campaigns for easing poverty, expanding women's rights, building religious and ethnic
    amity, ending untouchability, and above all for achieving Swaraj or self-rule. The same year Gandhi adopted the Indian loincloth, or short dhoti and, in the winter, a shawl, both woven with yarn hand-spun on a traditional Indian spinning wheel, or
    charkha, as a mark of identification with India's rural poor. Thereafter, he lived modestly in a self-sufficient residential community, ate simple vegetarian food, and undertook long fasts as a means of self-purification and political protest. Bringing
    anti-colonial nationalism to the common Indians, Gandhi led them in challenging the British-imposed salt tax with the 400 km (250 mi) Dandi Salt March in 1930, and later in calling for the British to Quit India in 1942. He was imprisoned for many
    years, upon many occasions, in both South Africa and India. Gandhi's vision of an independent India based on religious pluralism was challenged in the early 1940s by a new Muslim nationalism which was demanding a separate Muslim homeland carved out
    of India. In August 1947, Britain granted independence, but the British Indian Empire was partitioned into two dominions, a Hindu-majority India and Muslim-majority Pakistan. As many displaced Hindus, Muslims, and Sikhs made their way to their new
    lands, religious violence broke out, especially in the Punjab and Bengal. Eschewing the official celebration of independence in Delhi, Gandhi visited the affected areas, attempting to provide solace. In the months following, he undertook several fasts
    unto death to stop religious violence. The last of these, undertaken on 12 January 1948 when he was 78, also had the indirect goal of pressuring India to pay out some cash assets owed to Pakistan. Some Indians thought Gandhi was too accommodating.
    Among them was Nathuram Godse, a Hindu nationalist, who assassinated Gandhi on 30 January 1948 by firing three bullets into his chest. Gandhi's birthday, 2 October, is commemorated in India as Gandhi Jayanti, a national holiday, and worldwide as the
    International Day of Nonviolence. Gandhi is commonly, though not formally, considered the Father of the Nation in India, and was commonly called Bapu.


text:
Q: My customer wanted to implement SSO on their ADFS environment and it shows them the below error. Is there any troubleshooting steps? MSIS7007: The requested relying party trust 'https://domain/name/sso/saml' is unspecified or unsupported. If a relying party trust was specified, it is possible that you do not have permission to access the trust relying party. Contact your administrator for details.

A: This means that either they have not configured the SAML relying party on ADFS or that they have but have not configured this endpoint.


text:
Q: How to synchronize SharePoint online 2016 with onsite Active Directory using Rest APIs I have a SharePoint online site and a local SharePoint server with user accounts that i want to import to the the online SharePoint site. I know about Azure Active Directory Connect tool that used for connecting SharePoint online, but is there any other way to connect SharePoint with local server like web hooks and Rest API calls to local Active Directory to synchronize user accounts between SharePoint online and Active Directory ?

A: The User Profile must be linked to an existing object in Azure AD as the process for creating a Profile requires you to identify an existing object to bind to. For updating properties that are outside of Azure AD -> SPO sync, use the User Profile Batch Update API to do this in bulk. This is CSOM only, and must run on the local network containing the Domain Controller(s) as Active Directory (or LDAP in general) should not be exposed to an endpoint over the Internet due to creating significant security risks.
Another thing to keep in mind is that Azure AD is where objects are stored/is the identity store; a User Profile in SharePoint [Online] is not an identity store, it is simply a description of the object (user) that can be leveraged in other areas of SharePoint.


text:
Q: how to find slant height using radius and angle for a truncated cone I asked this question a while ago but it got closed. I'm trying to find the slant height or just height for a truncated cone with only the radius and the angles for a hobby project that i've been doing. Its called how to develop, build, and test small liquid-fueled rocket engines by rocket lab. The truncated cone is for the nozzle throat. The base radius (R=1.50225 in) and the top radius (r=0.50075 in). I have looked everywhere but it keeps saying volume and height and surface area. Not learning in 9th grade eather.
      r=0.50079
      ________________ 30˙
     /                \    |
    /                  \   |
   /                    \  |h= unknown
  /                      \ |
 /                        \|
 -------------------------- 60˙    looking for slant height or height   R=1.50225

A:
See (rather terrible) diagram above.
The half-angle of the cone (from the vertical axis) is $\theta$.
By simple right-angle trigonometry, you know that $l = \frac r{\sin \theta} = \frac r{\cos(90^{\circ} - \theta)}$. I'm giving you both forms because I'm not sure which angle you have.
Similarly, $L =  \frac R{\sin \theta} = \frac R{\cos(90^{\circ} - \theta)}$
Find $L-l$ to get the truncated slant height.

A: Here's a method that I think is especially easy to apply if you just know a little trigonometry.

The diagram is a cross-section of your truncated cone. The vertical line in the middle is the axis (centerline) of the cone.
The other vertical line is parallel to the axis and meets the edge of the circle at the upper end of the truncated cone.
So we now have a right triangle with base $R - r = 1.50225 - 0.50075 = 1.0015.$
The height $h$ is $(R - r) \tan 60^\circ$ and the slant height is
$(R - r) \sec 60^\circ$.
You can put any other angle in place of $60$ degrees for a different shape of cone.
But the $60$ degree angle is particularly nice because
$\tan 60^\circ = {\sqrt3}$ and $\sec 60^\circ = 2.$


text:
Q: Is there any built-in way in Yii framework that enables AJAX form submission? In the CustomerController, I have the create action:
public function actionCreate() {
    $model = new Customer;

    $this->performAjaxValidation($model, 'customer-form');

    //only support ajax saving
    if (isset($_POST['Customer']) && Yii::app()->getRequest()->getIsAjaxRequest()) {
              $model->setAttributes($_POST['Customer']);
              $saveSuccess = $model->save();
              if ($saveSuccess) {
                        //should echo a success message
              }
              else {
                        //should echo error messages
              }

              Yii::app()->end();
    }

    $this->render('create', array('customer' => $model));
}

In the view, I am using the CActiveform:
  $form = $this->beginWidget('CActiveForm', array(
      'id' => 'customer-form',
      'enableAjaxValidation' => true,
       'clientOptions'=>array(
          'validateOnSubmit'=>false
               )
          )
  );

As you can see, I set enableAjaxValidation to true, but I set the client options validateOnSubmit to false.
If I set it to true, when the form submits, it will first send an AJAX POST request to the server and then the server will return error messages (if any) in JSON format, CActiveForm will display the error summary automatically in the view and blocks the form submission.
If no error is found, the form will then do a second POST request (which is non-AJAX) and actually submit the form.
But this is not the behavior I am after.
Ideally, I would like to have a single AJAX POST request such that when the form submits, the server will return success or error message and CActiveForm will display them automatically.
Is this something built-in in Yii or I have to write my own codes doing this?

A: To perform ajax submission you need to replace the usual CHtml::submitButton() with ajaxSubmitButton(). Check it here: http://www.yiiframework.com/doc/api/1.1/CHtml#ajaxSubmitButton-detail


text:
Q: Create the square, rectangle, triangle of java in jframe I have a problem with Java As I understood not come Draw Geometric figures in Java, the code and the Following you can help me?
This is the code:
public class Gioco {

    public static void main (String args [])
    {
        PaintRect();

    }

    public static void PaintRect() {

        g.drawRect(100,100,300,300);
        g.drawLine(100,100,100,100);
        g.setBackground(Color.BLACK);
        System.out.println("Trasut");
        credits.setText("Kitebbiv");
        credits.setBackground(null);
        credits.setEditable(false);
        credits.setFocusable(false);
        credits.setBounds(0,0,100,100);
        credits.setForeground(Color.BLACK);
        panel.add(credits);
        g.getPaint();
    }

How can I create a JFrame the triangle, square and rectangle? correct my code thanks

A: Before I even start writing my answer I need to encourage you to read carefully to: How to create a valid Minimal, Complete and Verifiable Example and a Short, Self Contained, Correct Example.

*

*From your (now deleted) code, I see you haven't gone through the Swing Tutorial on Custom Painting yet or you didn't even pay attention to it, this line will cause you problems
static Graphics2D g = new Graphics2D()

*The excessive use of static modifier will harm you, static isn't a cross-method magic word to make your variables be accessible anywhere in your program, you should instead create an instance of your program and call the methods from there (they not being static), see Why are static variables considered evil?, and you should really go back and learn the essentials before adding more complexity to your learning with a GUI and even more with Swing custom painting.

*You're making use of setBounds() method, which suggests (and I can confirm in your deleted code) that you're using a null-layout:
panel.setLayout(null);

You should really consider checking the layout managers

*You're making use of a deprecated method JFrame#show() instead you should be using JFrame#setVisible() method.

*You're manually setting the size of your JFrame, you should instead use a layout manager and call the method JFrame#pack() which will calculate the preferred size for your JFrame or override your component's getPreferredSize().

*On your deleted code, you had a MouseListener attached to a JButton, instead you need to use an ActionListener, see How to use Actions to learn this.

*You're not placing your program on the Event Dispatch Thread (EDT) which could make your program to freeze, because Swing is not Thread safe. You can correct this by writing your main method as follows:
public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            //Your constructor here
        }
    });
}

*You should be more polite: "correct my code thanks" sounds like an order, I would have said that like could you help me? which sounds like a request / petition for someone to give you a hand, because they can, not because they must help you, all the above points correct your code.

After all the above has being said (and which you should read carefully) we can continue to the coding part:
In order to draw a rectangle we need to learn something about a rectangle:

*

*A rectangle has a width and a height, both are different

*The way to draw a rectangle in Swing is with drawRect(x, y, width, height) draw(Shape) of the Graphics2D method where Shape would be an instance of Rectangle2D
To draw a square we need to know that:

*

*A square has a width and a height, both are equal size

*The way to draw a square in Swing is with drawRect(x, y, width, height) draw(Shape) of the Graphics2D method where Shape would be an instance of Rectangle2D
You must be saying... "But the method you're using to draw the square is the same as the rectangle!", well... yep, we are, the difference lies in that we're going to pass a width and height equal size for the square and different size for the rectangle.
To draw a triangle you need to know that:

*

*A triangle has 3 sides, they can be same or different sizes

*We have no method to drawTriangle in Swing, but we have drawPolygon(xPoints, yPoints, nPoints) draw(Shape) of the Graphics2D method, which will draw a Polygon of nPoints (3 in this case), taking the coords from each array element of xPoints for the X coords and yPoints for the Y coords and where Shape would be an instance of Polygon
Now, putting all that together we should have all that code in an overridden method of our JPanel called paintComponent() as shown in the tutorial (See point #1). It should look like this:
@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g); //ALWAYS call this method first!
    g.drawRect(10, 10, 50, 50); //Draws square
    g.drawRect(10, 75, 100, 50); //Draws rectangle
    g.drawPolygon(new int[] {35, 10, 60}, new int[] {150, 200, 200}, 3); //Draws triangle
}

But we also need to override another method getPreferredSize() on our JPanel, (see: Should I avoid the use of setPreferred|Maximum|MinimumSize in Swing? the general consensus says yes), otherwise our JFrame will be smaller than what we want, so it should look like this:
@Override
public Dimension getPreferredSize() {
    return new Dimension(300, 300);
}

Don't forget to call @Override in those methods!
With only those methods we have completed our program to draw the shapes, but I know that if I don't post the whole code you'll end up writing the above methods in a place that won't work or cause you compilation errors, so the whole code (which in fact is a MCVE or SSCCE (see the very first paragraph in this answer to see what each means)) that produces the below output is:

import java.awt.Dimension;
import java.awt.Graphics;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class ShapesDrawing {

    private JFrame frame;
    private JPanel pane;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new ShapesDrawing().createAndShowGui();
            }
        });
    }

    public void createAndShowGui() {
        frame = new JFrame(getClass().getSimpleName());
        pane = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g); //ALWAYS call this method first!
                g.drawRect(10, 10, 50, 50); //Draws square
                g.drawRect(10, 75, 100, 50); //Draws rectangle
                g.drawPolygon(new int[] {35, 10, 60}, new int[] {150, 200, 200}, 3); //Draws triangle
                g.dispose();
            }

            @Override
            public Dimension getPreferredSize() {
                return new Dimension(300, 300);
            }
        };

        frame.add(pane);
        frame.pack();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

I really hope you read every link I posted here, because it's worth it
And if you need to fill the shapes then call fillRect and fillPolygon instead of drawRect and drawPolygon:
@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g); //ALWAYS call this method first!
    g.drawRect(10, 10, 50, 50); //Draws square
    g.fillRect(150, 10, 50, 50); //Fills a square
    g.drawRect(10, 75, 100, 50); //Draws rectangle
    g.fillRect(150, 70, 100, 50); //Fills a square
    g.drawPolygon(new int[] {35, 10, 60}, new int[] {150, 200, 200}, 3); //Draws triangle
    g.fillPolygon(new int[] {185, 150, 215}, new int[] {150, 200, 200}, 3); //Fills triangle
    g.dispose();
}

Edit
As per @MadProgrammer's comment:

Could we avoid using draw/fillPolygon in favor of using the updated Shapes API ... provides much more functionality and is generally easier to use :P

Here's the updated paintComponent method using the Shapes API:
@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g); //ALWAYS call this method first!

    Graphics2D g2d = (Graphics2D) g;
    g2d.draw(new Rectangle2D.Double(10, 10, 50, 50));
    g2d.fill(new Rectangle2D.Double(150, 10, 50, 50));

    g2d.draw(new Rectangle2D.Double(10, 75, 100, 50));
    g2d.fill(new Rectangle2D.Double(150, 75, 100, 50));

    g2d.draw(new Polygon(new int[] {35, 10, 60}, new int[] {150, 200, 200}, 3));
    g2d.fill(new Polygon(new int[] {185, 150, 215}, new int[] {150, 200, 200}, 3));

    g2d.dispose();
    g.dispose();
}

Which produces the following output:


text:
Q: $\sigma(\xi)$ is independent of a fixed $\sigma$-algebra I want to prove that if $\lim_{n->\infty}\xi_n = \xi$ pointwise and each $\xi_n$ is independent from a fixed sigma-algebra $F$ then $\xi$ is independent from $F$.
I understand that $\sigma(\xi)$ will be independent from $F$ too.
How can it be proved: if $\sigma(\xi)$ is independent from $F$ then $\xi$ is independent of $F$?

A: $\sigma (\xi)=\{\xi^{-1} (A): A \in \mathcal B\}$ where $\mathcal B$ is the Borel sigma algebra of $\mathbb R$. The  hypothesis gives  $P(\xi ^{-1}(A) \cap E)=P(\xi ^{-1}(A) )P(E)$  for any Borel set $A$ and any $E \in F$. This is the definition of $\xi$ being independent of $F$.


text:
Q: Install cloud9 pre-requisites on ssh workspace Currently when we make a new developer machine, we install node.js then connect with cloud9 via SSH and it installs the additional things it needs to.
Is there a command I can run at the end of my build script to install the cloud9 pre-requisites earlier? (Just to save waiting for it on first connection.)
Maybe the command on this page:
https://github.com/c9/install

A: Yes, that should work:
curl -L https://raw.githubusercontent.com/c9/install/master/install.sh | bash


text:
Q: Generate random number between 1 and 10 without repetition I want to generate a random number between 1 and 10. When the user clicks on the "next" button then a random question must be printed and questions can not repeat.
The problem is that sometimes the question is repeating.
Can anyone help me or give some reference or tutorial?
- (IBAction)nextQuestion:(id)sender
{
    NSInteger randomNum = arc4random() %10 ;
    int countCounter= counter++;
    [self.btnNext setTitle:@"Next" forState:UIControlStateNormal];

    if(countCounter==4)
    {
        self.btnNext.hidden=YES;
        self.btnQuizDone.hidden=NO;
    }

    switch ( arc4random()%10)
    {
      case 0:
      {
          NSLog(@"zero");

          [lblQuestion setText:@"Q10:question number ten"];

      }
      break;
     case 1:
      {
          NSLog(@"one");
          [lblQuestion setText:@"Q2:question number two"];

      }
      break;
      case 2:
      {
          NSLog(@"two");
          [lblQuestion setText:@"Q6:question number six"];

      }
      break;
      case 3:
      {
          NSLog(@"three");
          [lblQuestion setText:@"Q5:question  number five"];

      }
       break;
      case 4:
      {
          NSLog(@"four");
          [lblQuestion setText:@"Q3:question number three"];

      }
      break;
      case 5:
      {
          NSLog(@"five");
          [lblQuestion setText:@"Q9:question  number nine"];

      }
      break;
      case 6:
      {
          NSLog(@"six");
          [lblQuestion setText:@"Q7:question  number seven"];

      }
      break;
      case 7:
      {
          NSLog(@"seven");
          [lblQuestion setText:@"Q4:question  number four"];

      }
      break;
      case 8:
      {
          NSLog(@"eight");
          [lblQuestion setText:@"Q1:question  number one"];

      }
      break;
      case 9:
      {
          NSLog(@"nine");
          [lblQuestion setText:@"Q8:question  number eight"];

      }
      break;

      default:
          break;
    }
}

A: How about this.
- (IBAction) getNextRandomQues:(id) sender
{
   int randomQuesIndex = (arc4random() % mutableArrayOfQuestions.count) + 1;
   [mutableArrayOfQuestions removeObjectAtIndex: randomQuesIndex];
}

mutableArrayOfQuestions could be array of "Question" (Question could be a class to modal a question) or a simple array of question indexes. Idea is to select the question from mutableArrayOfQuestions randomly and remove it so that next time it will not selected again.

A: There is a simpler approach to do this.
You can simply create a NSMutableArray of 10 numbers:
NSMutableArray* numbers=[[NSMutableArray alloc]init];
for(int i=0; i<10; i++)
{
    [numbers addObject: [NSNumber numberWithInt: i]];
}

And everytime you need a random number, extract one number randomly from the array, and delete it:
int randomIndex= random()%[numbers size];
NSNumber* randomNumber=[numbers objectAtIndex: randomIndex];
[numbers removeObjectAtIndex: randomIndex];

A: What you want is actually a permutation.
Idea 1:
You have N questions. K questions are not used (0 at the beginning)
Algorithm:

*

*Generate random number r = arc4random() % (N - K)

*Find the r-th not used question.

*Register this question as used, decrement K.

Idea 2:
Generate the indices for the questions at the beginning:
Index of questions int indices[] = {0, 1, 2, 3, ..., N}; (generate this from the value of N)
Randomly swap indices - generating a random permutation.
for (int i = 0; i < 10 * N; i++) {
   int pos1 = arc4random() % N;
   int pos2 = arc4random() % N;

   swap(indices, pos1, pos2);
}

A: Like Sulthan said, but use the Fisher-Yates shuffle algorithm.
int i = N;
while (-- i) {
  int pos1 = arc4random() % (i + 1);
  swap(indices, pos1, i);
}

This algorithm is notorious for people getting it wrong (see http://www.codinghorror.com/blog/2007/12/the-danger-of-naivete.html). I've had to fix the above twice already, and I'm still not sure it's right! If at all possible, use a random-shuffle algorithm from a library.

A: In a set of 10 questions you may very well have a question repeated even with random selection.  Each question has a 1 in 10 chance to be selected and in a truly random selection, there is a chance that the same question may be selected again.  This is because the kind of selection you are doing is one where you select the item from the container and then you put it back.
If a question must not be repeated then what you will need to do is to have some kind of a mechanism so that when a question is used, it is not put back into the set of questions from which the selection is made.
So you will need to modify your code so that you have an array of questions and when one is selected, that question is removed from the random selection the next time that you produce a random question.  Then once that random selection is done, you put the removed question back into the set and remove the one just selected.
This means that the first time you select, you will do a 1 in 10 random number.  After that it will always be a 1 in 9 random number.

A: Do this:
-(NSMutableArray *)randomNumberGenrator:(NSMutableArray *)arrValues{

NSUInteger totalcount = [arrValues count];
for (NSUInteger i = 0; i < totalcount; ++i)
 {
    // Select a random element between i and end of array to swap with.
    int nElements = totalcount - i;
    int n = (random() % nElements) + i;
    [arrValues exchangeObjectAtIndex:i withObjectAtIndex:n];
 }
 return arrValues;
}

A: public int[] a = new int[10]{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1};

   public int onNextClickGetRandomQuestionNumber()
   {
       int k = arc4random()%10;

       if (!Exists(k,a))
       {
           for (int i = 0; i < a.Length; i++)
           {
               if (a[i] < 0)
               {
                   a[i] = k;
                   return i;
               }
           }

           for (int i = 0; i < a.Length; i++)
           {
               a[i] = -1;
           }
       }
       else
       {
           onNextClickGetRandomQuestionNumber();
       }

       return -1;

   }

    public  bool Exists(int parameter,int[] Massive)
    {
        for (int i = 0; i < Massive.Length; i++)
        {
            if( parameter == Massive[i])
            {
                return true;
            }
        }
        return false;
    }

thats some crappy i generated , i guess the idea is exactly that you need =)

A: Follow this code
NSMutableIndexSet *indexSet = [NSMutableIndexSet new];

while ([indexSet count]<10) {

int randomNumber = arc4random_uniform(11);

   if(randomNumber!=0)
   {
       [indexSet addIndex:randomNumber];
   }
}


text:
Q: pivot application windows phone 8.1 navigation I am developing a windows phone application for my firm.
I've just manually created  pivot items in a basic page. The application is working fine except the back button navigation. When I click on any button inside a pivot item it is navigating to desired page but when i click back button it is always navigating to pivot item 1 instead of the one from which the click event is originated.
My XAML looks like this
<Grid x:Name="ContentRoot"><Pivot x:Name="Test" Title="test book" FontSize="{ThemeResource TextStyleExtraLargeFontSize}">
        <!--Pivot item one-->
        <PivotItem x:Name="pitem1" Header="item1">
     <Grid>
                <Grid.RowDefinitions>
                        <RowDefinition Height="Auto" />
                        <RowDefinition Height="5*" />
                        <RowDefinition Height="5*" />
                        <RowDefinition Height="5*" />
                    </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="10*" />
                    <ColumnDefinition Width="*" />
                    <ColumnDefinition Width="10*"/>
                    <ColumnDefinition Width="*" />
                    <ColumnDefinition Width="10*" />
                </Grid.ColumnDefinitions>
                <Button x:Name="bt1" Grid.Row="1" Grid.RowSpan="2" Grid.Column="0" Grid.ColumnSpan="1" Content="" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" BorderThickness="0" Click="bt1_Click"/>
                <Button x:Name="bt2" Grid.Row="2" Grid.RowSpan="2" Grid.Column="2" Grid.ColumnSpan="1" Content="" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Click="bt2_Click"/>
                <Button x:Name="bt3" Grid.Row="3" Grid.RowSpan="2" Grid.Column="4" Grid.ColumnSpan="1" Content="" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Click="bt3_Click"/>
                <Rectangle StrokeThickness="0" Grid.Row="1" Grid.RowSpan="3" Grid.Column="0" Grid.ColumnSpan="11" Stroke="#FF015C1F">
                </Rectangle>
            </Grid>
        </PivotItem>
        <!--Pivot item one-->
        <PivotItem x:Name="pitem2" Header="item2" >
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="Auto" />
                        <RowDefinition Height="5*" />
                        <RowDefinition Height="5*" />
                        <RowDefinition Height="5*" />
                        <RowDefinition Height="5*" />
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="10*" />
                        <ColumnDefinition Width="*" />
                        <ColumnDefinition Width="10*" />
                    </Grid.ColumnDefinitions>
                    <Button x:Name="bt4" Grid.Row="1" Content="" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Click="bt4_Click"/ >
                <Button x:Name="bt5" Grid.Row="1" Grid.Column="2" Content="" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Click="bt5_click" />
                </Grid>
        </PivotItem>
        <!--Pivot item two-->
        <PivotItem x:Name="pitem3" Header="item3">
            <Grid >
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="10*" />
                    <RowDefinition Height="10*" />
                    <RowDefinition Height="10*" />
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="10*" />
                    <ColumnDefinition Width="*" />
                    <ColumnDefinition Width="10*" />
                </Grid.ColumnDefinitions>
                <Button x:Name="bt6" Grid.Row="1"  Content="" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Click="bt6_Click"/>
               <Button x:Name="bt7" Grid.Row="1" Grid.Column="2" Content="" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Click="bt7_Click"/>
                <Button x:Name="bt8" Grid.Row="2"  Content="" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Click="bt8_Click" />
              </Grid>
        </PivotItem>

For example : If I click "bt7" present inside the pivot item 3, it navigates to page and when i click back button it is navigating to pivot item 1 instead of item 3.
Am I missing something or the problem is i have created pivot item manually?
I'm new to C# and XAML. Any help would be highly appreciated.
UPDATE :
    public home()
    {
        this.InitializeComponent();
       this.NavigationCacheMode = NavigationCacheMode.Required;
        this.navigationHelper = new NavigationHelper(this);
        this.navigationHelper.LoadState += this.NavigationHelper_LoadState;
        this.navigationHelper.SaveState += this.NavigationHelper_SaveState;
    }
    public NavigationHelper NavigationHelper
    {
        get { return this.navigationHelper; }
    }
    public ObservableDictionary DefaultViewModel
    {
        get { return this.defaultViewModel; }
    }
    private void NavigationHelper_LoadState(object sender, LoadStateEventArgs e)
    {
    }
   private void NavigationHelper_SaveState(object sender, SaveStateEventArgs e)
    {
    }
    #region NavigationHelper registration
    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        this.navigationHelper.OnNavigatedTo(e);
    }
    protected override void OnNavigatedFrom(NavigationEventArgs e)
    {
        this.navigationHelper.OnNavigatedFrom(e);
    }
    #endregion
           private async void bt1_Click(object sender, RoutedEventArgs e)
    {
            home obj = new home();
            var result = await obj.GetToken4(sid);
          if (result.Substring(0, 2) == "No")
            {
                MessageDialog msgbox = new MessageDialog("No records found", "e-Book!");
                await msgbox.ShowAsync();
            }
            else
            {
                this.Frame.Navigate(typeof(firstpage), result);
            }
        }
    }
    private async Task<string> GetToken4(string sid)
    {
        string postData = "id=" + sid;
        var res = await post4("parameter", postData);
        return res;
    }
    private async Task<string> post4(string url, string postdata)
    {
        var request = WebRequest.Create(new Uri("myurl")) as HttpWebRequest;
        request.Method = "POST";
        request.ContentType = "application/json";
        byte[] data = Encoding.UTF8.GetBytes(postdata);
        //request.ContentLength = data.Length;
        using (var requestStream = await Task<Stream>.Factory.FromAsync(request.BeginGetRequestStream, request.EndGetRequestStream, request))
        {
            await requestStream.WriteAsync(data, 0, data.Length);
        }
        WebResponse responseObject = await Task<WebResponse>.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, request);
        var responseStream = responseObject.GetResponseStream();
        var sr = new StreamReader(responseStream);
        string received = await sr.ReadToEndAsync();
        return received;
    }
    private async void bt2_Click(object sender, RoutedEventArgs e)
    {
       home obj = new home();
            var result = await obj.GetToken4(sid);
          if (result.Substring(0, 2) == "No")
            {
                MessageDialog msgbox = new MessageDialog("No records found", "e-Book!");
                await msgbox.ShowAsync();
            }
            else
            {
                this.Frame.Navigate(typeof(secondpage), result);
            }
        }
    }
    private async Task<string> GetToken5(string sid)
    {
        string postData = "dep=" + sid;
        var res = await post5("parameter1", postData);
        return res;
    }
    private async Task<string> post5(string url, string postdata)
    {
        var request = WebRequest.Create(new Uri("myurl")) as HttpWebRequest;
        request.Method = "POST";
        request.ContentType = "application/json";
        byte[] data = Encoding.UTF8.GetBytes(postdata);
        //request.ContentLength = data.Length;
        using (var requestStream = await Task<Stream>.Factory.FromAsync(request.BeginGetRequestStream, request.EndGetRequestStream, request))
        {
            await requestStream.WriteAsync(data, 0, data.Length);
        }
        WebResponse responseObject = await Task<WebResponse>.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, request);
        var responseStream = responseObject.GetResponseStream();
        var sr = new StreamReader(responseStream);
        string received = await sr.ReadToEndAsync();
        return received;
    }

} }

A: Your page is completely reloaded when navigating back and therefor all controls will be in their default state (e.g. pivot is on the first item).
You can either save/restore the state in the OnNavigatedTo and OnNavigatedFrom methods, or activate page caching by setting your page's NavigationCacheMode to Enabled or Required in the constructor.


text:
Q: Order customers based on the purchases sum I have this  SQL
SELECT customers.first_name
FROM customers
INNER JOIN orders ON customer.id = orders.customer_id
GROUP BY first_name
HAVING SUM(orders.price) > 100;

But I want all customers to be listed in a table from the highest purchase price of their order to the lowest.

A: You can use next simple ORDER BY:
SELECT customers.first_name, SUM(orders.price) orders_price
FROM customers
INNER JOIN orders ON customers.id = orders.customer_id
GROUP BY first_name
ORDER BY orders_price DESC;

MySQL order by fiddfe
Also you can use LEFT JOIN and COALESCE function for select customers without orders:
SELECT
    customers.first_name,
    COALESCE(SUM(orders.price), 0) orders_price FROM customers
LEFT JOIN orders ON customers.id = orders.customer_id
GROUP BY first_name
ORDER BY orders_price DESC;

MySQL LEFT JOIN & COALESCE


text:
Q: Getting Error on the Terraform code while Azure App Registration Log Analytics API Permissions Allocation I'm Creating the App Registration, App Registration Secrets, API Permissions, and Role Assignment via Terraform. I'm Able to allocate the MicroSoft Graph API Permissions and able to Grant Permissions. For Log Analytic API Permission Grant, I'm Getting Error on the Terraform code.
data "azuread_client_config" "current" {}

data "azuread_application_published_app_ids" "well_known" {}

resource "azuread_service_principal" "msgraph" {
  application_id = data.azuread_application_published_app_ids.well_known.result.MicrosoftGraph
  use_existing   = true
  owners         = [data.azuread_client_config.current.object_id]

}

data "azuread_application_published_app_ids" "log" {}

resource "azuread_service_principal" "LogAnalyticsApi" {
  application_id = data.azuread_application_published_app_ids.log.result.LogAnalyticsAPI
  use_existing   = true
  owners         = [data.azuread_client_config.current.object_id]

}

# Retrieve domain information
data "azuread_domains" "domain" {
  only_initial = true
}

# Create an application
resource "azuread_application" "appreg" {
  display_name     = "Demo_App_Registration_Portal"
  owners           = [data.azuread_client_config.current.object_id]
  sign_in_audience = "AzureADMultipleOrgs"

  required_resource_access {
    resource_app_id = data.azuread_application_published_app_ids.well_known.result.MicrosoftGraph

    resource_access {
      id   = azuread_service_principal.msgraph.app_role_ids["User.Read.All"]
      type = "Role"
    }
    resource_access {
      id   = azuread_service_principal.msgraph.app_role_ids["Directory.Read.All"]
      type = "Role"
    }

    resource_access {
      id   = azuread_service_principal.msgraph.app_role_ids["Domain.Read.All"]
      type = "Role"
    }
    resource_access {
      id   = azuread_service_principal.msgraph.app_role_ids["Domain.ReadWrite.All"]
      type = "Role"
    }

    resource_access {
      id   = azuread_service_principal.msgraph.oauth2_permission_scope_ids["User.Read"]
      type = "Scope"
    }

    resource_access {
      id   = azuread_service_principal.msgraph.oauth2_permission_scope_ids["Domain.ReadWrite.All"]
      type = "Scope"
    }

    #####

    resource_access {
      id   = azuread_service_principal.msgraph.app_role_ids["UserAuthenticationMethod.Read.All"]
      type = "Role"
    }

    #####

  }

  #Log Analytic API Data Read Access

   required_resource_access {
    resource_app_id = data.azuread_application_published_app_ids.log.result.LogAnalyticsAPI

    resource_access {
      id   = azuread_service_principal.LogAnalyticsAPI.app_role_ids["Data.Read"]
      type = "Role"
    }
   }

}

#Creating Client Password for the Application
resource "azuread_application_password" "appregpassword" {
  display_name          = "Demo_App_Registration_Portal_Password"
  application_object_id = azuread_application.appreg.object_id

  depends_on = [
    azuread_application.appreg
  ]

}

output "azuread_application_password" {
  value = azuread_application_password.appregpassword.id

}

# Create a service principal
resource "azuread_service_principal" "appregsp" {
  application_id               = azuread_application.appreg.application_id
  app_role_assignment_required = true
  owners                       = [data.azuread_client_config.current.object_id]
}

resource "azuread_app_role_assignment" "example" {
  app_role_id         = azuread_service_principal.msgraph.app_role_ids["User.Read.All"]
  principal_object_id = azuread_service_principal.appregsp.object_id
  resource_object_id  = azuread_service_principal.msgraph.object_id

}

resource "azuread_app_role_assignment" "Directory" {
  app_role_id         = azuread_service_principal.msgraph.app_role_ids["Directory.Read.All"]
  principal_object_id = azuread_service_principal.appregsp.object_id
  resource_object_id  = azuread_service_principal.msgraph.object_id

}
resource "azuread_app_role_assignment" "Domain-Read" {
  app_role_id         = azuread_service_principal.msgraph.app_role_ids["Domain.Read.All"]
  principal_object_id = azuread_service_principal.appregsp.object_id
  resource_object_id  = azuread_service_principal.msgraph.object_id

}

resource "azuread_app_role_assignment" "Domain-Read-Write" {
  app_role_id         = azuread_service_principal.msgraph.app_role_ids["Domain.ReadWrite.All"]
  principal_object_id = azuread_service_principal.appregsp.object_id
  resource_object_id  = azuread_service_principal.msgraph.object_id

}

####
resource "azuread_app_role_assignment" "UserAuthenticationMethod-Read-All" {
  app_role_id         = azuread_service_principal.msgraph.app_role_ids["UserAuthenticationMethod.Read.All"]
  principal_object_id = azuread_service_principal.appregsp.object_id
  resource_object_id  = azuread_service_principal.msgraph.object_id

}
####

resource "azuread_service_principal_delegated_permission_grant" "example" {
  service_principal_object_id          = azuread_service_principal.appregsp.object_id
  resource_service_principal_object_id = azuread_service_principal.msgraph.object_id
  claim_values                         = ["User.Read", "Domain.ReadWrite.All"]
}

##Log Analytics API Role Assignment
resource "azuread_app_role_assignment" "LogAnalytics-Read" {
  app_role_id         = azuread_service_principal.LogAnalyticsAPI.app_role_ids["Data.Read"]
  principal_object_id = azuread_service_principal.appregsp.object_id
  resource_object_id  = azuread_service_principal.LogAnalyticsAPI.object_id

}

#Role Assigning to the App

data "azurerm_subscription" "primary" {
}

data "azurerm_client_config" "appregclient" {
}

resource "azurerm_role_assignment" "example" {
  scope                = data.azurerm_subscription.primary.id
  role_definition_name = "Reader"
  principal_id         = azuread_service_principal.appregsp.object_id
  depends_on = [
    azuread_application.appreg
  ]

}

I'm Creating the App Registration, App Registration Secrets, API Permissions, and Role Assignment via Terraform. I'm Able to allocate the MicroSoft Graph API Permissions and able to Grant Permissions. For Log Analytic API Permission Grant, I'm Getting Error on the Terraform code. I have upload how I want Log Analytic API Permission in the Image.

But I'm getting the Error Message as below:

A: I tried to reproduce the same in my environment:

As we see azuread_service_principal  block has been named LogAnalyticsApi and not LogAnalyticsAPI
resource "azuread_service_principal" "LogAnalyticsApi" {
  application_id = data.azuread_application_published_app_ids.log.result.LogAnalyticsAPI
  use_existing   = true
  owners         = [data.azuread_client_config.current.object_id]

}

When changed it LogAnalyticsApi when referred in remaining blocks
For example:
resource "azuread_app_role_assignment" "LogAnalytics-Read" {
  app_role_id         = azuread_service_principal.LogAnalyticsApi.app_role_ids["Data.Read"]
  principal_object_id = azuread_service_principal.appregsp.object_id
  resource_object_id  = azuread_service_principal.LogAnalyticsApi.object_id

}

Then the error is resolved.
But occurred to map element LogAnalyticsAPI to log result .

*

*Please change it to MicrosoftGraph  or AppIds present in this available ApplicationIds in place of   " application_id = data.azuread_application_published_app_ids.log.result.LogAnalyticsAPI "
 resource "azuread_service_principal" "LogAnalyticsApi" {
application_id = data.azuread_application_published_app_ids.log.result.MicrosoftGraph
use_existing   = false
owners         = [data.azuread_client_config.current.object_id]

}

*And also correct the same while giving Data.Read access to it in  required_resource_access block
ex:
required_resource_access {
      resource_app_id = data.azuread_application_published_app_ids.log.result.MicrosoftGraph

      resource_access {
        id   = azuread_service_principal.LogAnalyticsApi.app_role_ids["Data.Read"]
        type = "Role"
      }
     }

Reference: https://registry.terraform.io/providers/hashicorp/azuread/latest/docs/data-sources/application_published_app_ids

A: There is a Mapping issue, which I have identified and fixed the issue. Regarding the Log Analytic Grant permission,
My Log Analytic Resource Block:
data "azuread_application_published_app_ids" "log" {}

resource "azuread_service_principal" "LogAnalyticsApi" {
  application_id = data.azuread_application_published_app_ids.log.result.LogAnalyticsAPI
  use_existing   = true
  owners         = [data.azuread_client_config.current.object_id]

}

required_resource_access {
    resource_app_id = data.azuread_application_published_app_ids.log.result.LogAnalyticsAPI

    resource_access {
      id   = azuread_service_principal.LogAnalyticsAPI.app_role_ids["Data.Read"]
      type = "Role"
    }
   }

resource "azuread_app_role_assignment" "LogAnalytics-Read" {
  app_role_id         = azuread_service_principal.LogAnalyticsAPI.app_role_ids["Data.Read"]
  principal_object_id = azuread_service_principal.appregsp.object_id
  resource_object_id  = azuread_service_principal.LogAnalyticsAPI.object_id

}

I have modified the code as Below and Log Analytic Api Permission I'm able to Grant the Log Analytic API Permission. You can check by calling the below resource blocks in your code.
data "azuread_application_published_app_ids" "log" {}

resource "azuread_service_principal" "LogAnalyticsApi" {
 application_id = "ca7f3f0b-7d91-482c-8e09-c5d840d0eac5" #Data.Read
 use_existing   = true
 owners         = [data.azuread_client_config.current.object_id]

}

required_resource_access {
   resource_app_id = "ca7f3f0b-7d91-482c-8e09-c5d840d0eac5"

   resource_access {
     id   = azuread_service_principal.LogAnalyticsApi.app_role_ids["Data.Read"]
     type = "Role"
   }
 }

resource "azuread_app_role_assignment" "LogAnalytics-Read" {
 app_role_id         = azuread_service_principal.LogAnalyticsApi.app_role_ids["Data.Read"]
 principal_object_id = azuread_service_principal.appregsp.object_id
 resource_object_id  = azuread_service_principal.LogAnalyticsApi.object_id

}


text:
Q: Why do the Bajorans own DS9? There are a number of issues at play here:

*

*DS9 is in orbit around Bajor (before "Emissary")

*The Cardassians built DS9, using Cardassian design, in orbit around an occupied planet

*DS9 is, at least to some degree movable ("Emissary")

*DS9 is a significant military asset

It seems a little odd to abandon something so valuable.
I'm wondering if there's canon discussion of how Bajor came to possess DS9.    Is it only because it was considered essentially immovable?  Were there any negotiations involved?   Any governing laws mentioned?   Did Cardassia ever refute the claim by Bajor?

A: I don't know that DS9: "Emissary" ever explicitly states that the Cardassians gave Bajor the station, which suggests that Bajor claimed it at salvage.
This, by itself does not really answer the question of why the Cardassians left it, however. The closest we can come to a canonical answer to that is DS9: "Empok Nor", where we discover that the Cardassians seem to make a habit of simply abandoning their space habitats when they no longer have a use for them, sometimes going so far as to booby trap them against alien invasion, and thus safeguarding the possibility of eventual re-occupation.
Politically, Cardassia probably didn't feel that they could go that far with Terok Nor, given the scrutiny they were already under by the Federation, with whom they had only just recently concluded a treaty. Bajor's explicit request for Federation assistance would have magnified this aspect. Even if Cardassia had chosen to booby-trap it on their way out, clever people like O'Brien would have successfully dismantled the traps eventually.
More generally, constructing a space habitat is a fairly large undertaking. Once constructed, one does not simply scuttle it without good reason--particularly not in orbit of a populated planet, where the resulting pieces could be expected to de-orbit and make violent impacts upon the surface. Hauling away components for recycling would be problematic--Star Trek doesn't often seem to care much about mass, but volume would be a concern, certainly. Leaving the structure for someone else's use, or for their own later reuse (as in the case of "Empok Nor") costs nothing by comparison.

A: Terok Nor was an ore processing station built in orbit of Bajor during the Cardassian occupation of Bajor.

In 2346, the Cardassians used Bajoran slave labor to build an orbital space station known as Terok Nor. - https://memory-alpha.fandom.com/wiki/Occupation_of_Bajor

It has no warp capability and has basic thrusters to maintain orbit. As an ore processing center (which used ore coming from Bajor and its moons) it had no strategic  value to the Cardassians, and would have been a hassle to take with them.

As pointed out in a comment above, it seems to be standard procedure to booby-trap abandoned installations rather than destroy them. - Richard

A: Regarding your observation,

"It seems a little odd to abandon something so valuable",

O'Brien says,

"The Cardassians took every component of value."

(Source)


text:
Q: How to call vue methods inside jquery event? I'm using vue with webpack.
This is my code:
export default {
data() {
        return {
            start: true,
            logReg: false,
        }
},
methods: {
    checkLogged() {
        this.start = false;
        this.logReg = true;

    },
    closem(pathTo) {
        $('#mm').modal('hide')
        this.$router.push({ path: pathTo })

    }
},
mounted() {

    $('#mm').on('hide.bs.modal', function () {

       this.checkLogged();

    });
},
}

I'm trying to call "checkLogged" method inside the jquery event but it says the function is undefined.
How can i call the method?

A: This is because the function() {...} creates a new scope, therefore the this inside the callback does not actually refer to the VueJS component anymore, but to the window object instead.
You can use an arrow function, which does not create its own this binding, but passes in the lexical this (i.e. the this in an arrow function is the same this as the context it is called in):
$('#mm').on('hide.bs.modal', () => {
   this.checkLogged();
});


text:
Q: How to use cmd command in Gradle? I tried several ways found online, but have same exception below:
 Process 'command 'cmd'' finished with non-zero exit value 1

Following is my build script:
files.each { File file ->
        if (file.isFile()) {
            println " *** $file.name ***"
            exec {
                commandLine "cmd", "/c", "native2ascii", "$file.name", "$file.name"
            }
        }
    }
println " ==== Encoding done === "

A: Change the exec block as follows:
exec {
    commandLine "cmd", "/c native2ascii $file.name $file.name"
}


text:
Q: add occurences of the values of a list in another list I am trying to find the add together the values of a list that are matching a value from another list. My logic is the following:
for all the values in list1, count how many times each values of list1 are in list2, add them together and append them to a dictionary.
my current code is not giving me what I am expected and I am failing to understand why.
  list1 = [1,2,3,4,5]
  list2= [1,1,1,2,2,2,3,3,4,4,5]

  count = dict()
  for i in list1:
     if i in list2:

     count[i] = sum(i in list1 for i in list2)

  else:
     count[i] = 1

 print(count)

As a result I get this:
{1: 11, 2: 11, 3: 11, 4: 11, 5: 11}
and I am trying to find:
{1:3, 2:3, 3:2, 4:2, 5:1}
Thank you for any help!

A: I guess this is what you want
list1 = [1,2,3,4,5]
list2= [1,1,1,2,2,2,3,3,4,4,5]

count = {i:0 for i in list1}
for i in list2:
    if i in list1:
        count[i] += 1

print(count)


text:
Q: JavaFX 8 Animations I am trying to create a continuous animation, eventually the goal would be a bouncing ball that bounces off the edges of the screen, however, one step at a time.
I started with the sample code from Oracle that has an animation of circles that move for 40 seconds.
public void start(Stage primaryStage)
{
    Group root = new Group();
    Scene scene = new Scene(root, 800, 600);
    primaryStage.setScene(scene);

    Group circles = new Group();
    for (int i = 0; i < 1; i++)
    {
       MovingCircle circle = new MovingCircle(150, Color.web("white", 0.05));
       circle.setStrokeType(StrokeType.OUTSIDE);
       circle.setStroke(Color.web("black", 0.16));
       circle.setStrokeWidth(4);
       circles.getChildren().add(circle);
    }
    root.getChildren().add(circles);

    Timeline timeline = new Timeline();
    timeline.setCycleCount(Timeline.INDEFINITE);
    for (Node circle: circles.getChildren())
    {
            if(circle instanceof MovingCircle)
            {
                MovingCircle c = (MovingCircle)circle;

                timeline.getKeyFrames().addAll(
           /* new KeyFrame(Duration.ZERO, // set start position at 0
                new KeyValue(circle.translateXProperty(), random() * 800),
                new KeyValue(circle.translateYProperty(), random() * 600)
            ),*/
            new KeyFrame(new Duration(10), // set end position at 40s
                c.getXMovement(), c.getYMovement())

            );
                c.updateCenter();
            }

    }
    // play 40s of animation
    timeline.play();

    primaryStage.show();
}

I created a new MovingCircle that extends Circle to try and add other stuff to it later.  The two new class methods return exactly what was commented out from the default code given.
I changed the cycle to indefinite so that it would go forever.  All the circle does though is bounce between its original starting point and the translated point.  I have tried updating its center location in hopes that the next bounce would move it to a different location, however, that doesn't work.
I am at quite a loss as to what to try next to get this working more the way I was hoping.


text:
Q: jQuery - slideDown / slideUp two separate Div's from one button? Im very new to all coding including jquery. I though this would have been easy, but turns out I cant do it! Ive got a button that makes a div slide down, but I want another div to also slide down on top when the same button is hovered over.
Here the website Im working on- its when you hover over the timeline- a box darker box slide down, but I want a div containing text to also slide down at the same time...
http://beelinetest.site50.net/events_programme.html
Heres the jquery:- I want to put this two codes together as both dont seem to work- just the box slide down.
$(document).ready(function(){
    $('#ninethirtycircleTHURSDAY').hoverIntent(
  function () {
    $("#appearingthursdaybox").slideDown(500);
  },
  function () {
    $("#appearingthursdaybox").fadeOut(500);
  });

  return false;

    });

$(document).ready(function(){
    $('#ninethirtycircleTHURSDAY').hoverIntent(
  function () {
    $("#ninethirtyappearinginfoTHURSDAY").fadeIn(500);
  },
  function () {
    $("#ninethirtyappearinginfoTHURSDAY").fadeOut(500);
  });

  return false;

    });

Thanks in advance :)
HERES MY ENTIRE CODE:-
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>

<link rel="stylesheet" type="text/css" href="stylesheet.css"
 />

Only 9:45AM, 11:15AM AND 11:30AM are working at the moment. This is just to show the effect I am looking for. Donec sit amet turpis sit.

 INFO DISPLAYED HERE!

A: You just need to combine the different actions that you want on mousein and mouseout.  I also combined the two .fadeout() functions since you're doing the exact same thing to both targets.  I just selected for them both and applied the action.
$(document).ready(function(){

  $('#ninethirtycircleTHURSDAY').hoverIntent(
  function () {
    $("#appearingthursdaybox").slideDown(500);
    $("#ninethirtyappearinginfoTHURSDAY").fadeIn(500);
  },
  function () {
    $("#appearingthursdaybox, #ninethirtyappearinginfoTHURSDAY").fadeOut(500);
  });

  return false;

});


text:
Q: 2-step authentication to Gmail from Azure App service I have a Spring boot application run on Azure App Service, from which I want to send emails to users.
I can already do that with a gmail account I created myself, I just needed to turn on "allow less secure apps" feature.
However, I'm required to use another gmail account which belongs to a organization and thus is forced to use 2-step verification as per the organization policy.
Is it possible to complete the 2-step verification process from Azure's App service? What other options do I have?

A:
Is it possible to complete the 2-step verification process from Azure's App service?

In short, we couldn't do that from Azure's App service directly with you gmail account.
From goolge document we could know
that 2-Step Verification adds an extra layer of security to your users' managed Google accounts by requiring them to enter a verification code in addition to their username and password when signing in to their account.
In your case, according to your organization policy the google account is forced to enable 2-Step Verification. Based on my understanding, we can't do from the Azure's App service directly.

What other options do I have?

Based on my experince, you could registry a SendGrid account with your organization gmail account. Then you could use sendgrid to send the email to other users. Then other users could get the email from the organization gmail account but maybe there is no sent mails in the organization gmail account. More detail please refer to How to Send Email Using SendGrid with Azure.
Note: I don't test it on my side.


text:
Q: user-scalable=no but still able to scale entire page on web map application? I have a web application that is essentially a map (mapbox) with some d3.js points overlayed, filters, etc.
My issue is that when zooming in on the map using pinch (mobile), when I accidentally pinch over one of the points, or one of the map pop-ups, the entire page zooms (i.e. scaling). This is a fairly common occurrence. I only want user to be able to zoom the map, not the page itself.
I've implemented:
<meta name="viewport"
  content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

I also tried user-scalable=0
And still the behavior persists. I've also tried this:
document.addEventListener("touchstart", function(e){
  e.preventDefault();
},{passive: false});

document.getElementById('map')
 .addEventListener('touchstart', function(e){e.stopPropagation()}, false);

But this is cumbersome and doesn't exactly work the greatest because it involved limiting event-listeners one element at a time.  Shouldn't the user-scalable argument in the HTML be enough? I don't understand why this is happening.

A: Mobile browsers have no effect on user scalable because they over ride it to get people responsive experience on the mobiles.
Sites like google maps also zoom when we pinch in the site(expanding the ui elements as well as the map)
One way to override this response is to detect the pinch gesture and then re zoom  the page to the normal level  by a function such as:
function toggleZoomScreen() {document.body.style.zoom = "100%";}

A:
Shouldn't the user-scalable argument in the HTML be enough?

Depends on the browser/device. There are not many legitimately cases where zooming should be disallowed, so browsers will ignore it. Some browsers like Safari uses heuristics based on text size to decide if it should zoom or not... (where the solution is to set font-size to 17px or higher on input elements to prevent zoom)

*

*First strategy would be to call preventDefault() on all mouse
events, like mouseup, mousedown, et.al (not just the touch events)
until you are able to block the zoom.

*Second strategy is to take into account the zoom and scale the
images and point locations by the amount of zoom...
(Probably also want to take into account window.devicePixelRatio when scaling.)


text:
Q: Parse HTML contents of Webview - Android I'd like to detect when my webview loads a certain page, for example, an incorrect login page.  I've tried using onLoadResource and shouldOverrideUrlLoading, but I can't get either to work, and I'm thinking a better way would to parse the HTML whenever the webview starts loading a page, and if a certain string is found within the HTML, then do whatever.
Is there a method to do this?  I've tried using TagSoup, but I have no clue how to relate it into my webview.  Here's what my code looks like now:
String fullpost = "pass=" + passwordt + "&user=" + usernamet + "&uuid=" + UUID;

    String url = "mydomain.com";
        mWebview.postUrl(url, EncodingUtils.getBytes(fullpost, "BASE64"));
        mWebview.setWebViewClient(new WebViewClient() {

            public void onPageFinished(WebView mWebview, String url) {
                String webUrl = mWebview.getUrl();
                    if (webUrl.contains("/loginf")) {
                        MainActivity.this.mWebview.stopLoading();
                        MainActivity.this.setContentView(R.layout.preweb);

                    }
              }
       });

Basically, the postUrl is initiated from a user click on a button in a layout, and that's what starts the WebView, and then I call setContentView to the layout that contains the webview.
From there, if the login info is correct, the webpage goes to XXX, and if it's incorrect, it goes to YYY.  So, I want to detect immediately (and on every page load from there on out), if YYY is loaded, then //domagic.  Hope that makes sense.  Being the page redirect from url to XXX or YYY is automatic and not initiated by the user, shouldOverrideUrlLoading doesn't work, and I can't figure out how to use onLoadResource, so I'm just completely lost.
My current thought is loading everything in a separate thread and then using the WebView to display the content (that way I can parse the HTML), but I'm not sure how that'd work or even how to do it.
Anyone have any ideas or suggestions?

A: I think I've read a way to get a text string of a webview's content. Then, you could use jsoup to parse it. [neh, don't even need jsoup; just indexOf string check]
I'll suggest that you do consider handling the login with an HTTP client. It gives you flexibility, and seems the more proper way to go. I've been using the loopj library for HTTP get and post requests. It allows for simpler code. For me, anyway, a relative Android newbie. Here's some code from my project, to get you thinking. I've left out stuff like progress bar, and cookie management.
private void loginFool() {
    String urlString = "http://www.example.com/login/";

    // username & password
    RequestParams params = new RequestParams();
    params.put("username", username.getText().toString());
    params.put("password", password.getText().toString());

    // send the request
    loopjClient.post(urlString, params, new TextHttpResponseHandler() {

        @Override
        public void onStart() {
            // called before request is started
            //System.err.println("Starting...");
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, String responseString) {
            // called when response HTTP status is "200 OK"

            // see if 'success' was a failed login...
            int idx = responseString.indexOf("Please try again!");
            if(idx > -1) {
                makeMyToast("Sorry, login failed!");
            }
            // or actual success-ful login
            else {

               // manage cookies here

               // put extractData in separate thread
                final String responseStr = responseString;
                new Thread(new Runnable() {
                    public void run(){

                        extractData(responseStr);
                        selectData(defaultPrefs.getInt("xyz_display_section", 0));

                        // start the next activity
                        Intent intent = new Intent(MainActivity.this, PageViewActivity.class);
                        startActivity(intent);
                        finish();

                    }
                }).start();

            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            // called when response HTTP status is "4XX" (eg. 401, 403, 404)

            makeMyToast("Whoops, network error!");
        }

        @Override
        public void onFinish() {
            // done
        }

    });
}

You can see that, in the response handler's onSuccess callback, I can test for a string, to see if the login failed, and, in the onFailure callback, I give a network error message.
I'm not experienced enough to know what percent of web servers this type of post login works on.
The loopj client receives and manages cookies. If you will be accessing pages from the site via a webview you need to copy cookies from the loopj client, over to the webview. I cobbled code from a few online posts, to do that:
// get cookies from the generic http session, and copy them to the webview
CookieSyncManager.createInstance(getApplicationContext());
CookieManager.getInstance().removeAllCookie();
CookieManager cookieManager = CookieManager.getInstance();

List<Cookie> cookies = xyzCookieStore.getCookies();
for (Cookie eachCookie : cookies) {
    String cookieString = eachCookie.getName() + "=" + eachCookie.getValue();
    cookieManager.setCookie("http://www.example.com", cookieString);
    //System.err.println(">>>>> " + "cookie: " + cookieString);
}
CookieSyncManager.getInstance().sync();
// holy crap, it worked; I am automatically logged in, in the webview

EDIT: And, I should have included the class variable definitions and initializations:
private AsyncHttpClient loopjClient = new AsyncHttpClient();
private PersistentCookieStore xyzCookieStore;

xyzCookieStore = new PersistentCookieStore(this);
loopjClient.setCookieStore(Utility.xyzCookieStore);


text:
Q: Gravity Forms, insert entry via $.post I was wondering if anyone knew if there is a hook for gravity forms to $.post serialised form data so Gravity Forms can handle it and insert it into the database.
I was digging around the code and couldn't find how Gravity Forms itself inserts data as the URL action of the form seems just to be the permalink of the page.
I couldn't find a hook either where I could use the WordPress Ajax api to hook into a gravity forms insert entry sort of function.
Any ideas?

A: Seems to be what I'm looking for is this:
http://www.gravityhelp.com/documentation/page/API_Functions#add_entry


text:
Q: Optocoupler input protection I have to provide some isolated inputs that accept 12-24V. There should be some protection against reverse polarization, transient over-voltage and permanent over voltage (up to 40V) to some degree.
So far, I came up with the following circuit:

*

*R15+R21 limit the forward current to ~14mA@12V and 30mA@24V

*D1 TVS diode (breakdown ~@13V) protects against transients and voltages above ~26V

*D1 protects against reverse polarization

*R15 limits the current in case of reverse polarization or when D1 is clamping

This design seems suspiciously simple.
Do I miss something or should it work as desired?
EDIT:
R21 was meant to provide some additional transient over-voltage protection (ESD), because the TVS diode won't clamp instantly. This was also the reason for choosing a TVS diode instead of a normal one. Is this overkill?
As pointed out, If was somewhat high. I will consider something more like 580 Ohm for R15 and R21 to limit the current to 10-20mA.
LTV357T

A: Your resistors are a lot smaller then they need to be.
With two 390Ω resistors, you're getting ~15 mA @ 12VIn. The opto you have is characterized at both 5 mA vF and 20 mA vF. Unless you need fast response, running the LED in the opto at 5 mA shouldn't hurt anything.
It's probably worth making sure you're feeding the opto into a schmitt-trigger input, if it's going into any logic that can't handle slow transitions.
Also, there is no reason to bother with the two resistors. Just put the diode directly across the optocoupler. This will reduce the dissipation in the case of someone connecting the power backwards.

A: The circuit is good for protecting the diode.  I don't know of a better one.
You don't have to worry about protecting the diode from transients.  If a large current ( < 1A) flows through the diode for a microsecond, it won't hurt the diode.  You can get away with a regular zener diode instead of a TVS.
You might consider using a lower zener (TVS) voltage, say 5V.  That will cause less variation of diode current between 12V and 24V input voltage.
Optoisolators tend to age poorly, and the CTR will decline over time (or at least they used to, maybe that's been improved).  So it's a good idea to drive the diode with more than the minimum current to be sure that over time the input drive will continue to drive the output.  10mA is probably a good number for an opto LED spec'd at 5mA minimum.


text:
Q: Tracking App is closed after i tap it but still running on background i want it to stay in Main Activity I am making and App related to Tracking its working perfectly put the problem is it closes after I tap it though it is still working on background and providing data perfectly I want it to stay in Main Activity because I want add more features in app I am a little new coding sorry if my problem turns out to be simple and thank you in advance for help
Someone Asked if app crashes no it doesn't crash it works like it supposes to it just runs on background
As You can see there is no app shown here
That's how I want it to work so even if someone closes app tracking will still be active unless someone tabs app icon on notification bar pic of that below
Now if you tap on this then app stops tracking
Main Activity
    public class MainActivity extends AppCompatActivity {

    private static final int PERMISSIONS_REQUEST = 100;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
        if (!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            finish();
        }

        int permission = ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION);

        if (permission == PackageManager.PERMISSION_GRANTED) {
            startTrackerService();
        } else {

            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    PERMISSIONS_REQUEST);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[]
            grantResults) {

        if (requestCode == PERMISSIONS_REQUEST && grantResults.length == 1
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

            startTrackerService();
        } else {

            Toast.makeText(this, "Please enable location services to allow GPS tracking", Toast.LENGTH_SHORT).show();
        }
    }

    private void startTrackerService() {
        startService(new Intent(this, TrackingService.class));

        Toast.makeText(this, "GPS tracking enabled", Toast.LENGTH_SHORT).show();
    }

}

Tracking Service
    public class TrackingService extends Service {

    private static final String TAG = TrackingService.class.getSimpleName();
    public TrackingService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }
    @Override
    public void onCreate() {
        super.onCreate();
        buildNotification();
        loginToFirebase();
    }

    private void buildNotification() {
        String stop = "stop";
        registerReceiver(stopReceiver, new IntentFilter(stop));
        PendingIntent broadcastIntent = PendingIntent.getBroadcast(
                this, 0, new Intent(stop), PendingIntent.FLAG_UPDATE_CURRENT);

        Notification.Builder builder = new Notification.Builder(this)
                .setContentTitle(getString(R.string.app_name))
                .setContentText(getString(R.string.tracking_enabled_notif))

                .setOngoing(true)
                .setContentIntent(broadcastIntent)
                .setSmallIcon(R.drawable.tracking_enabled);
        startForeground(1, builder.build());
    }

    protected BroadcastReceiver stopReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            unregisterReceiver(stopReceiver);

            stopSelf();
        }
    };

    private void loginToFirebase() {

        String email = getString(R.string.test_email);
        String password = getString(R.string.test_password);

        FirebaseAuth.getInstance().signInWithEmailAndPassword(
                email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(Task<AuthResult> task) {

                if (task.isSuccessful()) {

                    requestLocationUpdates();
                } else {

                    Log.d(TAG, "Firebase authentication failed");
                }
            }
        });
    }

    private void requestLocationUpdates() {
        LocationRequest request = new LocationRequest();

        request.setInterval(10000);

        request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        FusedLocationProviderClient client = LocationServices.getFusedLocationProviderClient(this);
        final String path = getString(R.string.firebase_path);
        int permission = ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION);

        if (permission == PackageManager.PERMISSION_GRANTED) {

            client.requestLocationUpdates(request, new LocationCallback() {
                @Override
                public void onLocationResult(LocationResult locationResult) {

                    DatabaseReference ref = FirebaseDatabase.getInstance().getReference(path);
                    Location location = locationResult.getLastLocation();
                    if (location != null) {

                        ref.setValue(location);
                    }
                }
            }, null);
        }
    }
}

Information for Quick Test of App
In Firebase Project on Authentication tab.
Select "Set up sign-in method."
Choose "Email/password" and then push the slider into the "On" position. Click "Save."
Select the "Users" tab and then click "Add User."
Enter the email and password for the test user; I'm opting for test@test.com and testpassword.
Click "Add User."

**Android Studio what I did for Notifications icons **
Control-click your project's "res/drawable" folder and then select New > Image Asset.
Open the "Icon Type" dropdown and then select "Notification Icons."
Click the little button that appears alongside the "Clip Art" label.
Choose the icon you want to use; I'm opting for "My Location." Click "OK."
Name this icon "tracking_enabled," and then click "Next."
Check the information on the subsequent screen, and then click "Finish."

**Dependencies**

dependencies {
   implementation 'com.google.firebase:firebase-auth:11.8.0'
   implementation 'com.google.android.gms:play-services-location:11.8.0'
   implementation 'com.google.firebase:firebase-database:11.8.0'
}

Manifest
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
   <uses-permission android:name="android.permission.INTERNET"/>

String
    <string name="tracking_enabled_notif">Tracking is currently enabled. Tap to cancel.</string>
<string name="test_email">test@test.com</string>
<string name="test_password">testpassword</string>
<string name="firebase_path">location</string>

Ok I think I made Title summary and Provided Minimal Testing code if I still missed something Sorry for that I hope you guys can help me I will be really grateful thank you in advance xD

A:  LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
    if (!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        finish();
    }

In this part of code you are checking status of given provider which is in your case GPS Provider and if it returns false than finish(); method is called and your MainActivity finishes. But since you are starting services just below app runs service as well that is why your are getting info on Firebase even app is closed. Not sure why you are calling finish(); but I think that is the problem.
Also check changes and limitations which are introduced in Android Oreo and one particularly will impact your app:
https://developer.android.com/about/versions/oreo/android-8.0-changes


text:
Q: Session and Thread in ASP.NET I have a ASP.NET website where a thread is responible for doing some code retrived from a database queue.
Is it possible to get access to the Session or pass that as a parameter ?
My current code looks a follows:
MediaJob nextJob = GetNextJobFromDB();

CreateMedia media = new CreateMedia();

Thread t = new Thread(new parameterizedThreadStart(media.DOSTUFF);

t.Start(nextJob);

The HttpContext.Current.Session is null when running in a thread, so cant do that

A: edited:
 HttpContext ctx = HttpContext.Current;
 Thread t = new Thread(new ThreadStart(() =>
                {
                    HttpContext.Current = ctx;
                    worker.DoWork();
                }));
 t.Start();
 // [... do other job ...]
 t.Join();

A: If your job gets done outside the asp.net thread, then its probably not safe to assume that session would be available. Only deterministic way would be to pass this data explicitly to the thread. You can do this by assigning data in a named data slot

A: You can't access the session from within a thread, but you could share your data using: HttpRuntime.Cache
There are a few things to keep in mind though: unlike session, cache do expire. Also the cache is shared between all web users.


text:
Q: apply CSS to set position for icon inside button

      {{cart.length || 0}}

Now, I want ion-android-cart to be placed near the bottom of the button and anchor link to be at the right top edge of the icon . How do I apply this CSS here?
By default, these appear at the top left corners one after the other.

A: Use this code-snippet:
.button {
    position: relative;
}

.button i {
    position: absolute;
    top: 50%;
    right: 50%;
    transform: translate(-50%, -50%);
    -webkit-transform: translate(-50%, -50%);
    -moz-transform: translate(-50%, -50%);
    -o-transform: translate(-50%, -50%);
}

The icon will always stay in the absolute middle of the button.


text:
Q: Meaning of _(' ') in php and what inside it? I was reading and learning a code and I found this code,  infoBookingsTitle shows the title of the page, which is "Reservation options", I tried to found this file to edit the "Reservation options" word with something else but I didn't know where should I look, like what is that a PHP file, class or what?
          <div>

          <h2>   <?php __('infoBookingsTitle') ?>  </h2>

          </div>

Thanks.

A: It's not built into PHP, but like @SLaks said, it's usually for translation. When a different language file is used, it will look through that file for the translation of infoBookingsTitle and show that instead. Usually the __() function will return the string, and the _e() function will echo it.
<?php
echo __('Hello');
_e(' World');

// Result: "Hello World" will be displayed, unless a translation file is available


text:
Q: How to process map data from OpenStreetMap with Java? I'm developing an Java application which, given a list of street names, must get a route and information about each street name, as the city or cities where each street is located. This is a preprocessing, made in a desktop, for an Android application.
For that I must to process data from some map source like OSM. I need to easily access data from streets and some other points programmatically to select my desired data.
I need to do it with Java. Is there some Java library for this?

A: The OSM wiki has a large list of routing software and libraries. Some of them use Java, for example GraphHopper. Also don't forget to take a look at the various online and offline routers to get some inspiration.


text:
Q: What scm(git) workflow works well when developing multiple services? (SOA) We are about to start splitting our web application into multiple services, each being their own repository. We use git as our scm and I am wondering if anyone has any recommendations for a workflow for our scm (in this case git).
Right now we use a similar workflow to what is shown here: http://nvie.com/posts/a-successful-git-branching-model/.
I would like to move to a simpler model, such as how Github works: http://scottchacon.com/2011/08/31/github-flow.html. Is this feasible for developing SOA?
Curious as to if anyone has an opinion on this. Thanks.

A: Github flow relates feature branches to a single product, but there is no reason it couldn't be implemented . Your workflow options depend on how you deploy your application. Consider "MyApp", which has three component services:
MyApp
|- ServiceA
|- ServiceB
|- ServiceC

If you can deploy ServiceA independently of ServiceB and ServiceC, and more importantly deploy all of those independently of code contained by MyApp but which exists in none of the Service* repositories, then just apply Github flow, your preferred workflow, to each repository and team.
If the services are heavily intertwined, and deploying ServiceA necessarily requires a deploy of ServiceB or more importantly, MyApp represents a significant chunk of scaffolding or routing code that has to advance every time one of the Services* repos do, then you might want something like submodules or subtree. In that model, you'd have one Github flow, and an additional step between #4 and #5, namely collecting submodule (or subtree) updates to the services before deployment. I would avoid repository nesting without subtrees or submodules, unless you (and your team) know git extremely well.
All of that written, I'd suggest you take a deep look at your motivations for splitting the application at all. There are advantages to it and successful workflows on it, but they come at a cost: It's more difficult to get a "whole picture" of your history; in certain circumstances it can be harder to debug with tools like git bisect; each new developer has to learn your git infrastructure before he or she can be comfortable working your codebase. These aren't reasons to abandon your plan, just food for thought.

A: You would want each of your services' repos to have submodule that points to your messages or contracts repo. This repo would enforce an additive only model. This means that you once a message or contract has been published it cannot be erased. You can simply just add a new version of the massage and stop using the old one. This allows you to have incremental roll-outs.


text:
Q: How can I manage to install packages within python-dev on windows systems just like that on Linux? Actually, we can simply install python-dev on linux just use the following command:
sudo apt-get install python-dev
since python is integrated with Linux. But no such luck on windows. For input "pip install python-dev", there is no corresponding package on pypi.python.org.
What packages should I install to match those when installed by "apt-get install python-dev" command under Linux on Windows?

A: python-dev installs the headers and libraries for linux, allowing you to write / compile extensions.
In windows, the standard installer provides this by default.  The header files are in the $installroot\include directory.  The link libraries are found in $installroot\libs.
For example I've installed python 2.7 into c:\python27.  This means my include files are located here: c:\python27\include.  And the link libraries are in c:\python27\libs