text:
Q: Allow direct access to files/folders within Wordpress to replace wp-admin Here is the scenario:
I would like to design a brand new wordpress admin for my clients (using WordPress autoload as the core to interact with WordPress). I have tried slightly modifying the css or even using javascript to manipulate DOMs, but it just seems very inefficent while I can just re-code a new page instead of manipulating existing page.
With that in mind, I created a new folder, say, custom_dashboard, and try to redirect the clients there whenever they visit /wp-admin. However, it always shows 404 NOT FOUND when I open mydomain.com/custom_dashboard/index.php or anything that is not /wp-admin.
My questions are:

*

*What are some recommended approaches this problem? Is manipulating CSS & javascript via wp_enqueue_script and wp_enqueue_style the only possible way to recreate the new dashboard?

*How do I allow direct access to a single folder/file within the WordPress installation?

A: Since you asked for recommended approaches...
Why code your own custom dashboard? What is WordPress not doing that yours would?
WordPress is 15 years old with contributions from hundreds of developers. Are you sure that your dashboard is going to be better, and worth your time (or your clients' time) to code?
I don't mean that to be rude at all. Maybe you have a valid reason that you need a custom dashboard. But it would take a lot to convince me it's a better route than just extending or modifying the WordPress one. And the first part of that convincing would be telling me what you hope to gain. What is unique about your situation?
In answer to your second question, that doesn't sound like a WordPress issue, but rather a server or file issue. Here's why:
The way WordPress works on the server is that everything is rerouted to index.php. This bootstraps the WordPress process, including the handling of rewrite rules for all other paths. The way that the requests are rerouted to WordPress is important here:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

This is the standard Apache .htaccess WordPress redirect block. In English, line by line, it would read:

*

*If the server can handle redirects:

*Get ready to redirect

*We'll be talking about the / directory

*If the request is for index.php, great! Do nothing, we're done.

*If the request is NOT for a real, existing file...

*and if the request is NOT for a real, existing directory...

*...then redirect to index.php

*End of code that only runs if the server can handle redirects

So the important part for your case is that, in a nutshell, requests only get redirected to WordPress if they aren't actually real files or directories. Since you said they are real files and directories, something seems to be misconfigured on your server.
Please make sure that the files are present, that their permissions are correct (For instance: directories set to 755, files set to 644), and that the path you are attempting to access them at is correct. For real files at mydomain.com/custom_dashboard/index.php, that folder would be in the same directory as wp-content and wp-admin, but not inside either of them.


text:
Q: insert data in database and show same data after insert without refresh page(call data after insert of database) i want insert some of data in database by ajax call ($.ajax()) and generation tracking code by a code php  and with others data it insert in database  . how after (upon) insert in database, displaying to user it tracking code ? (Without Refresh Page)
With respect
my code:
$('.insert').live('click',function(e){
        e.preventDefault();
        var dataObj = $(this).closest('form').serialize();
        //alert(dataObj)
        $.ajax({
            type: "POST",
            url: 'insert_customers',
            data: dataObj,
            cache: false,
            success: function() {
                //alert(idname)
                    $('.result').hide().fadeIn('slow').html("
Your information was successfully. your tracking code is : '+$tracking'
");
            },
                "error": function (x, y, z) {
                    // callback to run if an error occurs
                    alert("An error has occured:\n" + x + "\n" + y + "\n" + z);
                }
        });
        return false;
    })

A: You can send back data to the client (either html or objects) and use the data in the success function. To do so you use whatever print method that your server language uses (ie. if php use echo, perl print, etc) To print a content header and the information (like you would on a normal request for a web page. I would sugesst sending a content header of Content-type:application/json and format your data back as {"tracking":trackingVar} Then in your success function define it as:
success: function(data) {
    //alert(idname)
    $('.result').hide().fadeIn('slow').html("
Your information was successfully. your tracking code is : " + data.tracking + "
");
},

redpajama_set_name: RedPajamaStackExchange


text:
Q: Are sojourn times independent in non homogeneous poisson process? We know that in homogeneous Poisson process, sojourn times are independent. But are they still independent if  $\lambda (t)$ varies?
If so, what is the proof?
Thanks
the problem I have now is that after calculation, I am expecting f(s1,s2)=λ(s1)e^(-λ(s1))λ(s2)e^(-λ(s2)) if they are independent. But We I get is not this, the answer contains λ(s1+s2)! Please can any one help!


text:
Q: WebGL create Texture I successfully created a WebGL texture from an image and drew it into a canvas element.
function initTexture(src) {
  texture = gl.createTexture();
  texture.image = new Image();
  texture.image.onload = function() {
    handleLoadedTexture(texture)
  }

  texture.image.src = src;
}

I also tried to create a texture from one of these datatypes, but without success.

*

*[object ImageData]

*[object CanvasPixelArray]

*[object CanvasRenderingContext2D]

Is it possible to create a texture just with an image's pixel array?
Or in other words: Is it possible to create a JS Image object out of a pixel array?
Edit:
The pixel array looks like this [r,g,b,a,r,g,b,a,r,g,b,a,...] and each value is in a range of {0..255}.
I want to create a texture with the pixels in the given array.

A: It's absolutely possible to create a texture with a pixel array! I use the following in my code all the time to create a single pixel, solid color texture.
function createSolidTexture(gl, r, g, b, a) {
    var data = new Uint8Array([r, g, b, a]);
    var texture = gl.createTexture();
    gl.bindTexture(gl.TEXTURE_2D, texture);
    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
    return texture;
}

EDIT: To extrapolate this a little further, most of what you need to know is in the gl.texImage2d call. In order to create a texture from raw RGB(A) data you need an array of unsigned byte values, you need to specify to WebGL what the data represents (RGB or RGBA), and you need to know the dimensions of the texture. A more generalized function would look like this:
function textureFromPixelArray(gl, dataArray, type, width, height) {
    var dataTypedArray = new Uint8Array(dataArray); // Don't need to do this if the data is already in a typed array
    var texture = gl.createTexture();
    gl.bindTexture(gl.TEXTURE_2D, texture);
    gl.texImage2D(gl.TEXTURE_2D, 0, type, width, height, 0, type, gl.UNSIGNED_BYTE, dataTypedArray);
    // Other texture setup here, like filter modes and mipmap generation
    return texture;
}

// RGB Texture:
// For a 16x16 texture the array must have at least 768 values in it (16x16x3)
var rgbTex = textureFromPixelArray(gl, [r,g,b,r,g,b...], gl.RGB, 16, 16);

// RGBA Texture:
// For a 16x16 texture the array must have at least 1024 values in it (16x16x4)
var rgbaTex = textureFromPixelArray(gl, [r,g,b,a,r,g,b,a...], gl.RGBA, 16, 16);


text:
Q: Having Issue on Field Calculator With Python in ArcMap I have tried all of below snippets to use Python Parser in Field Calculator and update the values of a field called type based on a filed called MamerMN but in all of them I am getting Syntax error in Geoprocessing result window!
if !MamerMN! <= 0.151560:
    return 1

and
if (!MamerMN! <= 0.151560):
    return 1

and
if (MamerMN <= 0.151560):
    return 1

and
def(MamerMN)
if MamerMN <= 0.151560:
    return 1

and
def(MamerMN)
if (MamerMN <= 0.151560):
    return 1

Can you please let me know what I am doing wrong?

A: You are writing your functions wrong. In the Field Calculator, make sure you check 'Show Codeblock' so the Pre-Logic Script Code box appears. Inside the Pre-Logic box, write your function-
def calcValue(mamerMN):
    if mamerMN <= 0.151560:
        return 1

and then in the box under, where it says the field_name =
you should write the name of the function and the field value you are passing to it surrounded by exclamations. So if your function above is named calcValue you would write
calcValue(!mamerMN!)

A: Without seeing a graphic of what your Field Calculator looks like, I suspect @csterling is probably right. However, an alternative is to just Select by Attribute where "mamerMN" <= 0.151560, then Field Calculate your selected features to 1 the regular way without necessitating a codeblock.


text:
Q: Return value of filled JComboBox and using the values to fill JTextField I'm coding a JFrame which opens a JOptionPane through JMenubar. The JOptionPane does have a combobox with a lot of different string values. After the JComboBox there is a JTextfield.
I want the text I select in the JComboBox to be inserted into the next JTextField and to be updated everytime I select a new string value in the JComboBox.
Please help!
class DateiAdapter implements ActionListener {

public void actionPerformed(ActionEvent event) {

    JMenuItem change = (JMenuItem) event.getSource();

    JComboBox alleQuest = new JComboBox(ah.getLine(1)); //this ComboBox gets a lot of different values from a different class

    // Actionlistener
    ActionListener cbActionListener = new ActionListener() {

        public void actionPerformed(ActionEvent e) {

            String s = (String) allQuest.getSelectedItem(); //gets the selected string of the JComboBox
            System.out.println("\n" + s); // I want to use String s outside of here, too
            }
        };

        allQuest.addActionListener(cbActionListener);

        JTextField questions = new JTextField(); //THIS is the TextField I want to insert the different values of the ComboBox above
        JTextField a2 = new JTextField();
        JTextField b2 = new JTextField();
        JTextField c2 = new JTextField();
        JTextField answ2 = new JTextField();

        if (change == itemChange) {

            final JComponent[] input = new JComponent[] {
                    new JLabel("You change your question here:"),
                    allQuest,
                    quest2,
                    a2,
                    b2,
                    c2,
                    answ2,  };

            JOptionPane.showMessageDialog(null, input, "Change Question", JOptionPane.PLAIN_MESSAGE);

A: you can use
questions.setText(alleQuest.getSelectedItem().toString());

inside the ActionListener.
But questions textfileld should be defined above the actionPerformed method

A: You have 2 options regarding
public void actionPerformed(ActionEvent e) {

    String s = (String) allQuest.getSelectedItem(); //gets the selected string of the JComboBox
    System.out.println("\n" + s); // I want to use String s outside of here, too
    }
};

*

*Either store s as a field of enclosing class (DateiAdapter class in your case)

*Update every GUI component you want with given s value from the actionPerformed method. To be honest this is the exact place to do this as actionPerformed is invoked by the EDT, where all GUI changes should happen.

*In case you want s to use outside DateiAdapter class, follow point 1, then optionally 2, and add public getter for that field.

In your case putting
questions.setText(alleQuest.getSelectedItem().toString()); in the actionPerformed would be the most straightforward choice.

A: So, this basically, seems to, come down a question of context, the questions field needs to be defined in a context in which the cbActionListener can reference it.
One of the simplest was would be to make questions an instance field of the class, for example...
class DateiAdapter implements ActionListener {

    private JTextField questions = new JTextField(); //THIS is the TextField I want to insert the different values of the ComboBox above

    public void actionPerformed(ActionEvent event) {

        JMenuItem change = (JMenuItem) event.getSource();

        JComboBox alleQuest = new JComboBox(ah.getLine(1)); //this ComboBox gets a lot of different values from a different class

        // Actionlistener
        ActionListener cbActionListener = new ActionListener() {

            public void actionPerformed(ActionEvent e) {

                String s = (String) allQuest.getSelectedItem(); //gets the selected string of the JComboBox
                questions.setText(s);
            }
        };

        allQuest.addActionListener(cbActionListener);

        JTextField a2 = new JTextField();
        JTextField b2 = new JTextField();
        JTextField c2 = new JTextField();
        JTextField answ2 = new JTextField();

        if (change == itemChange) {

            final JComponent[] input = new JComponent[]{
                new JLabel("You change your question here:"),
                allQuest,
                quest2,
                a2,
                b2,
                c2,
                answ2,};

            JOptionPane.showMessageDialog(null, input, "Change Question", JOptionPane.PLAIN_MESSAGE);
        }
    }
}


text:
Q: compare ArrayList with contain object I have my object class :
public class Test {
private String name;
private int id;
private boolean aBoolean;

public Test(String name, int id, boolean aBoolean) {
    this.name = name;
    this.id = id;
    this.aBoolean = aBoolean;
}

and 2 arrayList of this object:
 ArrayList<Test> myFirstList = new ArrayList<>();
    ArrayList<Test> mySecondList = new ArrayList<>();

    myFirstList.add(new Test("a", 1, false));
    myFirstList.add(new Test("b", 2, false));
    myFirstList.add(new Test("c", 3, false));

    mySecondList.add(new Test("a", 1, false));
    mySecondList.add(new Test("b", 2, false));
    mySecondList.add(new Test("c", 3, false));

now I need to check that these array list contain objects which have same fields inside; is there any ways but to use fori loop and getting each parameter for compare?

A: Record
Apparently you want to compare objects of the same class for equality by examining the content of each and every member field.
You get that behavior automatically by using the records feature. This feature is new in Java 16, with early access builds available now. In a record you simply declare the member fields. The compiler implicitly creates the constructor, getters, equals & hashCode, and toString.
So no need for you to override equals wih your own implementation as seen in the other Answers.
Use a record where the primary purpose of a class is to immutably and transparently carry data. In contrast, if your class has a focus on behavior with encapsulated data, or uses other OOP features such as inheritance, then your should use a regular class, not records.
So your code:
public class Test {
private String name;
private int id;
private boolean aBoolean;

public Test(String name, int id, boolean aBoolean) {
    this.name = name;
    this.id = id;
    this.aBoolean = aBoolean;
}

… becomes:
public record Test ( String name , int id , boolean aBoolean ) {}

Using that record:
Test x = new Test ( "Alice" , 42 , true ) ;
Test y = new Test ( "Alice" , 42 , false ) ;
boolean same = x.equals( y ) ;  // false because of third field.

Comparing lists
Use List#equals to see if two lists contain equal elements in the same order.
List x = List.of(
    new Test ( "Alice" , 1 , true ) ,
    new Test ( "Bob" , 2 , true ) ,
    new Test ( "Carol" , 3 , true )
);

List y = List.of(
    new Test ( "Alice" , 1 , true ) ,
    new Test ( "Bob" , 2 , true ) ,
    new Test ( "Carol" , 3 , true )
);
boolean same = x.equals( y ) ;   // True.

A: If you override equals() in our class you should be able to sort both lists with  myFirstList.sort()  and then just use
myFirstList.equals(mySecondList)

A: This is not related to ArrayList, it is related to your Test Class. As said by @VGR, In order to know if the two objects of the Test Class have the same fields, you have to override the equals method inside your Test class like this:
public class Test {

    // your constructors and methods

    @Override
    public boolean equals(Object o) {

        if (o == this) {
            return true;
        }

        if (!(o instanceof Test)) {
            return false;
        }

        Test t = (Test) o;

        // Compare the data members and return accordingly
        return this.name.equals(t.name)
                && this.id == t.id;
                && this.aBoolean == t.aBoolean;
    }
}

Now to check if two objects in ArrayList are equal, Simply do this:
    boolean result = myFirstList.get(indexOfObject1).equals(indexOfObject2);
    System.out.println("Result : "+result);

And obviously, to search for equal objects in two ArrayLists, you have to loop through every single object in the first list, then compare that object with all objects in the second list, or implement your own algorithm. That's where data structure and algorithms are used!


text:
Q: Intuition behind why density operator contains complete information about the system? I have read this and I want to know why is that the case, and why not simply write two (or more) particles with their 'pure' states, because the latter is much more straightforward?

A: There are two different kinds of uncertainty in quantum mechanics.
The first is the normal, intrinsic, quantum mechanical uncertainty. Knowing the state of the system completely, still means you only can make probabilistic statements about the outcomes of some experiments. For example, if we have two particles in a 2-state system (if it helps, say the two states are "spin up" and "spin down" for concreteness), then the system may be in an entangled state like
\begin{equation}
| \Psi \rangle = \frac{1}{\sqrt{2}} \left(|0 \rangle | 1 \rangle + | 1 \rangle | 0 \rangle \right)
\end{equation}
in which case it is not possible to say with certainty if a measurement of particle $1$ will yield the result $0$ or $1$.
The second is an uncertainty in what the state of the system is. For example, perhaps we think there's a 50% chance that the system is in the state $|\Psi\rangle$ given above, and a 50% chance that the system is in a different state $|\Phi\rangle$, given by
\begin{equation}
| \Phi \rangle = \frac{1}{\sqrt{2}} \left(|0 \rangle | 1 \rangle - | 1 \rangle | 0 \rangle \right)
\end{equation}
This kind of uncertainty cannot be represented nicely using only state vectors in Hilbert space. One option is to say in words "there's a 50% chance that the state is $|\Psi\rangle$ and a 50% chance that the state is $|\Phi\rangle$, but this becomes cumbersome. And, in situations like thermodynamics, you often need to specify the probability for an infinite number of possible states of the system.
The density matrix can encode both kinds of uncertainty. In the first case, where we know the state is $|\Psi\rangle$, the density matrix is
\begin{equation}
\rho = |\Psi \rangle \langle \Psi |
\end{equation}
In the second case, with a 50% chance that the state is $|\Psi\rangle$ or $|\Phi\rangle$, the density matrix is
\begin{equation}
\rho = \frac{1}{2} \left( |\Psi \rangle \langle \Psi | + |\Phi \rangle \langle \Phi |  \right)
\end{equation}
Because the density matrix can handle both kinds of uncertainty, the density matrix generalizes the normal quantum state vector and lets us handle a wider variety of cases.
This flexibility also lets us formulate statements about entanglement in a precise way. For example, in the first case where the state is $|\Psi\rangle$, we can consider the state of knowledge we would have if we only have access to the first particle, by tracing over the second particle. This leads to a density matrix
\begin{eqnarray}
\rho' &=& {\rm Tr}_2 \rho \\
&=& \frac{1}{2} \left(|0\rangle \langle 0| + | 1 \rangle \langle 1 | \right)
\end{eqnarray}
where $\rm Tr_2$ denotes a trace over the Hilbert space of the second particle. This tells us that if we don't know anything about particle 2, then we only know that particle 1 has a 50% chance of being in state $|0\rangle$ or state $|1\rangle$. Of course, this uncertainty is different from particle 1 being in a superposition of states $|0\rangle$ and $|1\rangle$.


text:
Q: Android Studio 3.1.3 Missing constraint in constrain layout My Question is why i'm not seeing the code results on display and how i can fix this problem thanks in advance
Greetings

A: Replace in your xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="148dp"
        android:text="Hello World!"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="192dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:text="OK!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />
</android.support.constraint.ConstraintLayout>

A: add implementation 'com.android.support.constraint:constraint-layout:1.0.2' in dependencies block in app build.gradle .
Maybe it works.


text:
Q: error: 'Class' was not declared in this scope I would like to ask, how can I define class inside another one.  In the code below. I try to define it in the way   #define "CCompField.h" ,but it doesn't work. :(.
I think that it is very common programming problem, probably it was 100000 times solved on the internet, but I don't know how to find it. Thanks for help.
#ifndef CNEWGAME_H
#define CNEWGAME_H

class CNewGame{
    public:
               CNewGame();
              ~CNewGame();

        void  BeginnerGame();
        void  IntermediateGame();
        void  AdviceGame();
        void  HowToPlay();
        void  NetGame( int mode );

        int MoveInMenu();

    protected:
        void  Intro();
        void  Animation ();
        void  Menu(int);
         int  MoveInNetMenu();
        void  NetMenu(int);

        void  HeadOfGame();
template <class T> void BodyOfGame(CCompField & b, T & a);
        void  FooterOfGame();
};

#endif

It makes following errors.
In file included from src/CNewGame.cpp:12:0:
src/CNewGame.h:37:36: error: 'CCompField' was not declared in this scope
src/CNewGame.h:37:45: error: 'b' was not declared in this scope
src/CNewGame.h:37:50: error: expected primary-expression before '&' token
src/CNewGame.h:37:52: error: 'a' was not declared in this scope
src/CNewGame.h:37:53: error: variable or field 'BodyOfGame' declared void

A: Instead of #define "CCompField.h" you need to include it:
#include "CCompField.h"

You also have an extra pair of
#ifndef CNEWGAME_H
#define CNEWGAME_H

but only one closing #endif.  You don't need the second pair of #ifndef/#define

A:
I try to define it in the way #define "CCompField.h" ,but it doesn't work. :(

You need to figure out the header file where CCompField is defined and #include (not #define) it from CNewGame.h.


text:
Q: Sorting contents of a listbox I'm using the following code to add items to a listbox:
Dim i As Integer = 0
Dim temp As String

ListBox2.Items.Clear()
While i <= 9
    temp = Str(final_average(i)) + "        " + Str(i + 1) + "             " + Str(cals(i))
    ListBox2.Items.Add(temp)
    i = i + 1
End While

I want to sort this using the average or final_average(i), but the following code doesn't seem to work:
Dim arr(ListBox2.Items.Count - 1) As Object

ListBox2.Items.CopyTo(arr, 0)
Array.Sort(arr)
ListBox2.Items.Clear()
ListBox2.Items.AddRange(arr)

How do I sort the contents of the listbox?
(Note: This is not homework but part of a bigger project).

A: Here is the proper way to do it.
A. First create your list items class.
Public Class MyListItem
    Implements IComparable(Of MyListItem)

    Public FinalAverage As Integer
    Public Number As Integer
    Public Cals As Integer

    Public Sub New(ByVal finalAverage As Integer, ByVal number As Integer, ByVal cals As Integer)
        Me.FinalAverage = finalAverage
        Me.Number = number
        Me.Cals = cals
    End Sub

    Public Overrides Function ToString() As String
        '' the way you want it to be shown in the listbox.
        Return String.Format("{0}        {1}             {2}", FinalAverage, Number, Cals)
    End Function

    Public Function CompareTo(ByVal other As MyListItem) As Integer Implements System.IComparable(Of MyListItem).CompareTo
        '' the way list items are compared for sorting... Return 0 for equal, -1 for smaller, +1 for bigger
        If Me.FinalAverage < other.FinalAverage Then Return -1
        If Me.FinalAverage > other.FinalAverage Then Return 1
        Return 0
    End Function
End Class

B. Now use this class to add items to your listbox.
    Dim listItems As New List(Of MyListItem)
    For i As Integer = 0 To 9
        listItems.Add(New MyListItem(final_average(i), i + 1, cals(i)))
    Next
    listItems.Sort()
    ListBox2.DataSource = listItems

And that's it! :)

A: I have a rather simpler solution to your problem!
Method 1
1) Sort the items in Listbox1:
We will do this by setting the Sorted property of Listbox1 to True. It will keep your old list which was not sorted safely!
listBox1.Sorted = True

2) Send the items to Listbox2:
Copy all the items from listbox1 to listbox2 by saving it to an object collection. They will move in order, and hence, the second one is sorted from A-Z.
Dim objCollection As Object() = New Object(listBox1.Items.Count - 1)
listBox1.Items.CopyTo(objCollection, 0)
listBox2.Items.AddRange(objCollection)

3) Place items in Listbox1 in proper order:
We have both the listbox with sorted items. Now, all we need to do is to place items in the previous order. As I said, your placement of items will be stored safely, we will retrieve it back by setting the Sorted property of Listbox1 to False.
listBox1.Sorted = False

And, you will get a sorted listbox2!
Method 2
Instead of sorting and then copying and then unsorting listbox1, you can first copy all items to listbox2 and then sort listbox2. In this case, there will be no need of unsorting the first one again!
I hope it works perfectly!


text:
Q: How to use this.state.rent value instead of this.props.house.rent value in cache.readQuery or cache.writeQuery The old value comes back into the input field.
I had initialized this.props.house.rent (which is the old value coming back) with input field value this.state.rent (user entered value) but I cannot do it as it becomes antipattern syntax, you can see it in below comments of code.
cacheUpdate = (cache, { data: { updateHouse } }) => {
    const data = cache.readQuery({
      query: QUERY_CONFIRM_QUERY,
      variables: { id: this.props.confirmId },
    });
    const houses = data.queryConfirm.houses;
    const prevHouse = this.props.house;
    //prevHouse.rent = this.state.rent; // this.state.rent is user entered input value
    const updatedHouses = houses.map(house => {
      if (house.id === prevHouse.id) {
        const updatedHouseItem = _.pickBy(updateHouse, _.identity);
        return { ...prevHouse, ...updatedHouseItem };
      }
      return house;
    });
    data.queryConfirm.houses = updatedHouses;

    cache.writeQuery({
      query: QUERY_CONFIRM_QUERY,
      variables: {
        id: this.props.confirmId,
      },
      data,
    });
  };

I want the old value to be removed from readQuery or writeQuery of cache.

A: Hope this helps someone. Ooof..I think a lot, it was simple actually. I thought to make callback, but not possible as values are coming from database. Anyways, in conclusion simple look at the value of data.queryConfirm.houses in the console and assign the required array like, say I required was data.queryContact.houses[0].rent and initialize it to this.state.rent. That's all.


text:
Q: What to do here in rails app? i am new in rails. i started learning rails from a web source .http://guides.rubyonrails.org/getting_started.html
i have a problem in this tutorial in '5.7 Showing Post'. i don't know what to do here . i completed every previous tusk. so please someone help me.please go to the link and check 5.7 showing post,and see what they told to do.
in there(5.7 showing post) i confused in this "post GET    /posts/:id(.:format)      posts#show . "

A: You need to create a show action in your posts_controller.rb:
def show
  @post = Post.find(params[:id])
end

Also a show.html.erb file within the posts folder under the view sub directory of the Rails application. This means the application can redirect to the show action after a post has been created, utilising the ID parameter in your query string.


text:
Q: Dynamically create a SQL statment from passed values in PHP I am passing a number of values to a function and then want to create a SQL query to search for these values in a database.
The input for this is drop down boxes which means that the input could be ALL or * which I want to create as a wildcard.
The problem is that you cannot do:
$result = mysql_query("SELECT * FROM table WHERE something1='$something1' AND something2='*'") or die(mysql_error());

I have made a start but cannot figure out the logic loop to make it work. This is what I have so far:
public function search($something1, $something2, $something3, $something4, $something5) {

    //create query
    $query = "SELECT * FROM users";

    if ($something1== null and $something2== null and $something3== null and $something4== null and $something5== null) {
        //search all users
        break
    } else  {

        //append where
         $query = $query . " WHERE ";

                if ($something1!= null) {
                    $query = $query . "something1='$something1'"
                }
                if ($something2!= null) {
                    $query = $query . "something2='$something2'"
                }
                if ($something3!= null) {
                    $query = $query . "something3='$something3'"
                }
                if ($something4!= null) {
                    $query = $query . "something4='$something4'"
                }
                if ($something5!= null) {
                    $query = $query . "something5='$something5'"
                }

    $uuid = uniqid('', true);

    $result = mysql_query($query) or die(mysql_error());
}

The problem with this is that it only works in sequence. If someone enters for example something3 first then it wont add the AND in the correct place.
Any help greatly appreciated.

A: I would do something like this
criteria = null
if ($something1!= null) {
      if($criteria != null)
      {
          $criteria = $criteria . " AND something1='$something1'"
      }
      else
      {
           $criteria = $criteria . " something1='$something1'"
      }
}
   ... other criteria

$query = $query . $criteria

A: Here's an example of dynamically building a WHERE clause.  I'm also showing using PDO and query parameters.  You should stop using the deprecated mysql API and start using PDO.
public function search($something1, $something2, $something3, $something4, $something5)
{
    $terms = array();
    $values = array();

    if (isset($something1)) {
       $terms[] = "something1 = ?";
       $values[] = $something1;
    }

    if (isset($something2)) {
       $terms[] = "something2 = ?";
       $values[] = $something2;
    }

    if (isset($something3)) {
       $terms[] = "something3 = ?";
       $values[] = $something3;
    }

    if (isset($something4)) {
       $terms[] = "something4 = ?";
       $values[] = $something4;
    }

    if (isset($something5)) {
       $terms[] = "something5 = ?";
       $values[] = $something5;
    }

    $query = "SELECT * FROM users ";

    if ($terms) {
        $query .= " WHERE " . join(" AND ", $terms);
    }

    if (defined('DEBUG') && DEBUG==1) {
      print $query . "\n";
      print_r($values);
      exit();
    }

    $stmt = $pdo->prepare($query);
    if ($stmt === false) { die(print_r($pdo->errorInfo(), true)); }

    $status = $stmt->execute($values);
    if ($status === false) { die(print_r($stmt->errorInfo(), true)); }
}

I've tested the above and it works.  If I pass any non-null value for any of the five function arguments, it creates a WHERE clause for only the terms that are non-null.
Test with:
define('DEBUG', 1);
search('one', 'two', null, null, 'five');

Output of this test is:
SELECT * FROM users  WHERE something1 = ? AND something2 = ? AND something5 = ?
Array
(
    [0] => one
    [1] => two
    [2] => five
)

If you need this to be more dynamic, pass an array to the function instead of individual arguments.

A: try with array.
 function search($somethings){

     $query = "SELECT * FROM users";
     $filters = '';
     if(is_array($somethings)){

        $i = 0;
        foreach($somethings as $key => $value){
           $filters .= ($i > 0) ? " AND $key = '$value' " : " $key = '$value'";
           $i++;
        }
     }
     $uuid = uniqid('', true);
     $query .= $filters;
     $result = mysql_query($query) or die(mysql_error());
 }

 // demo
 $som = array(
      "something1" => "value1",
      "something2" => "value2"
 );

 search( $som );


text:
Q: Stack Overflow Searchbox increases in width automatically
Possible Duplicate:
Make the search box bigger

Is this a new feature added to searchbox in stackoverflow websites. When I click on the search box it automatically expands in length hiding my username and other details near it. I have never seen it before.


text:
Q: PHP superglobal variables I trying to have a PHP script calling several functions that should do some operations on couple of variables.
Like for example have one function fetch the matrix, then the second is doing one operation over it, then the third doing different operation on it.
It all worked well when it was in one file, but now that I've split it up it won't work. I get all undefined index and undefined variable error.
What do I have to do with variables so that they should keep their values throughout the script?

A: The easiest way (and bad way in larger PHP projects, as this can make things very messy very fast), is to either use $GLOBALS['myvar'] to set/get the variable value for $myvar in a global scope.  Or you can use:
<?php
global $myvar;
//use the $myvar below...

Use that anywhere, including inside a function, or in a new file, to use $myvar in a global scope.
On a side note, there are better ways to make something accessible "everywhere" depending on context.  It may be a little outside the scope of this global question, but just be aware there are other ways, for instance using the Singleton method (enforce single instance of a class used throughout the software, retrieved with a static class that returns the object, like MyClass::getInstance()).   For a simple 2/3 file script this probably doesn't matter as much (unless you need re-usable code), but for anything more complex, avoid using globals for everything.  You will save a lot of headache, the code will be easier to maintain, and your peers won't snicker at you behind your back for using globals.

A: Did you used require_once('file2.php') , and the same for the third file? Assuming you are running the first file.
Splitting fuctionallity into separate files requires those files to be included as if it was all in one file. Make sure that you did that.


text:
Q: Offline Spacewalk Server - Create Repo I have a CentOS7 server running Spacewalk 2.6
This server manages multiple other centOS servers on a closed loop network. These are not allowed to touch the internet.
To add packages to the Spacewalk server, I must download to a USB HDD and move them over manually.
My question is, how do I create a repo under a channel that points to local storage (since I don't have a Repository URL) and is there a default location on the file system that packages should be placed / stored?

A: *

*Make local package directory as a Local Repo : Use createrepo command

*install FTP/HTTP to create a link which can be pointing from spacewalk Channel Repo.

Eg: ftp://10.80.10.199/pub/centos6.


text:
Q: Analyzing user driving pattern data so I have a lot of GPXs of users driving data from a game project where object which are placed on the road and then the user collects it. I want to somehow analyze these data to find out how users tend to drive given different objects, which ones draw them the most, which ones draw least. I have not done any data analysis before, so how can I analyze these data to get this sort of information? This might sound very novice, but yeah any help is appreciated.

A: You would probably like to do this in Python if you are novice, and then you can use a library like this one (gpxpy) to explore your data.
That is a GPX parser, I believe it will provide you with the data you like to see.
In their documentation you can see that you can use it like that :
import gpxpy
import gpxpy.gpx

# Open a file
gpx_file = open('yourfile.gpx', 'r')

# Parse the file
gpx = gpxpy.parse(gpx_file)

# Iterate over the tracks
for track in gpx.tracks:
    for segment in track.segments:
        for pt in segment.points:
            print(f'Point at ({pt.latitude},{pt.longitude}) -> {pt.elevation}')

for waypoint in gpx.waypoints:
    print(f'waypoint {waypoint.name} -> ({waypoint.latitude},{waypoint.longitude})')

for route in gpx.routes:
    print('Route:')
    for pt in route.points:
        print(f'Point at ({pt.latitude},{pt.longitude}) -> {pt.elevation}')

Once you have those points you can calculate the distances, speeds, etc. from the coordinates.


text:
Q: Javascript - Como adicionar coisas no html e salvar informações do html Se o título do tópico ficou confuso peço desculpas, porque não sei como eu faria a minha pergunta de forma resumida e correta, mas é o seguinte...
Estou na reta final de um curso de informatica (acaba dia 13 desse mês) e a última tarefa do curso é criar um app para celular usando html, css e javascript e por fim fazer o porte para celular usando o Phonegap
O problema é que o curso não ensina JS (ensina apenas html e css) e eu estou com muita dificuldade em aprender JS, além da data de entrega estar muito próxima, a ideia do meu app é criar listas

Conforme esta na imagem, preciso fazer uma função para que quando eu clique no botão "Adicionar Item" na página seja adicionado outra caixa (um retangulo com input e textarea dentro dele) igual as duas que estão abaixo do input para adicionar titulo a lista
Sou muito leigo com JS, assisti várias vídeo aulas para tentar aprender, mas ainda não consegui entender nem a sintaxe básica direito
O que eu gostaria de saber é: o que eu deveria focar em aprender especificamente de JS, para fazer o botão "Adicionar Item" funcionar da forma que eu descrevi, e como eu faria para que as caixas criadas e as informações digitadas pelo cliente nos inputs e textarea salvem
Desde já peço desculpas pela minha leguisse no assunto
Meu HTML (somente o da pagina da imagem)

let currentItem = 3;
function adicionarItem(e) {
e.preventDefault(); // evitar que o form seja submetido

// criar o input
let input = document.createElement('input');
with (input) {
    classList.add('titulo');
    placeholder = 'Digite o Título da lista';
    maxLength = 19;
}
// criar o textarea
let textarea = document.createElement('textarea');
with (textarea) {
    classList.add('descricao');
    cols = 5;
    rows = 5;
    maxLength = 130;
}

// adiciona ambos em um div
let div = document.createElement('div');
div.id = 'retangulo' + currentItem; // usa o contador como parte do id
div.appendChild(input);
div.appendChild(textarea);

// atualiza o contador (assim o próximo div não terá id repetido)
currentItem++;

// adiciona a div no form
document.querySelector('#formulario').appendChild(div);
}

// ao clicar no botão, adiciona um novo item
document.querySelector('#botaoNovoItem').addEventListener('click', adicionarItem);
body {}

div {
  text-align: center;
  align-items: center;
}

.botao {
  background: #00FFFF;
  cursor: pointer;
  color: black;
  border: 0;
  text-decoration: none;
  text-shadow: 2px 2px 2px rgba(0, 0, 0, 0.5);
  border-radius: 0.5em;
  width: 300;
  font-size: 50;
  box-shadow: 2px 2px 0 1px #131;
  transition: box-shadow 0.3s ease, transform 0.3s ease;
  outline: 0;
  padding: 50px 0px 0px 0px;
}

.botao:active {
  box-shadow: 0 0 0 0 #131, inset 3px 3px 3px #131;
  transform: translate (3px, 3px);
}

.botaor {
  background: #836FFF;
  cursor: pointer;
  color: white;
  border: 0;
  text-decoration: none;
  text-shadow: 2px 2px 2px rgba(0, 0, 0, 0.5);
  border-radius: 0.5em;
  width: 300;
  font-size: 50;
  box-shadow: 2px 2px 0 1px #131;
  transition: box-shadow 0.3s ease, transform 0.3s ease;
  outline: 0;
}

.botaor:active {
  box-shadow: 0 0 0 0 #131, inset 3px 3px 3px #131;
  transform: translate (3px, 3px);
}

.listas {
  font-size: 50;
  text-align: center
}

.loading {
  font-size: 50;
  text-align: center
}

.logo {
  width: 856;
  height: 502;
  display: block;
  margin-left: auto;
  margin-right: auto;
}

.titulo {
  width: 300;
  height: 45;
  display: block;
  margin-left: auto;
  margin-right: auto;
  font-size: 28;
}

#retangulo {
  width: 300;
  height: 200;
  border: 3px solid;
  border-color: black;
  background: white;
  margin-left: auto;
  margin-right: auto;
}

.item {
  width: 280;
  height: 45;
  margin-top: 5;
  font-size: 25;
}

.descricao {
  width: 290;
  height: 140;
  margin-top: 9;
  font-size: 20;
}

.adicionaritem {
  margin-left: 400;
  background: #00BFFF;
  cursor: pointer;
  color: white;
  border: 0;
  text-decoration: none;
  text-shadow: 2px 2px 2px rgba(0, 0, 0, 0.5);
  border-radius: 0.5em;
  box-shadow: 2px 2px 0 1px #131;
  transition: box-shadow 0.3s ease, transform 0.3s ease;
  outline: 0;
  padding: 10px 0px 0px 0px;
  font-size: 15;
  width: 100;
}

.adicionaritem:active {
  box-shadow: 0 0 0 0 #131, inset 3px 3px 3px #131;
  transform: translate (3px, 3px);
}

.voltar {
  margin-left: 400;
  background: #00BFFF;
  cursor: pointer;
  color: black;
  border: 0;
  text-decoration: none;
  text-shadow: 2px 2px 2px rgba(0, 0, 0, 0.5);
  border-radius: 0.5em;
  box-shadow: 2px 2px 0 1px #131;
  transition: box-shadow 0.3s ease, transform 0.3s ease;
  outline: 0;
  padding: 0px 0px 0px 0px;
  font-size: 15;
  width: 100;
}

.voltar:active {
  box-shadow: 0 0 0 0 #131, inset 3px 3px 3px #131;
  transform: translate (3px, 3px);
}

  <title> Criar Lista </title>
  <link rel="stylesheet" type="text/css" href="personalizacao.css" />

                         <button class="voltar"> ⬅ Voltar para o início  </button>

                        <input type="text" class="titulo" placeholder="Digite o Título da lista" maxlength=18>

                        <form id="formulario">
  <button id="botaoNovoItem" class="adicionaritem">Adicionar item</button>

<input type="text" class="item" placeholder="Novo item" maxlength=19>
<textarea class="descricao"  cols="5" rows="5" maxlength=130></textarea>

<input type="text" class="item" placeholder="Novo item" maxlength=19>
<textarea class="descricao"  cols="5" rows="5" maxlength=130></textarea>

</form>

A: Para adicionar um novo item, você pode dar uma pesquisada na função appendChild se for JavaScript puro, ou append se você estiver usando jQuery. Tem um exemplo bem bacana em português aqui.
E para pegar os dados dos campos, você pode a função getElementById ou getElementsByTagName juntamente com a propriedade value, que também está no link do exemplo anterior.
Espero ter ajudado e boa sorte com o trabalho.

A: A ideia básica é usar createElement para criar os novos campos e adicioná-los em algum elemento já existente.
Tem outros detalhes para arrumar, como por exemplo:

*

*um id deve ser único na página, mas você criou dois div's com o mesmo id. Isso não dá erro (no sentido de não carregar a página), mas ao buscar ou manipular esses elementos, o JavaScript não se comportará da maneira esperada (pois as funções que usam o id assumem que ele é único)

*o HTML está mal formado (tem tags que fecham sem a respectiva abertura, as div's não têm o fechamento, etc). Então eu eliminei algumas partes no exemplo abaixo, e deixei somente o essencial para o exemplo (depois você completa com o restante do seu código)

Também eliminei boa parte do CSS, já que é somente "visual" e não interfere no JavaScript (pois a ideia é focar no funcionamento deste, então depois você adiciona novamente seu CSS).
Coloquei as div's dentro de um form, pois entendo que a ideia seja submeter estes dados posteriormente (se for só para preencher e não fazer nada, me pareceria inútil), então estes elementos deveriam estar em um form. Aproveitei para deixar este form como o elemento no qual serão adicionadas as novas div's.

let currentItem = 3;
function adicionarItem(e) {
    e.preventDefault(); // evitar que o form seja submetido

    // criar o input
    let input = document.createElement('input');
    with (input) {
        classList.add('titulo');
        placeholder = 'Digite o Título da lista';
        maxLength = 19;
    }
    // criar o textarea
    let textarea = document.createElement('textarea');
    with (textarea) {
        classList.add('descricao');
        cols = 5;
        rows = 5;
        maxLength = 130;
    }

    // adiciona ambos em um div
    let div = document.createElement('div');
    div.id = 'retangulo' + currentItem; // usa o contador como parte do id
    div.appendChild(input);
    div.appendChild(textarea);

    // atualiza o contador (assim o próximo div não terá id repetido)
    currentItem++;

    // adiciona a div no form
    document.querySelector('#formulario').appendChild(div);
}

// ao clicar no botão, adiciona um novo item
document.querySelector('#botaoNovoItem').addEventListener('click', adicionarItem);
div {
  border: 3px solid black;
  margin: 3px;
  padding: 3px;
}
<form id="formulario">
  <button id="botaoNovoItem" class="adicionaritem">Adicionar item</button>

    <input type="text" class="item" placeholder="Novo item" maxlength=19>
    <textarea class="descricao"  cols="5" rows="5" maxlength=130></textarea>

    <input type="text" class="item" placeholder="Novo item" maxlength=19>
    <textarea class="descricao"  cols="5" rows="5" maxlength=130></textarea>

</form>


text:
Q: Registry Value Change Error(Object reference not set to an instance of an object) I'am currently trying to make a little program, which changes my standard audio device from my USB Headset to my Speakers. After using Regshot to locate the registry keys that are changed by manually switching the audio devices, I was able to find out the binary codes for my Speaker and Headset.
static void Main(string[] args)
    {
        RegistryKey standarddevice = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\MMDevices\\Audio\\Render\\{02b3c792-0c05-486c-be02-2ded778dc236}", true);
        standarddevice.SetValue("Role:0", "DF 07 01 00 04 00 08 00 16 00 01 00 14 00 55 01", RegistryValueKind.Binary);
        standarddevice.SetValue("Role:1", "DF 07 01 00 04 00 08 00 16 00 01 00 14 00 55 01", RegistryValueKind.Binary);
        standarddevice.SetValue("Role:2", "DF 07 01 00 04 00 08 00 16 00 01 00 14 00 55 01", RegistryValueKind.Binary);
    }

The Problem, which I'am not able to solve, is that I get a "Object reference not set to an instance of an object" Error.

A: Seems that your standarddevice object is null.
Why do I get the error "Object reference not set to an instance of an object"?

A: It's most likely because the specified key does not exist.
Check out the documentation: http://msdn.microsoft.com/en-us/library/z9f66s0a(v=vs.110).aspx

*

*OpenSubKey will return null if the Open operation fails.

To resolve this, you should check for null and do the appropriate thing, perhaps:
RegistryKey standarddevice = Registry.LocalMachine.OpenSubKey(
    "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\MMDevices\\Audio\\Render\\" +
    "{02b3c792-0c05-486c-be02-2ded778dc236}", true);

if (standardDevice != null)
{
    standarddevice.SetValue("Role:0",
        "DF 07 01 00 04 00 08 00 16 00 01 00 14 00 55 01", RegistryValueKind.Binary);
    standarddevice.SetValue("Role:1",
        "DF 07 01 00 04 00 08 00 16 00 01 00 14 00 55 01", RegistryValueKind.Binary);
    standarddevice.SetValue("Role:2",
        "DF 07 01 00 04 00 08 00 16 00 01 00 14 00 55 01", RegistryValueKind.Binary);
}

If you see that the key does actually exist, it's possibly under the Wow6432Node if you're on a 64-bit machine. In that case you can try something like:
RegistryKey standarddevice = Registry.LocalMachine.OpenSubKey(
    "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\MMDevices\\Audio\\Render\\" +
    "{02b3c792-0c05-486c-be02-2ded778dc236}", true);

if (standardDevice == null)
{
    standarddevice = Registry.LocalMachine.OpenSubKey(
       "SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\MMDevices\\" +
       "Audio\\Render\\{02b3c792-0c05-486c-be02-2ded778dc236}", true);
}

if (standardDevice != null)
{
    standarddevice.SetValue("Role:0",
        "DF 07 01 00 04 00 08 00 16 00 01 00 14 00 55 01", RegistryValueKind.Binary);
    standarddevice.SetValue("Role:1",
        "DF 07 01 00 04 00 08 00 16 00 01 00 14 00 55 01", RegistryValueKind.Binary);
    standarddevice.SetValue("Role:2",
        "DF 07 01 00 04 00 08 00 16 00 01 00 14 00 55 01", RegistryValueKind.Binary);
}


text:
Q: SharePoint 2013 DataSheet View make Column mandatory I am currently trying to make a specific Column mandatory on SharePoint Datasheet View.
SharePoint default validation on Column or List Level are NOT an option.
I allready have the Code to check for the right view GUID and so on, but I can't find any hint on how to make a specific Column mandatory in a specific view.
I would be happy if I could insert the JS later on the Masterpage Level, but it would be also okay if it works via js Link.
I have tried for days now but I don't find the right point....
I hope it is understandable what I am trying to do.

A: I think you can go with customizing the particular list in infopath designer, make certain fields based on your requirement conditionally using the infopath rules.... this is very simple to implement than going with the coding approach.


text:
Q: Have text wrap at a certain width if it can without breaking a word I have an element which will contain dynamic text, that I would prefer to be 30% of its container, but wouldn't mind it stretching if the content won't allow due to long words.
If I have inline-block width 30% at certain times some of the text will overflow the container, and looks bad.
If I have inline-block width auto, the text never overflows, but the container grows as long as the text without breaking at all.
I'd like some way of having a "wrap at width" of 30%, so text begins wrapping there, but if it can't wrap the container just stretches big to be enough.
I'd love a 100% CSS answer if it can be done. I have a few ideas on how I'd do it in Javascript, but I want to avoid that if possible.
I have messed around with display:table-cell but that screwed up my layout because I need this to be 100% height, and tables don't respect that.
Problem illustrated here:
http://codepen.io/nicklepedde/pen/gLYgpw
html:

  Sometimes this text is long

This is filled with other content that sets the height some what dynamically

This is filled with other content that sets the height some what dynamically

This is filled with other content that sets the height some what dynamically

This is filled with other content that sets the height some what dynamically

This is filled with other content that sets the height some what dynamically

This is filled with other content that sets the height some what dynamically

This is filled with other content that sets the height some what dynamically

This is filled with other content that sets the height some what dynamically

This is filled with other content that sets the height some what dynamically

This is filled with other content that sets the height some what dynamically

This is filled with other content that sets the height some what dynamically

This is filled with other content that sets the height some what dynamically

This is filled with other content that sets the height some what dynamically

This is filled with other content that sets the height some what dynamically

CSS:
.con{position:relative;width:600px;background:orange}
.side{
  position:absolute;
  left:0;
  top:0;
  width:30%;
  height:100%;
  background:yellow;
  filter:opacity(.8);
  font-size:50px
}

UPDATE:
The font size, or actual text used is not under my control, please do not take my example too literally. I know that the word is too big, it's the point of me asking here. And no, I can't just change the font size, that's not an option in the problem I'm trying to solve.
I updated my codepen to more closely simulate my final product:
http://codepen.io/nicklepedde/pen/gLYgpw

A: You can just float the elements left and set the widths at the percentages you'd like. Just make sure to set a global box-sizing:border-box so your elements don't move down the page if you set margins and padding.

*{
  box-sizing:border-box;
}
.con{
  /*position:relative;*/
  float:left;
  width:70%;
  /*width:600px;*/
  background:orange;
    padding:4px;
}
.side{
  /*position:absolute;
    left:0;
  top:0;*/
  padding:4px;
  float:left;
  width:30%;
  height:100vh;
  background:yellow;
  filter:opacity(.8);
  font-size:50px /* for only 30% width, I would consider decreasing the font size */
}

  Sometimes this text is long

This is filled with other content that sets the height some what dynamically

This is filled with other content that sets the height some what dynamically

This is filled with other content that sets the height some what dynamically

This is filled with other content that sets the height some what dynamically

This is filled with other content that sets the height some what dynamically

This is filled with other content that sets the height some what dynamically

This is filled with other content that sets the height some what dynamically

This is filled with other content that sets the height some what dynamically

This is filled with other content that sets the height some what dynamically

This is filled with other content that sets the height some what dynamically

This is filled with other content that sets the height some what dynamically

This is filled with other content that sets the height some what dynamically

This is filled with other content that sets the height some what dynamically

This is filled with other content that sets the height some what dynamically

Here's my edit to your code, hope it helps.
http://codepen.io/ciammarino/pen/dObNQO


text:
Q: Measuring latency in a GStreamer pipeline I'm using a RTP pipeline to stream video from a camera over local network.
The pipeline is: camera > h264enc > RTP > UDP > receiver_and_display
How can I find out how the latency is composed?

A: Nowadays GStreamer has really nice tracers mechanisms to measure latency as for the whole pipeline or for individual elements
This is how this can be done with gst-launch
env GST_DEBUG="GST_TRACER:7" \
    GST_TRACERS="latency(flags=element+pipeline)" \
    GST_DEBUG_FILE=./latency.log \
    gst-launch-1.0 -v videotestsrc pattern=snow ! video/x-raw,width=640,height=480,framerate=30/1 ! videoconvert ! autovideosink

./latency.log will contain a lot of logs like this:
...
0:00:06.072184000 40898    0x11d816920 TRACE             GST_TRACER :0:: element-latency, element-id=(string)0x11e848210, element=(string)videotestsrc0, src=(string)src, time=(guint64)16000, ts=(guint64)6072172000;
0:00:06.072209000 40898    0x11d816920 TRACE             GST_TRACER :0:: element-latency, element-id=(string)0x11e850440, element=(string)capsfilter0, src=(string)src, time=(guint64)28000, ts=(guint64)6072200000;
0:00:06.072224000 40898    0x11d816920 TRACE             GST_TRACER :0:: element-latency, element-id=(string)0x11e824660, element=(string)videoconvert0, src=(string)src, time=(guint64)17000, ts=(guint64)6072217000;
0:00:06.072468000 40898    0x11d816920 TRACE             GST_TRACER :0:: element-latency, element-id=(string)0x11e83f280, element=(string)autovideosink0, src=(string)src, time=(guint64)21594000, ts=(guint64)6072456000;
....

So here you have a starting point to analyze latency (time=(guint64)... values) per element and experiment with different settings
More details in this article https://gstreamer.freedesktop.org/documentation/additional/design/tracing.html?gi-language=c#use-cases


text:
Q: Determine an absolute url to a resource using vbscript/classic asp I've created a pseudo user control for a site written in classic asp.  The control is simply an asp page (with full HTML headers and body) that resides within an iframe in the parent page.  The point was to create an AJAX-like interface for uploading files asynchronously (the parent page contains a large form and I didn't want to have to upload the files and submit the rest of the form at the same time).
The problem is, I'm running into a lot of issues with relative urls being used in the iframe page/user control.  Depending on what page the iframe is a child of, the relative url base location seems to change according to the directory that particular page is in.
Example:
www.website.com/directory1/application1.asp
...
<form>
    <input>
    ...
    <iframe src="../controls/FileUpload.asp"/>
    ...
</form>
...

www.website.com/directory1/directory2/application2.asp
...
<form>
    <input>
    ...
    <iframe src="../../controls/FileUpload.asp"/>
    ...
</form>
...

www.website.com/controls/FileUpload.asp
...
<form method="post" enctype="multipart/form-data" action="FileUpload.asp"><!--problem here-->
    <input type="file">
    <input type="submit"/>
</form>

The iframe src paths work correctly (notice the one that's buried a directory deeper has an extra double dot).  But in the code for the FileUpload.asp page, relative URLs don't work consistently.  The URL I have in the action attribute for the form tag works if you simply load the page as-is, not in an iframe of another page.  You can change it to "../controls/FileUpload.asp" and it will work on the first application page, but you have to add another "../" for it to work on the second application page.
I was wondering if maybe there's a way with vbscript to find the absolute URL to a certain file. I do use an include file into which I could hard-code this, but I'd rather not if that's possible. Any other ideas?

A: You could also just put in an absolute path from the root such as
action="/controls/FileUpload.asp"

A: I'm not sure if you are perhaps looking for
<%
Response.Write Server.MapPath("./foo.txt")
%>

Some usefull code from Thorarin
that I just saw in a different post
Look for ThisPage() Function


text:
Q: libfixmath's atan2 seems to produce invalid results - any ideas, suggestions or alternatives? I want to do fixed point math in C++, so I looked for a suitable library. libfixmath has been suggested here a couple of times, but I have difficulties with the atan2 function it provides. My test code calculates sine and cosine of an angle and then recalculates that angle using atan2:
#include <cmath>
#include <fstream>
#include <iostream>

#include <fix16.h>
#include <fix16.hpp>

int main()
{
  unsigned int n = 1000;
  std::ofstream atan2File("atan2.dat");
  for(unsigned int i = 0; i <= n; i++)
  {
    double d = M_PI/2.*i/n;
    double s = sin(d);
    double c = cos(d);
    double a = atan2(s,c);
    Fix16 df(d);
    Fix16 sf(df.sin());
    Fix16 cf(df.cos());
    Fix16 af(sf.atan2(cf));
    atan2File << d
              << " " << a
              << " " << (double)af
              << std::endl;
  }
  return 0;
}

Here is the plotted result:

It was generated with gnuplot using
plot "atan2.dat" u 1:2 w l title 'double', "atan2.dat" u 1:3 w l title 'Fix16'

Some values near zero and pi/2 are reasonable, but a lot are not. The code seems to use this algorithm for calculating atan2, but I couldn't spot where it might fail in the way shown above.

*

*Does anyone know of a possible bug in the libfixmath code?

*Is there an alternative library that provides trigonometric functions for fixed point values? I need sine, cosine, tangent and their inverse.

I could, of course, try to add the missing functions to other suggested fixed point libraries, but I don't have any experience in writing code for fixed point types.
gcc -v: gcc version 4.7.2 20130108 [gcc-4_7-branch revision 195012] (SUSE Linux)
I need fixed point because I want to do these calculations on a Cortex-M4 (no FPU). Actually I already had libfixmath in my Cortex-M4 code, but it has shown errors like those described above. OTOH, it was about 10 times as fast as the float version. I'd like to add more or less correct results to that speed.


text:
Q: Retain DataGrid IsSelectionActive when a ContextMenu opens in WPF? I have a DataGrid which has a style for IsSelectionActive; however, as soon as the ContextMenu opens, the grid loses IsSelectionActive and it looks like to the user that as if the context menu somehow took the selection and may confuse the user.
Is there a way to retain IsSelectionActive when a context menu opens?
<ControlTemplate.Triggers>
    <MultiTrigger>
        <MultiTrigger.Conditions>
            <!--<Condition Property="Selector.IsFocused" Value="True" />-->
            <Condition Property="IsSelected" Value="True" />
        </MultiTrigger.Conditions>

        <Setter Property="Background" Value="Red" />
    </MultiTrigger>

    <MultiTrigger>
        <MultiTrigger.Conditions>
            <Condition Property="Selector.IsFocused" Value="False" />
            <Condition Property="IsSelected" Value="False" />
        </MultiTrigger.Conditions>

        <Setter Property="Background" Value="Green" />
    </MultiTrigger>

    <MultiTrigger>
        <MultiTrigger.Conditions>
            <Condition Property="Selector.IsFocused" Value="False" />
            <Condition Property="IsSelected" Value="True" />
        </MultiTrigger.Conditions>

        <Setter Property="Background" Value="Blue" />
    </MultiTrigger>

A: Here is an entire XAML that I used in test application to get your desired behavior:
<Window x:Class="DataGridSelectionActive.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:DataGridSelectionActive"
        Title="MainWindow" Height="350" Width="525">

    <!-- People is just an ObservableCollection derived class. -->
    <Window.DataContext>
        <local:People/>
    </Window.DataContext>

    <Window.Resources>

        <ContextMenu x:Key="dataGridContextMenu">
            <MenuItem Header="Some context menu item"/>
        </ContextMenu>

        <Style TargetType="{x:Type DataGridCell}">
            <Style.Triggers>
                <Trigger Property="IsSelected" Value="True">
                    <Setter Property="Background" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/>
                    <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.HighlightTextBrushKey}}"/>
                    <Setter Property="BorderBrush" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/>
                </Trigger>
                <MultiDataTrigger>
                    <MultiDataTrigger.Conditions>
                        <Condition Binding="{Binding IsSelected, RelativeSource={RelativeSource Self}}" Value="True"/>
                        <Condition Binding="{Binding IsKeyboardFocusWithin, RelativeSource={RelativeSource AncestorType=DataGrid}}" Value="False"/>
                    </MultiDataTrigger.Conditions>
                    <Setter Property="Background" Value="{DynamicResource {x:Static SystemColors.ControlBrushKey}}"/>
                    <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
                    <Setter Property="BorderBrush" Value="{DynamicResource {x:Static SystemColors.ControlBrushKey}}"/>
                </MultiDataTrigger>
                <MultiDataTrigger>
                    <MultiDataTrigger.Conditions>
                        <Condition Binding="{Binding IsSelected, RelativeSource={RelativeSource Self}}" Value="True"/>
                        <Condition Binding="{Binding ContextMenu.IsOpen, RelativeSource={RelativeSource AncestorType=DataGrid}}" Value="True"/>
                    </MultiDataTrigger.Conditions>
                    <Setter Property="Background" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/>
                    <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.HighlightTextBrushKey}}"/>
                    <Setter Property="BorderBrush" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/>
                </MultiDataTrigger>
            </Style.Triggers>
        </Style>

    </Window.Resources>

    <DockPanel>
        <!-- Added button for testing keyboard focus. -->
        <Button DockPanel.Dock="Top" Content="Click me"/>
        <DataGrid ItemsSource="{Binding}" ContextMenu="{StaticResource dataGridContextMenu}"/>
    </DockPanel>

</Window>

The key thing that enables this behavior is that if multiple triggers that have conflicting Setters are active simultaneously, the last one wins.


text:
Q: SQL Server DAC - Connection Issue I am having a strange issue when trying to connect to my SQL Server instance remotely from my client computer. I am able to do this on my other instances by opening up a new Database Engine Query and PREFIXING ADMIN: in front of my server name. It only doesnt work on one instance. When I open up the Error Log, it states that "Dedicated admin connection support was established for listening remotely on port 55632." SQL Server Browser is running (and Restarted). When I try to connect to DAC on this one instance, I get an error saying to look in my SQL error logs.this is where I am getting confused:

I had installed a Monitoring solution from SolarWinds (DPA Free) last week. I didnt find it very useful so I uninstalled it and deleted the database where it stores the metrics (ignite_DBAnalyzer). I double-checked that this DB does not exist on this instance. This is the same DB, ignite_DBAnalyzer, it is claiming it cannot explicitly open (See line 1 of error log). I checked my user Mappings and that DB is not anywhere to be found. I checked my default DB to connect to when i start a new connection and that is also fine.
Has anyone seen this kind of behavior before? Is there cache somewhere I need to clean out so it forgets this DB and can verify that it has been deleted?


text:
Q: How do I statistically model events to account for arrival times? I've got a problem where I need to probabilistically score different possible sequences of events, and I think I'm missing something about how to properly model them.  Here's the example:  Say someone flips a fair coin once per second for a whole day. I didn't seen the coin flips, but am given a two possible sequences.  One has ~50% heads, but they all occur up front (the first half of the flips are all heads, then the remainder are all tails).  The second sequence is also ~50% heads, but they occur in a more random seeming way, distributed throughout the day.  In what sense, if any, is the second sequence more likely?
At the sequence level, all sequences have equal likelihood.  I can also look at a binomial distribution in number of heads, but they would score equally well against that metric too.  I could also look at the event arrival times, in terms of the number of flips between heads, perhaps looking at it as a Poisson with an exponential distribution describing the time between changes.  I believe this ends up scoring the same too though.  An ad-hoc thing would be to break it into time segments and score them separately - that would expose that it's very unlikely to get zero heads in 12 hours of flipping, but I don't like the ad-hoc nature of it, where I need to pick a time window interval.
What's the right way to do this?

A: One way you can model this is by counting the total number of "changes" from heads to tails (Binomial, and approximately normal with a large number of flips). Notice at each flip, there is an (independent) 1/2 probability that there will be a change in the sequence.
This approach will correctly combine groups of "regular" sequences you would get through a day, but will also pick out the highly unusual case of no changes in a large number of flips.

A: You definitely want to model the question with a binomial distribution. You have a fixed number of trials (once every second per day, or 86,400 trials a day), you have two possible outcomes (heads or tails), the probability of each result is constant (always 50% heads and 50% tails), and the results do no affect each other (flipping 2400 heads in a row doesn't mean more chance of flipping tails next time round). Poisson would not be the correct distribution here.
(For simplicity, I'm going to assume that the number of heads flipped is exactly 50%, since working with factorials of ~86,400 isn't a fun experience).
You're correct in your statement that two sequences have the same probability. The sequence HHHHTTTT has the same chance as HHTHTTHT. However, there is only one sequence where all of the heads occur first. In this example of 8 trials with 4 successes, there are 70 different sequences to arrange four heads and four tails, so that leaves 68 'seemingly random' sequences if you eliminate HHHHTTTT and TTTTHHHH.
It appears that the reason you can't find a good way to statistically model this is because you don't have a mathematical criteria. I would say something like, "if the same side is flipped more than 25 times in a row, the distribution is not seemingly random". In 86,400 trials, there are 86,376 chances for 25 flips in a row to be heads. Using 0.5^25 * 86376 gives us 0.257% chance of getting 25 heads in a row at some point. Multiplying by 2 to account for tails gives us 0.515% chance. You could change the '25' to whatever you wish.
Since the probability of HHHH...HHHH then TTTT...TTTT is 0.5^86400 (1.019E-26009, or 0.0000...[26004 more zeroes]...1019), you can see that this probability is vastly different to 0.515%. I believe that overlooking the amount of combinations that appear random was the missing piece here.


text:
Q: Should I install MariaDB to my git repo, or locally / individually to all development computers? I am starting work on a website that will use MariaDB for storing information  (no sensitive information), and would like to keep everything in my git repo.
Originally, I planned on installing MariaDB to the separate computers that I plan to develop on (my desktop and laptop), but decided that it may be easier to store all of MariaDB (the program and the databases) in the git repo, so that one would just need to clone the repo and run MariaDB from the repo just like they would run Node, but I have not found any information on how to do this.
My questions are (1) should I install MariaDB and its databases to my git repo, instead of installing MariaDB in /usr, and the database in /var/lib/mysql, and (2) how would one do that?

A: Instead of attempting to put a mariadb runtime environment inside your version control, consider using docker to describe how to configure an appropriate mariaDB installation.  I use makefiles atop that to contain the commands I use to build and run the docker but you coould just as easily use a shell script.  Finally, provide a dataabase load script that loads your test database from a text file within the repo.
using docker to describe runtime environments for your application and dependencies is awesome.  It strikes a great balance between having an incomplete git repo, and having to put binaries and database data in your version control.  You wouldn't want to track changes to the underlying maria db files, anyway, so best not to commit them.  You can build the docker containers you need on every workstation you use without much trouble, your automation around creating them provides a mechanism to ensure consistency, and by loading a database with the correct test data every time you develop your app, you'll have a better development process and less schema and data related changes.  It works great, I do nothing but docker driven development these days.


text:
Q: Different xstep and ystep in TikZ with to[path] (precisely to[grid with coordinates]) As it's my first question, I want to say hello first!
I am using [grid with coordinates] code from Andrew Stacey answer (link) for How can I show coordinates by grid in TikZ automatically?.
I modified it a bit and tried to acquire different major/minor lines xstep and ystep, I ended with:
\documentclass{article}

%\usepackage{pgfplots}
\usepackage{tikz,pgfplots}

\makeatletter
\def\grd@save@target#1{%
  \def\grd@target{#1}}
\def\grd@save@start#1{%
  \def\grd@start{#1}}
\tikzset{
  grid with coordinates/.style={
    to path={%
      \pgfextra{%
        \edef\grd@@target{(\tikztotarget)}%
        \tikz@scan@one@point\grd@save@target\grd@@target\relax
        \edef\grd@@start{(\tikztostart)}%
        \tikz@scan@one@point\grd@save@start\grd@@start\relax
        \draw[minor help lines] (\tikztostart) grid (\tikztotarget);
        \draw[major help lines] (\tikztostart) grid (\tikztotarget);
        \grd@start
        \pgfmathsetmacro{\grd@xa}{\the\pgf@x/1cm}
        \pgfmathsetmacro{\grd@ya}{\the\pgf@y/1cm}
        \grd@target
        \pgfmathsetmacro{\grd@xb}{\the\pgf@x/1cm}
        \pgfmathsetmacro{\grd@yb}{\the\pgf@y/1cm}
        \pgfmathsetmacro{\grd@xc}{\grd@xa + \pgfkeysvalueof{/tikz/grid with coordinates/major step x}}
        \pgfmathsetmacro{\grd@yc}{\grd@ya + \pgfkeysvalueof{/tikz/grid with coordinates/major step y}}
        \foreach \x in {\grd@xa,\grd@xc,...,\grd@xb}
        \node[anchor=north] at (\x,\grd@ya) {\pgfmathprintnumber{\x}};
        \foreach \y in {\grd@ya,\grd@yc,...,\grd@yb}
        \node[anchor=east] at (\grd@xa,\y) {\pgfmathprintnumber{\y}};
      }
    }
  },
  minor help lines/.style={
    help lines,
    gray,
    line cap =round,
    xstep=\pgfkeysvalueof{/tikz/grid with coordinates/minor step x},
    ystep=\pgfkeysvalueof{/tikz/grid with coordinates/minor step y}
  },
  major help lines/.style={
    help lines,
    line cap =round,
    line width=\pgfkeysvalueof{/tikz/grid with coordinates/major line width},
    xstep=\pgfkeysvalueof{/tikz/grid with coordinates/major step x},
    ystep=\pgfkeysvalueof{/tikz/grid with coordinates/major step y}
  },
  grid with coordinates/.cd,
  minor step x/.initial=.5,
  minor step y/.initial=.2,
  major step x/.initial=1,
  major step y/.initial=1,
  major line width/.initial=1pt,
}
\makeatother

What I need now is to specify xstep and ystep in actual tikzpicture, e.g. in code below I want to pass xstep and ystep (for minor and major lines separately) so that Fig. B gets major lines xstep =0.2.
\begin{document}

\begin{figure}
    \centering
    \begin{tikzpicture}[xscale=1,yscale=2]
    \draw (0,0) to[grid with coordinates] (5,1);
    \end{tikzpicture}
    \caption{A}\label{fig:sphere}
\end{figure}

\begin{figure}
    \centering
    \begin{tikzpicture}[xscale=5,yscale=2]
    \draw (0,0) to[grid with coordinates] (1,1); %major step x =0.2
    \end{tikzpicture}
    \caption{B}\label{fig:sphere}
\end{figure}

\end{document}

I can't guess how to pass the parameters.

A: You can use the option
grid with coordinates/major step x=<value>

A complete example:
\documentclass{article}

%\usepackage{pgfplots}
\usepackage{tikz,pgfplots}

\makeatletter
\def\grd@save@target#1{%
  \def\grd@target{#1}}
\def\grd@save@start#1{%
  \def\grd@start{#1}}
\tikzset{
  grid with coordinates/.style={
    to path={%
      \pgfextra{%
        \edef\grd@@target{(\tikztotarget)}%
        \tikz@scan@one@point\grd@save@target\grd@@target\relax
        \edef\grd@@start{(\tikztostart)}%
        \tikz@scan@one@point\grd@save@start\grd@@start\relax
        \draw[minor help lines] (\tikztostart) grid (\tikztotarget);
        \draw[major help lines] (\tikztostart) grid (\tikztotarget);
        \grd@start
        \pgfmathsetmacro{\grd@xa}{\the\pgf@x/1cm}
        \pgfmathsetmacro{\grd@ya}{\the\pgf@y/1cm}
        \grd@target
        \pgfmathsetmacro{\grd@xb}{\the\pgf@x/1cm}
        \pgfmathsetmacro{\grd@yb}{\the\pgf@y/1cm}
        \pgfmathsetmacro{\grd@xc}{\grd@xa + \pgfkeysvalueof{/tikz/grid with coordinates/major step x}}
        \pgfmathsetmacro{\grd@yc}{\grd@ya + \pgfkeysvalueof{/tikz/grid with coordinates/major step y}}
        \foreach \x in {\grd@xa,\grd@xc,...,\grd@xb}
        \node[anchor=north] at (\x,\grd@ya) {\pgfmathprintnumber{\x}};
        \foreach \y in {\grd@ya,\grd@yc,...,\grd@yb}
        \node[anchor=east] at (\grd@xa,\y) {\pgfmathprintnumber{\y}};
      }
    }
  },
  minor help lines/.style={
    help lines,
    gray,
    line cap =round,
    xstep=\pgfkeysvalueof{/tikz/grid with coordinates/minor step x},
    ystep=\pgfkeysvalueof{/tikz/grid with coordinates/minor step y}
  },
  major help lines/.style={
    help lines,
    line cap =round,
    line width=\pgfkeysvalueof{/tikz/grid with coordinates/major line width},
    xstep=\pgfkeysvalueof{/tikz/grid with coordinates/major step x},
    ystep=\pgfkeysvalueof{/tikz/grid with coordinates/major step y}
  },
  grid with coordinates/.cd,
  minor step x/.initial=.5,
  minor step y/.initial=.2,
  major step x/.initial=1,
  major step y/.initial=1,
  major line width/.initial=1pt,
}
\makeatother

\begin{document}

\begin{figure}
    \centering
    \begin{tikzpicture}[xscale=1,yscale=2]
    \draw (0,0) to[grid with coordinates] (5,1);
    \end{tikzpicture}
    \caption{A}\label{fig:sphere}
\end{figure}

\begin{figure}
    \centering
    \begin{tikzpicture}[xscale=5,yscale=2,grid with coordinates/major step x=0.2]
    \draw (0,0) to[grid with coordinates] (1,1); %major step x =0.2
    \end{tikzpicture}
    \caption{B}\label{fig:sphere}
\end{figure}

\end{document}

Analogously, you can change major step y, minor step x, minor step y, and major line width.


text:
Q: How to refresh my simulation to its beginning? I created a coronavirus simulation and I wanted to refresh everything to the beginning each time I click the screen. I would greatly appreciate your help if you could help me. Thank you!
My code:
x= [ ]
y= [ ]
h= [False, True] #False=> infected
infected=1
healthy=24
runs=0

def setup():
    size(500,500)

    #Setting up the ... random coordinates
    for i in range(25):
        x.append(random(0,500))
        y.append(random(0,500))
        h.append(True) #All healthy, h is health
    textSize(12);

def distance(x1, x2, y1, y2):
    a=(x1-x2)
    b=(y1-y2)
    c= sqrt(a**2 + b**2)
    return c

def draw():
    global x, y, infected, healthy
    background(255)

      #Drawing the individuals
    for individuals in range(len(x)):
        strokeWeight(2)
        if h[individuals] == True:
            fill(255)  #healthy
        else:
            fill(255,0,0)  #infected

        circle(x[individuals], y[individuals], 40)
        #calulate the distance to each neighbors
        for neighbors in range(len(x)):
            if neighbors == individuals:
                continue
            d = distance(x[individuals], x[neighbors], y[individuals], y[neighbors])
            if d < 40 and (h[neighbors] == False or h[individuals]==False) and (h[individuals] == True or h[neighbors] == True):
                #infection happens
                h[individuals] = False
                h[neighbors] = False
                infected = infected + 1
                healthy = healthy -1
                if healthy <0:
                    healthy=0
                if infected >25:
                    infected=25   #Need to put infected, healthy stuff in another if statement

    for m in range(len(x)):
        x[m]= x[m] + random(-10,10)
        y[m]= y[m] + random(-10,10)
        if x[m] > 500:
                x[m] = 500

        if y[m] > 500:
                    y[m] = 500
        if x[m] < 0:
                    x[m] = 0
        if y[m] < 0:
                    y[m] = 0
    barGraph()
    delay(100)

def barGraph():
    global infected, healthy, runs
    strokeWeight(1)
    fill(255,0,0)
    rect(60, 10, infected, 10) #(x coordinate, y coordinate, width, height)
    fill(3,3,3)
    text('Infected', 10,20)
    text(infected, 180,20)
    strokeWeight(1)
    fill(255)
    rect(60, 30, healthy, 10)
    fill(3,3,3)
    text('Healthy', 10,40)
    text(healthy, 180, 35)
    text('Click screen to run the simulation again', 10, 60)
    text('Iteration # :', 10,80 )
    text(runs, 120,80)

P/s. This is what I had been trying so far for the code to refresh:
def mouseClicked():
    global infected, healthy, x
    infected=1
    healthy=24
    for individuals in range(len(x)-1):
        strokeWeight(2)
        if h[individuals] == True:
            fill(255)  #healthy
            circle(x[individuals], y[individuals], 40)
    for individuals in range(1):
        strokeWeight(2)
        fill(255,0,0)  #infected
        circle(x[individuals], y[individuals], 40)

However, it only refresh the bar graphs, not the circles. It should refresh so that in the beginning, there will be 1 red infected circle, the other 24 circles are white and healthy.

A: Define a function initSimulation the function has to initialize all attributes and to create the lists x, y and h:
def initSimulation():
    global infected, healthy, x, y, h
    infected=1
    healthy=24
    x = [ ]
    y = [ ]
    h = [ ]
    #Setting up the ... random coordinates
    for i in range(25):
        x.append(random(0,500))
        y.append(random(0,500))
        h.append(True) #All healthy, h is health
    h[0] = False

Invoke the function in setup and when the mouse is clicked:
def setup():
    size(500,500)
    textSize(12);
    initSimulation()

def mouseClicked():
    initSimulation()


text:
Q: Surjectivity of a an endomorphism such that $\varphi\left(f\right) = f \circ g -f$ Let $E$ the set of functions $f$ from $f :\left[0;1\right] \rightarrow\mathbb{R}$ and for all $x \in \left[0;1\right]$, there exists $C \geq 0$ such that $\left|f\left(x\right)\right| \leq C \left|x\right|$. Let $\varphi$ the endomorphism such that for all $f \in E$:
$$
\varphi\left(f\right) = f \circ g-f
$$
where $g : x \mapsto \frac{x}{2}$.
I need to show that $\varphi$ is an automorphism. I've shown that
$$
\varphi\left(f\right) = 0 \Rightarrow\forall x \in \left[0;1\right], \ f\left(\frac{x}{2}\right)=f\left(x\right) \Rightarrow \forall n \in \mathbb{N}, \ f\left(\frac{x}{2^n}\right)=f\left(x\right)
$$
And
$$
\left|f\left(\frac{x}{2^n}\right)\right| \leq \frac{x}{2^n} \underset{n \rightarrow +\infty}{\rightarrow}0
$$
Hence
$$
\left|f\left(x\right)\right|=0
$$
Hence $f=0$ and I have $\varphi$ injective. However, I'm stuck with surjectivity. I need to prove that for all $h \in E$, I can find $f$ such that
$$
\varphi\left(f\right) = f \circ g-f=h
$$
which means that for all $x \in \left[0;1\right]$, it should fulfill
$$
f\left(\frac{x}{2}\right)-f\left(x\right)=h\left(x\right)
$$
All my ideas are gone since we dont know about $f$ being differentiable. I've tried to express $f$ as a function of $h$ but in vain. Any hint would be much appreciated

A: Hint(s): You've shown that we have:
$$\begin{align*} \forall x \in [0,1],\,\forall n \in \mathbb{N},\quad\left|f\left(\frac{x}{2^n}\right)\right| \leq\, C\frac{x}{2^n} \xrightarrow[n \to \infty]{} 0 \tag{1}\\
{}\end{align*}$$
On the other hand, the relation $h(x) = \displaystyle f\left(\frac{x}{2}\right) - f(x)$ is true for all $x \in [0,1]$, so for example, say, $\displaystyle \frac{x}{2}$...
${}$
${}$
${}$
Full solution below (tried to find a way to spoiler tag all of it and failed, so try to not read the following if you want to only use the hints at first):
First, let's find a candidate using our for now formal equation $h(x) = \displaystyle f\left(\frac{x}{2}\right) - f(x)$ with some telescoping, for all $n \in \mathbb{N}^*$:
$$\sum_{k=0}^{n-1} h\left(\frac{x}{2^k}\right) = \sum_{k=0}^{n-1} \left(f\left(\frac{x}{2^{k+1}}\right) - f\left(\frac{x}{2^k}\right)\right) = f\left(\frac{x}{2^n}\right) - f(x) \xrightarrow[n \to \infty]{} -f(x)$$
This gives us a possible candidate $x \mapsto \displaystyle -\sum_{n=0}^{\infty} h\left(\frac{x}{2^n}\right)$ for our $f$. Let's check that this function is well-defined, belongs to $E$, and does satisfy $\varphi(f) = h$.

*

*Let $C \geq 0$ be such that $|h(x)| \leq Cx$ for all $x \in [0,1]$ ($C$ exists since $h \in E$).
$h$ satsifies $(1)$ for that $C$, and thus, since the series $\displaystyle\sum_{n\geq 0} \frac{x}{2^n}$ converges, so is $\displaystyle\sum_{n \geq 0} \left|h\left(\frac{x}{2^n}\right)\right|$, which grants that $f$ is well-defined on $[0,1]$ since absolute convergence implies convergence for real-valued series.

*Using $(1)$ in more detail, we have, since $(1)$ holds for all $n$:
$$\forall x \in [0,1],\quad|f(x)| = \left|-\sum_{n \geq 0} h\left(\frac{x}{2^n}\right)\right| \leq \sum_{n \geq 0} \left|h\left(\frac{x}{2^n}\right)\right| \leq \sum_{n\geq 0} C\frac{x}{2^n} = Cx \cdot \sum_{n \geq 0} \frac{1}{2^n} = 2Cx$$
Therefore, $f$ indeed belongs in $E$.

*There only remains one thing to check. Let $x \in [0,1]$:
$$\varphi(f)(x) = -\sum_{n \geq 0} h\left(\frac{\frac{x}{2}}{2^n}\right) - \left(-\sum_{n \geq 0} h\left(\frac{x}{2^n}\right)\right) = h(x) + \sum_{n \geq 1} h\left(\frac{x}{2^n}\right) - \sum_{n \geq 1} h\left(\frac{x}{2^n}\right) = h(x)$$
Hence $\varphi : E \to E$ is indeed surjective.


text:
Q: AWS SSM deleting its own files as part of its execution. Any way to safely do it? Is there a safe way to delete all of an AWS SSM runRemoteScript directory as part of execution?  Details below.
We've got a very robust AWS SSM setup working involving a python app that polls AWS, grabs the instances you want based on tags, and then issues remote commands to it via SSM.  If you give it a command, it uses runShellScript to simply execute what you want.  If you specify a file, it uploads a single shell script (requires bash), sets its attributes to public, and then, on the remote side, executes curl https://domain/file.sh | /bin/bash using AWS' runShellScript.
However, if you specify a directory at the command line, it uploads the entire directory to S3 and then issues a runRemoteScript command and automatically executes autorun.sh on the remote side.  Of course, autorun.sh can contain anything we want.  I typically use it to python3 uploaded_script.py and call it good.
One of the current tasks is to set up tripwire (Open Source, so everything is local on the individual machines).  For those unaware, it encrypts its database and configuration files using passphrases.  I've got 32 byte random passphrases created and can issue them, but in order to do so (I think), I have to send them in the upload so the scripts know what passphrases to use at the command line for report generation.  We don't want to leave the passphrases lying around, hence my question.
Is there a safe way to just delete all of the files in question while guaranteeing that I'm not going to somehow trash another, potentially random directory?
My idea is in the autorun.sh script to put at the very bottom:  rm -f *.ini
But, me being paranoid, I want to somehow guarantee I'm deleting ONLY what I want to be deleting.
I would like to manually specify the directory of the downloaded contents, but the path contains the InstanceId, which the script doesn't have.
Thoughts on how to maintain security while automating this task?
If I could simply (and safely!) wipe the ENTIRE contents of /var/lib/amazon/ssm/<InstanceId>/document/orchestration/<CommandID>, I gladly would, but then I'd have to know how to get the InstanceId during script execution, too.


text:
Q: Set Snapshot isolation is not reflecting When I ran - SET TRANSACTION ISOLATION LEVEL SNAPSHOT -Command successfully executed But the below query returns :
SELECT is_read_committed_snapshot_on,
       snapshot_isolation_state_desc,
       snapshot_isolation_state
FROM   sys.databases
WHERE  name = 'MyDB'

Output:
is_read_committed_snapshot_on   0
snapshot_isolation_state_desc   OFF
snapshot_isolation_state        0

Could you pleae let me know why the set transction command is not reflecting?
Also, I assume ALLOW_SNAPSHOT_ISOLATION is already "on" as my "SET TRANSACTION ISOLATION LEVEL SNAPSHOT "command runs successfully.Is that correct?

A: No snapshot isolation is not on for that database.
If you try and then run a query against that database you will get the message.

Snapshot isolation transaction failed accessing database 'MyDB'
  because snapshot isolation is not allowed in this database. Use ALTER
  DATABASE to allow snapshot isolation.

To enable it you need to run
ALTER DATABASE MyDB SET ALLOW_SNAPSHOT_ISOLATION ON;


text:
Q: How to extract vertical/slanting text alongwith bounds from pdf file using pdfbox? I have implemented functionality using pdfbox to extract words from any pdf. It extracts the words line by line. Below is the class that I am using for this purpose:
    class PDFTextLocationStripper : PDFTextStripper
    {
        public string textWithPostion = "";
        public Dictionary<float, Dictionary<float, PdfWord>> pdfWordsByXByY;

        public PDFTextLocationStripper(): base()
        {
            try
            {
                textWithPostion = "";
                pdfWordsByXByY = new Dictionary<float, Dictionary<float, PdfWord>>();
            }
            catch (Exception ex)
            {

            }
        }

        protected override void processTextPosition(TextPosition text)
        {
            try
            {
                float textX = text.getXDirAdj();
                float textY = text.getYDirAdj();
                if (!String.IsNullOrWhiteSpace(text.getUnicode()))
                {
                    if (pdfWordsByXByY.ContainsKey(textY))
                    {
                        Dictionary<float, PdfWord> wordsByX = pdfWordsByXByY[textY];
                        if (wordsByX.ContainsKey(textX))
                        {
                            PdfWord word = wordsByX[textX];
                            wordsByX.Remove(word.Right);
                            word.EndCharWidth = text.getWidthDirAdj();
                            if (text.getHeightDir() > word.Height)
                            {
                                word.Height = text.getHeightDir();
                            }
                            word.EndX = textX;
                            word.Text += text.getUnicode();
                            if (!wordsByX.Keys.Contains(word.Right))
                            {
                                wordsByX.Add(word.Right, word);
                            }
                        }
                        else
                        {
                            float requiredX = -1;
                            float minDiff = float.MaxValue;
                            for (int index = 0; index < wordsByX.Keys.Count; index++)
                            {
                                float key = wordsByX.Keys.ElementAt(index);
                                float diff = key - textX;
                                if (diff < 0)
                                {
                                    diff = -diff;
                                }
                                if (diff < minDiff)
                                {
                                    minDiff = diff;
                                    requiredX = key;
                                }
                            }
                            if (requiredX > -1 && minDiff <= 1)
                            {
                                PdfWord word = wordsByX[requiredX];
                                wordsByX.Remove(requiredX);
                                word.EndCharWidth = text.getWidthDirAdj();
                                if (text.getHeightDir() > word.Height)
                                {
                                    word.Height = text.getHeightDir();
                                }
                                word.EndX = textX;
                                word.Text += text.getUnicode();
                                if (!wordsByX.ContainsKey(word.Right))
                                {
                                    wordsByX.Add(word.Right, word);
                                }
                            }
                            else
                            {
                                PdfWord word = new PdfWord();
                                word.Text = text.getUnicode();
                                word.EndX = word.StartX = textX;
                                word.Y = textY;
                                word.EndCharWidth = word.StartCharWidth = text.getWidthDirAdj();
                                word.Height = text.getHeightDir();
                                if (!wordsByX.ContainsKey(word.Right))
                                {
                                    wordsByX.Add(word.Right, word);
                                }
                                pdfWordsByXByY[textY] = wordsByX;
                            }
                        }
                    }
                    else
                    {
                        Dictionary<float, PdfWord> wordsByX = new Dictionary<float, PdfWord>();

        PdfWord word = new PdfWord();
                    word.Text = text.getUnicode();
                    word.EndX = word.StartX = textX;
                    word.Y = textY;
                    word.EndCharWidth = word.StartCharWidth = text.getWidthDirAdj();
                    word.Height = text.getHeightDir();
                    wordsByX.Add(word.Right, word);
                    pdfWordsByXByY.Add(textY, wordsByX);
                }
            }
        }
        catch (Exception ex)
        {

        }
    }
}

Here, is the code to call this class:
        private Dictionary<float, Dictionary<float, PdfWord>> ExtractTextWithLocation(PDDocument doc)
        {
            try
            {
                PDFTextLocationStripper textStripper = new PDFTextLocationStripper();
                textStripper.setSortByPosition(true);
                textStripper.getText(doc);
                return textStripper.pdfWordsByXByY;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

This code extracts words which are aligned horizontally fine, but how do I implement functionality to detect words which are vertical or slanting?


text:
Q: How to read Scaled Graphs?
Please ignore the graphed lines, those are irrelevant to the question, it's the graph itself that's relevant.
I see this type of graph used all the time, between multiple manufacturers and device types. It's a plotted graph, x * y, where x could be time, and y some value, or vis-versa or a mix of different variables. While I can extrapolate the approximate value of a point between two marked values (ex: The 1 hour and the 10 hour), I still don't know what the in between values should be.

Is each line half between the next highest up? For example. Half way between 100 to 1000 is 500. So that next line up from 100 is 500. Then half way between 500 and 1000 is 750. Then 875, etc? x = y + ((y - z) / 2), where Y is the next marked up, and Z is the last value to the left?
Or is it a simple next value up. 100, 200, 300, etc? If so, why the scaling to the distance instead of linear graph?
And most importantly, do these type of scaled graphs have a specific name or standard attached to them?

A:
I'm sorry @Passerby.  I couldn't resist.

A: It's a log-log plot.
The lines still denote "equal" spacing. So your ? mark is 200, and the ?! mark is 300, and so on.
If there's less than 10 marks, then the step is will be larger (say, 5 minor marks from 100 to 1000 equals 200/minor mark). Because it's a logarithmic plot, their spacing isn't even. It makes is somewhat harder to estimate the value in between the lines, I tend to take a "lazy" approach and linearly interpolate between the minor marks, though you can do a log fit to get more precise results.
Log-log plots are used for several reasons. The figure of interest can have a very large dynamic range (say the irradiance vs. current response of photodiodes), or there may be some interesting exponential growth/decay, which will become linear on a log-log plot.

A: This is a log graph, or more accurately, log log, because both x and y are log axes.  The lines between 100 and 1000 are 200, 300, 400, etc.

A: That's a "log log" graph. You may notice that the major divisions go up by factors of ten.
The minor divisions in the example, say starting after 100, are 200, 300, 400, and so on up to 900.
log(100) is 2
log(1000) is 3
So halfway between is \$10^{2.5}\$ or about 316.
It is said that just about everything is approximately linear if you plot it on a log-log graph with a fat marker.