text:
Q: Navigate to chatter file in salesforce1 and salesforce I've been trying to navigate to chatter file both in desktop browser and in salesforce1 from a publisher action but I can't seem to get it working.
I have a VF Page like
<script  type="text/javascript">

function redirectToFile(){
    if ( (typeof sforce != 'undefined') && (sforce != null) ) {
        sforce.one.navigateToSObject('{!file.Id}');
    }
}
</script>

<apex:actionFunction name="createPDF" action="{!generatePdf}" oncomplete="redirectToFile();"/>

<script type="text/javascript">
window.setTimeout(createPDF,50);
</script>

And on the generatePdf method I insert a ContentVersion (which is happening) and return a PageReference with the Id of that 'ContentVersion`.
public ContentVersion file {get;set;}
public PageReference generatePdf(){
    file = new ContentVersion();
    //Some code to create a PDF file...
    insert file;
    return new PageReference('/' + file.Id);
}

When I remove the oncomplete statement the redirect works in desktop, but I haven't been able to do so in mobile.

A: Here is a workaround I found to get it working in both Salesforce1 and Salesforce Website:
In the page:
<apex:page standardController="Custom__c" extensions="Extension" action="{!generatePdf}">

     <script type="text/javascript">
     var fileId = '{!JSENCODE(fileId)}';
     if (fileId.length > 14) {
        if (sforce.one) {
             window.location.href = 'javascript:sforce.one.navigateToURL(\'' + fileId + '\')';
         }
      }
     </script>
</apex:page>

Where fileId is the ID of the generated ContentVersion (remember to just pass the ID, not the entire ContentVersion object since this will crash your view state)
In the class:
public String fileId {get; private set;}

public PageReference generatePdf(){
    ContentVersion file = new ContentVersion();
    //Some stuff to generate the pdf
    insert file;
    fileId = String.valueOf(file.Id);

    if (isS1())
        return null;
    else
        return new PageReference('/' + fileId);
}

public Boolean isS1(){

    String retUrl = ApexPages.currentPage().getParameters().get('retURL');

    return String.isNotBlank(ApexPages.currentPage().getParameters().get('sfdcIFrameHost')) || String.isNotBlank(ApexPages.currentPage().getParameters().get('sfdcIFrameOrigin')) || ApexPages.currentPage().getParameters().get('isdtp') == 'p1' || (String.isNotBlank(retUrl) && retURL.contains('projectone'));

}

Notes:

*

*The fileId.length > 14 is just to check that there is a file in context with a valid Id

*The method isS1() was taken from here


text: Q: How can I create an object in the android menu with Unity? Okay so messanger does it, I have seen plenty of other apps doing it as well, I'd like kind of create like a tomagachi, but more extreme/aggressive version of it as a game on the menu, with some twists, I am capable of doing that, have worked on numerous Android projects, but I never tried displaying something without a game window as you might say and this won't be that really effective and good without me being able to learn how to possible create an object like this. Thank you.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Intent overlap the dialog box? I write this code to make a dialogue box with 'yes' and 'no' option appear after pressing the 'OK' button. The'Yes'should lead users to a 'ShowResult' activity where it will show the user's input from the 'Main Activity'; and the 'No' will just have a toast message saying 'you have cancelled the submission.'
The problem is when the 'OK'button is clicked, the dialogue pops up for a second, then the intent will show up, covering the dialogue box.
If I click return and click 'Yes', the activity won't show the user inputs.  This is the Main activity code I have been struggling on.  I hope to not change much of the whole structure since this is a school project and we should be using simple techniques.
 Button btnOK;
    EditText txtName;
    EditText txtCoursename;
    RadioButton rdnYear1;
    RadioButton rdnYear2;

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

        btnOK = (Button) findViewById(R.id.btnOK);
        btnOK.setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {

        Intent intent = new Intent(this, ShowResult.class);
        txtName = (EditText) findViewById(R.id.txtName);
        txtCoursename = (EditText) findViewById(R.id.txtCoursename);
        rdnYear1 = (RadioButton) findViewById(R.id.rdnYear1);
        rdnYear2 = (RadioButton) findViewById(R.id.rdnYear2);

        intent.putExtra("Name", txtName.getText().toString());
        intent.putExtra("Course Name", txtCoursename.getText().toString());
        intent.putExtra("Year 1", rdnYear1.isChecked());
        intent.putExtra("Year 2", rdnYear2.isChecked());

        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setCancelable(false);

            switch (v.getId()) {
            case R.id.btnOK:
                builder.setTitle("You are submitting your data.");
                builder.setMessage("Are you sure?");
                builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(getApplicationContext(), "You cancelled the submission.", Toast.LENGTH_SHORT).show();
                    }

                });
                builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startActivity(new Intent(MainActivity.this, ShowResult.class));

                    }
                });

                builder.show();
            }
    }
}

A: try putting the intent part inside the switch case & do add startActivity(intent);

A: You have already created an intent at the very start of "onClick". Try using the same intent instead of creating another new one after postive clicks. Also, I didn't see a break statement in your switch case which needs to be followed.

A: builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    startActivity(new Intent(MainActivity.this, ShowResult.class));

                }
            });

            builder.show();
        }

here you are creating a new intent with no data
you should use your previously created intent where you used putExtra()
use this :
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

////////////////////////////
                        startActivity(intent);
\\\\\\\\\\\\\\
                    }
                });
            builder.show();
        }


text:
Q: INFILE MySQL - TIMESTAMP not working I am trying to use the INFILE statement to import data from a tab delimited file. However, one of the data types is a TIMESTAMP. I tried using NULL in the flat file, but the resulting value after executing the statement was '0000-00-00 00:00:00'. What value can I use so the TIMESTAMP will work?

A: your table definition should be
timestamp_column TIMESTAMP DEFAULT CURRENT_TIMESTAMP

then when inserting the timestamp_column should be time of insert.


text:
Q: How to keep n osgi bundle listening to the mqtt broker I was able to bundle the ActiveMQ and push it into the Apache Felix context.
But I faced an issue once started playing with it:
Here is the scenario :

*

*I created the ActiveMQ bundle inside Apache Felix, I run it and it listens to the needed port.

*I created the producer bundle and putted all the needed connection and queue creation in the start method.

*I created the consumer bundle following the same strategy

Once I start the producer, I can see my message sent.
Once I run the consumer it's OK I can see the message received,
the issue is once I stop the producer bundle and I restart it, I was waiting to get a notification from my consumer bundle getting the new message.. but not, I do have to restart the consumer so it knows about the new message and throw it out.
Do you have an idea on how could I get notified by my bundle once a new message pushed into the broker queue ?
I'm thinking about the multithreading, but I'm not sure, in the activeMq tutos it creates the producers/consumers using threads.
So probably that's the issue..
Do I have to register my bundle in the osgi service registry ?!
//this is my start method
// Create a ConnectionFactory
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost");

// Create a Connection
Connection connection = connectionFactory.createConnection();
connection.start();

// Create a Session
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

// Create the destination (Topic or Queue)
Destination destination = session.createQueue("TEST.FOO");

// Create a MessageProducer from the Session to the Topic or Queue
MessageProducer producer = session.createProducer(destination);
producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

// Create a messages
String text = "Hello world! From: " + Thread.currentThread().getName() + " : " + this.hashCode();
TextMessage message = session.createTextMessage(text);

// Tell the producer to send the message
System.out.println("Sent message: "+ message.hashCode() + " : " + Thread.currentThread().getName());
producer.send(message);

// Clean up
session.close();
connection.close();


text:
Q: Cauchy's theorem: what about non-smooth homotopies? This morning I realized I have never understood a technical issue about Cauchy's theorem (homotopy form) of complex analysis. To illustrate, let me first give a definition.
(In what follows $\Omega$ will always denote an open subset of the complex plane.)
Definition Let $\gamma, \eta\colon [0, 1]_t \to \Omega$ be two piecewise smooth closed curves (or circuits). We say that $\gamma, \eta$ are $\Omega$-homotopic if there exists a continuous mapping $H \colon [0, 1]_\lambda \times [0, 1]_t \to \Omega$ s.t.

*

*$H(0, t)=\gamma(t)$ and $H(1, t)=\eta(t), \quad \forall t \in [0, 1]$;

*$H(\lambda, 0)=H(\lambda, 1), \quad \forall \lambda \in [0, 1]$.

Theorem (Cauchy) Let $f\colon \Omega \to \mathbb{C}$ be holomorphic. If $\gamma, \eta$ are $\Omega$-homotopic circuits, then
$$\int_{\gamma} f(z)\, dz= \int_{\eta}f(z)\, dz.$$

Problem The function $H$ above is only continuous and need not be smooth. So for $0< \lambda < 1$, the closed curve $H(\lambda, \cdot)$ may be pretty much everything (a Peano curve, for example). Does this void the validity of theorem as it is stated above? How can integration be defined over such a pathological object?

The proof of Cauchy's theorem that I have in mind goes as follows. To begin, one observes that for a sufficiently small value of $\lambda_1$, the circuits $\gamma=H(0, \cdot)$ and $H(\lambda_1, \cdot)$ are close toghether; that is, they can be covered by a finite sequence of disks not leaving $\Omega$ like in the following figure:

Since $f$ is locally exact, its integrals over every single disk depend only on the local primitive. Playing a bit with this, one arrives at
$$\int_\gamma f(z)\, dz= \int_{H(\lambda_1, \cdot)} f(z)\, dz.$$
Then one repeats this process, yielding a $\lambda_2$ greater than $\lambda_1$ and such that
$$\int_{H(\lambda_1,\cdot)} f(z)\, dz= \int_{H(\lambda_2, \cdot)} f(z)\, dz.$$
And so on. A compactness argument finally shows that this algorithm ends in a finite number of steps.
Problem is: this proof assumes implicitly that $H(\lambda_1, \cdot), H(\lambda_2, \cdot) \ldots$ are piecewise smooth, to make sense of integrals $$\int_{H(\lambda_j, \cdot)}f(z)\, dz.$$
This, however, does not follow from the definition if $H$ is only assumed to be continuous. Therefore this proof works only for smooth $H$.
Is this regularity condition necessary?

A: If I understand your question correctly, the problem that $H$ may be non-smooth can be solved by approximating with polygonal smooth paths, see for example Rudin's real and complex analysis (3rd edition), thm 10.40 and the remark after it.
As an interesting note, Rudin adds that another way to circumvent this difficulty is to extend the definition of index to closed curves, which is sketched in one of the exercises of the book.

A: As has already been pointed out by Akhil in the comments, any two smooth curves $\gamma_0, \; \gamma_1$ which are continuously homotopic are also smoothly homotopic. The point here is to approximate a continuous homotopy, rather than the curves themselves.
More concretely, given homotopic smooth curves $\gamma_0, \gamma_1: I \to \Omega$,    let $H(s,t): I\times [0,1] \to \Omega$ be a continuous homotopy between $\gamma_0$ and $\gamma_1$.
By the approximation theorem of your choice (mine is due to Whitney), we can find a smooth map $G: I\times[0,1] \to \Omega$, which coincides with $H$ on $I \times \{0\} \cup I \times \{1\}$ (since $H$ is smooth there).
This means that we find a smooth homotopy $G$ between $\gamma_0$ and $\gamma_1$, so we are done in this special case.
Now, if we start out with rectifiable curves rather than smooth ones, we can find two smooth curves $\tilde \gamma_0$ and $\tilde \gamma_1$, which approximate our initial $\gamma_0$ and $\gamma_1$, respectively, and such that the linear homotopy
$$H_\lambda(s,t) := t\gamma_\lambda(s) + (1-t)\tilde \gamma_\lambda(s) \qquad \lambda = 0, 1$$
maps into $\Omega$ (choose a $\epsilon$-neighborhood of the image $\gamma_\lambda(I)$ of $I$ which is contained in $\Omega$ and take $\tilde \gamma_\lambda$ to be contained within this neighborhood).
It is not difficult to see that $H_\lambda$ will then be a "rectifiable" homotopy.
But with $\tilde \gamma_0$, $\tilde \gamma_1$ we are again in the first situation, so there is a smooth homotopy between them.
Now we can build a rectifiable homotopy between $\gamma_0$ and $\gamma_1$ in three steps

*

*Homotop $\gamma_0$ to $\tilde \gamma_0$ by the linear homotopy.

*Use a smooth homotopy between $\tilde \gamma_0$ and $\tilde \gamma_1$

*Go from $\tilde \gamma_1$ to $\gamma_1$ by the straight line homotopy.

Thus proving that all notions of "homotopic" agree.


text:
Q: How can I get the Namespace property value from a ConceptualEntityModel at run-time? I am using C#, Visual Studio 2010 and Entity Framework 4.  I have an assembly that contains multiple entity models.  Project requirements are such that I am not storing any connection information in the app.config.
I have written a method that returns an entity connection string when I supply the name of the model I wish to load.
public static string GetEntityConnectionString(string modelName)
{
    const string providerName = "somedatabaseprovider";
    string metadata = string.Format(@"res://*/{0}.csdl|res://*/{0}.ssdl|res://*/{0}.msl", modelName);

    EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder
    {
        Provider = providerName,
        ProviderConnectionString = GetProviderConnectionString(),
        Metadata = metadata
    };

    return entityBuilder.ToString();
}

I now want to make it a little more bullet-proof by passing the entity model type, instead of a literal string for the model name.  When I am editing the entity model in Visual Studio, the Properties window for MyModel (of type ConceptualEntityModel) contains a property called 'Entity Container Name' that shows MyEntities, and another property called 'Namespace' which shows MyModel.
At design-time, the type that I have access to is MyEntities.  How can I derive the value stored in the 'Namespace' property of the ConceptualEntityModel at run-time?

A: This comes a few months late, but I put this idea up for discussion.
I got the Conceptual Entity Model namespace property from any one of the Entities (tables) in the model, as follows:
string namespaceName = EDMInstance.Entity.EntitySet.ElementType.NamespaceName;

So I have an entity data model called "NITESMOVE_EDM" containing an entity "NM_PATHS", and create the entity metadata locations string as follows:
// create an instance of the Data Model
NITESMOVE_EDM EDMinst = new NITESMOVE_EDM();

// create a connection string builder
System.Data.EntityClient.EntityConnectionStringBuilder entityBuilder = new System.Data.EntityClient.EntityConnectionStringBuilder();

// Set the Metadata location, by querying an Entity in the model
entityBuilder.Metadata = string.Format(@"res://*/{0}.csdl|res://*/{0}.ssdl|res://*/{0}.msl", EDMinst.NM_PATHS.EntitySet.ElementType.NamespaceName);

This could be useful in conjunction with the advice given here: MSDN How to: Build an EntityConnection Connection String

A: Well, if your goal is to make this "bulletproof," this won't work. The string you call modelName is not actually the model name, but the resource name. In your case it coincidently happens to be the same as the model name, but that isn't always true.


text:
Q: How to find $\lim\limits_{n\to +\infty}(3+\frac{1}{a_n})$, where $a_n = 3+\frac{1}{a_{n-1}}$? How to find $\lim\limits_{n\to +\infty}(3+\frac{1}{a_n})$, where $a_n = 3+\frac{1}{a_{n-1}}$?
I tried to find $(a_n-a_{n-1})$ but it didn't help.

A: A fun but too-advanced approach is to use linear algebra. Take $a_0=a$ and write:
$$a_n = \frac{P_n(a)}{Q_n(a)}$$
where $P_n,Q_n$ are polynomials. Then you get that:
$$a_{n+1}=3+\frac{Q_n(a)}{P_n(a)}=\frac{3P_n(a)+Q_n(a)}{P_n(a)}$$
or $P_{n+1}(a)=3P_n(a)+Q_n(a), Q_{n+1}(a)=P_n(a).$
This means that $$\begin{pmatrix}P_{n+1}\\Q_{n+1}\end{pmatrix}=\begin{pmatrix}3&1\\1&0\end{pmatrix}^n\begin{pmatrix}a\\1\end{pmatrix}$$
Now, the matrix has eigenvalues $\lambda_1,\lambda_2=\frac{3\pm\sqrt{13}}2$ with eigenvectors $v_i=\begin{pmatrix}\lambda_i\\1\end{pmatrix}$.
If $a=\lambda_2$ then the limit is $\lambda_2$.
If $a\neq \lambda_2$, then, since $|\lambda_2|<1$, the value will converge to $\lambda_1$, assuming $P_n(a)\neq 0$ for all $n$.
To figure out if $P_n$ is ever zero, we write:
$$\begin{pmatrix}a\\1\end{pmatrix}=b_1v_1+b_2v_2$$
and solve for scalars $b_1,b_2$. We know that $b_1+b_2=1$ and $b_1\lambda_1+b_2\lambda_2=a.$
Then $a_n=0$ iff $b_1\lambda_1^n+b_2\lambda_2^n=0$ or $b_1\lambda_1^{2n}=(-1)^{n+1}b_2.$
Since $a\neq \lambda_2$, we know $b_1\neq 0$, you want:
$$2n=\log_{\lambda_1}\left((-1)^{n+1}\frac{b_2}{b_1}\right)$$
That means you want $\left|\frac{b_2}{b_1}\right|$ to be an even power of $\lambda_1$, and certain sign conditions.

Alternatively, since $Q_{n+1}=P_n$ you get $P_{n+1}=3P_n+P_{n-1}$ and you can use a linear recurrence to show that $P_{n}=c_1\lambda_1^n+c_2\lambda_2^n$ with $P_0=a, P_{1}=3a+1.$ Then, for $n>0$ you have:
$$a_n=\frac{P_n}{Q_n}=\frac{c_1\lambda_1^{n}+c_2\lambda_2^n}{c_1\lambda_1^{n-1}+c_2\lambda_2^{n-1}}=\frac{c_1\lambda_1+(-1)^{n-1}c_2\lambda_2^{2n-1}}{c_1+(-1)^nc_2\lambda_2^{2n-2}}$$
Since $|\lambda_2|<1$ this converges to $\lambda_1$ if $c_1\neq 0$. If $c_1=0$ the the limit is $\lambda_2.$
Then again, we deal with the question of for what values of $a$ do we get some $a_n=0$.
Also, $$a_n-\lambda_1 = c_2\frac{c\lambda_2^n-\lambda_1\lambda_2^{n-1}}{P_{n-1}}=c_2\lambda_2^{n-2}\frac{\lambda_2^2+1}{P_{n-1}}=c_2\lambda_2^{n-2}\frac{3\lambda_2+2}{P_{n-1}}$$
Now, $$\frac{\lambda_2^{n-2}}{P_{n-1}}=\frac{(-1)^{n-2}\lambda_1}{c_1\lambda_1^{2n-2}+(-1)^{n-1}c_2}$$
So you get: $$a_n-\lambda_1 = c_2\frac{(-1)^{n-2}(2\lambda_1-3)}{c_1\lambda_1^{2n-2}+(-1)^{n-1}c_2}$$
showing, if $c_1\neq 0$ thatn $a_n-\lambda_1 = O\left(\lambda_1^{-2n}\right)$

A: Here is a method which analyses the error term - which seems to me to be like what you are trying to do with $a_{n+1}-a_n$. But this uses the equation you have been given in a different way. I've put enough to give you a start. Other methods may be more efficient, so this is more for interest.
Suppose that $a^2-3a-1=0$ and set $a_n=a+e_n$ then $$a_{n+1}=a+e_{n+1}=3+\frac 1{a_n}=\frac{3a+3e_n+1}{a+e_n}$$ so that $$a^2+ae_n+ae_{n+1}+e_ne_{n+1}=3a+3e_n+1$$ whence $$(a+e_n)e_{n+1}=(3-a)e_n$$ and $$e_{n+1}=\frac {(3-a)}{(a+e_n)}e_n$$
Now note what happens when you take the root which is greater than $3$ and $e_n$ is small enough in absolute value. - you should be able to prove that in this case the error term tends to zero, and hence establish the limit.

A: If the limit exists, it is a solution of the equation
$$x=3+\frac1x$$
Nevertheless, the existence of the limit must be proved, and it can depend on the value of $a_1$ which you have not specified.

A: Let's show that for $\forall a_0>0$, the sequence is converging ...
Proposition 1. $3< a_n < 4$, for $\forall n \geq 2$.
If $a_0 > 0 \Rightarrow \frac{1}{a_0}>0 \Rightarrow \color{red}{a_1}=3+\frac{1}{a_0}\color{red}{>3}$. So $a_1 >0 \Rightarrow \frac{1}{a_1}>0 \Rightarrow \color{red}{a_2}=3+\frac{1}{a_1}\color{red}{>3}$ and, by induction
$$\color{red}{a_n > 3}, \forall n >0 \tag{1}$$
Also, from $(1)$ $a_n > 3 \Rightarrow 0< \frac{1}{a_n} < \frac{1}{3} < 1 \Rightarrow \color{red}{a_{n+1}}=3+\frac{1}{a_n}\color{red}{<4}$. But $(1)$ is true for $n > 0$, so (by induction again)
$$\color{red}{a_n < 4}, \forall n>1 \tag{2}$$
Altogether $$3< a_n < 4,\forall n \geq 2$$

Now, let's look at the function
$$f(x)=3+\frac{1}{x}$$
which is an important one, because $a_{n+1}=f(a_n)$.
Proposition 2. if $3\leq x \leq 4 \Rightarrow 3 \leq f(x) \leq 4$
$3\leq x \leq 4 \Rightarrow \frac{1}{3} \geq \frac{1}{x} \geq \frac{1}{4} \Rightarrow 4 > 3+ \frac{1}{3} \geq 3+\frac{1}{x} \geq 3+\frac{1}{3} > 3$ which is $3 < f(x) < 4$

Proposition 3 Function $f: [3,4] \rightarrow [3,4]$ is a contraction mapping.
From MVT
$$|f(x)-f(y)|= |f'(\varepsilon)| |x-y|=\left|\frac{1}{\varepsilon^2}\right| |x-y|$$
where $\varepsilon \in (x,y) \subset [3,4]$, thus
$$|f(x)-f(y)| \leq \frac{1}{9} |x-y|$$

Altogether, we can ignore the first 2 elements (Proposition 1) of the sequence, when the initial element is greater than $0$, they don't affect the convergence of the sequence. And according to the Banach fixed-point theorem, the sequence has a limit. More reading on this subject here


text:
Q: dns problem on my mac? I have a subversion installation running on a remote server which I manage myself. It worked just fine for a few weeks already and there were no changes in DNS or subversion configuration, but since yesterday I'm unable to commit/update anything. The error message I'm getting is:

Olgas-MacBook-Pro:ingenix olgary$ svn
  update
      svn: OPTIONS of 'http://mysvnhost/myproject/trunk':
  Could not resolve hostname
  `svn.logicaldesign.ru': Host not found
  (http://mysvnhost)

When I try to ping the host I get:

Olgas-MacBook-Pro:ingenix olgary$ ping
  mysvnhost ping: cannot resolve
  mysvnhost: Unknown host

The situation is that from OTHER computers everything is working just fine, no problems at all. Seems the problem is on my end... I've tried to reboot, execute "dscacheutil -flushcache" command, but nothing helped. Have no idea what else I can do. Any help will be greatly appreciated... Thank you in advance!

A: Is it possible that you a hosts file referencing an old ip address?
Here's how to edit the hosts file.


text:
Q: Android application doesn't close I've written an application for Android, but it doesn't close and it also starts automatically with the system. I don't know why, but it can't be closed, even through the Task Manager. So I would like to know why it doesn't close.

A: I'm sure you have read how Android apps aren't really supposed to close. That aside, I also needed my app to terminate when no longer visible. First I tried
System.exit();

That worked just fine but it isn't the proper way to do it, the best way is to call
finish();

I'm sorry if you had already tried/were aware of those solutions; it wasn't clear from your question.


text:
Q: Convert column headers into index / row values python I have a pandas dataframe with the following format:
Time        07:45:00    08:00:00    08:30:00    08:45:00    09:05:00    09:30:00    10:00:00    11:30:00    Total
2020-03-09  NaN         NaN         NaN         NaN         400.0       NaN         450.0       NaN     NaN
2020-03-10  NaN         NaN         NaN         NaN         350.0       NaN         NaN         NaN     10

I want to adjust the timestamps into the rows (as indexes or just as values), without the total column, how can I convert it, that it looks like:
Time          Timestamp   Value  Total
2020-03-09    07:45:00    NaN    NaN
....
2020-03-09    09:05:00    400.0  NaN
...
20-03-10     11:30:00     NaN    10


text:
Q: Finding an angle in a circle with triangles good day! Excuse me, I am new to finding angles using a circle, and I don't know how to find X using trigonometric functions and everything else about triangle angles. What is the 100° talking about? Or, how can one proof that BE is parallel to AC? (Maybe it isn't!) What I know is the angle of ACD is going to be 78. Any help, guidance, approach would be warmly welcomed.

A: The $100º$ refers to $\angle BOA$. Whenever you see an angle on the arc of a circle, this means that the two points are separated by that angle: in this case, $A$ and $B$ are separated by an angle of $100º$.
If $\angle BFC + \angle ACF = 180º$, then $BF$ is parallel to $AC$ (these would be co-interior angles, if you're curious). Therefore, we have to find $\angle BFC$ and $\angle ACF$ somehow.
It is often helpful to draw an extra line or two: for this problem, connect $B$ and $C$ together. Now, can you find:

*

*$\angle DCA$?

*$\angle BCA$ using the inscribed angle theorem (with angles $2 \theta$ and $\theta$)?

*$\angle BCF$ using the alternate angle theorem for circles?

*$\angle CEB$ using the sum of opposite angles in a cyclic quadrilateral?
and these facts will lead you to find the two angles mentioned above, and hence whether $BF$ is parallel to $AC$.

A: Hint:
Work with multiple isosceles triangles with one of the vertices being at the center of the circle. Start with $\triangle AOB$ and we know $\angle AOB = 100^0$, can you find $\angle OAB$? Then can you go on to find $\angle OCA$ and $\angle OCE$?
Now using the fact that $FC$ is tangent to the circle, you should be able to find $\angle FCE$.
Then can you find $\angle FEC$ given $ABEC$ is a cyclic quadrilateral?
Now you know two angles of $\triangle FCE$. So you know $\angle X$.


text:
Q: Help: Making a device to measure the amount of liquid an a container I want to make a device that would measure the amount of liquid in a container. Can anyone give me an idea on it? I am planning to use a pressure sensor, the required range would be from 0 pascal to 2 pascal. Which pressure sensor would be best suited for this purpose?

A: What kind of a container are we talking about here?  What kind of liquid?  Is it enclosed?  Under pressure?  Corrosive?
My vote would be for some sort of proximity sensor at the top of the container that measures the distance to the surface of the liquid.  This means the sensor should not come in contact with the liquid.  Depending on the liquid, it might be possible to use an optical sensor such as a Sharp analog distance sensor, in which case the sensor can peer into the container through a window.  This may not work if the liquid is clear or absorbs infrared light.  Alternatively, you can use an ultrasonic range finder to measure the distance to the surface.
A capacitive sensor of some sort might also be a good option.  String an insulated wire from the top to the bottom of the tank and measure the capacitance.  Different liquid levels will change the capacitance on the wire.  You can also try this with a pair of wires and measure the capacitance between the two.  There are capacitance to digital chips that you can buy or you can use the capacitance to form a free running oscillator and then measure the frequency.

A: Electronic scale would be my choice. Weight of liquid etc.. Use a small strain gauge like the type used in off the shelf kitchen or bathroom scales.
Alternatively find some scales with an output signal or data signal. They must be around.
Pressure sensors are good in that they will work ok but may be affected by barometric pressure. Measuring weight has a long history of accuracy but if you are trying to determine volume of fluid and the fluid is unknown then weight and pressure are no good so maybe go for a float sensor like in car fuel tanks.


text:
Q: System.out.print(Arrays.toString()); is not working for array of OBJECTS I keep searching on how to fix this, but I cannot find something that applies/works for my problem. I am trying to print out an array of Circles. All I know is that I have to overwrite the toString() method.
I keep getting the following output:

[Heather$Circle@2a139a55, Heather$Circle@15db9742,
  Heather$Circle@6d06d69c, Heather$Circle@7852e922]

import java.util.*;
public class heather {
    public static void main(String[] args) {
        heather c = new heather();

        Circle c1 = c.new Circle(4,6,4);
        Circle c2 = c.new Circle(4,5,4);
        Circle c3 = c.new Circle(5,4,4);
        Circle c4 = c.new Circle(5,4,3);

        Circle[] a = {c1, c2, c3, c4};

        Arrays.sort(a);
        System.out.print(Arrays.toString(a));
    }

    public class Point {
        private int x;
        private int y;

        public Point(int x, int y){
            this.x = x; this.y = y;
        }

        public int getX(){
            return this.x;
        }

        public int getY(){
            return this.y;
        }
    }

    public class Circle extends Point implements Comparable<Circle> {
        private double radius;
        private Point point;

        public Circle(int x, int y, double radius) {
            super(x, y); this.radius = radius;
        }

        public double getRadius() {
            return this.radius;
        }

        public Point getPoint() {
            return this.point;
        }

        public int area() {
            return (int) (Math.PI*radius*radius);
        }

        public int compareTo(Circle other){
            if(this.area()>other.area()) {
                return 1;
            }

            if(this.area()<other.area()) {
                return -1;
            } else if(this.getX()>other.getX()) {
                return 1;
            }

            if (this.getX()<other.getX()){
                return -1;
            } else if(this.getY()<other.getY()) {
                return -1;
            } else {
                return 1;
            }
        }
    }
    public String toString(){

    }
}

A: This part of your code...
    }
public String toString(){

}

closes the Circle class before it includes your toString() method. Therefore, you should rewrite it like...
    public String toString(){

    }
}

and then just fill in whatever you want in the toString() method. Maybe something like...
return "Circle of radius " + radius;

You may find that these issues are more easily detected if your actively organize your code for readability. I've cleaned the code you posted for reference...
package Shift;

import java.util.*;

public class Shift {

    public static void main(String[] args) {

        Shift c = new Shift();

        Circle c1 = c.new Circle(4,6,4);
        Circle c2 = c.new Circle(4,5,4);
        Circle c3 = c.new Circle(5,4,4);
        Circle c4 = c.new Circle(5,4,3);

        Circle[] a = {c1, c2, c3, c4};

        Arrays.sort(a);
        System.out.print(a[0]);
    }

public class Point{

    private int x;
    private int y;

    public Point(int x, int y){
        this.x = x; this.y = y;
    }

    public int getX(){
        return this.x;
    }

    public int getY(){
        return this.y;
    }
}

public class Circle extends Point implements Comparable<Circle>{

    private double radius;
    private Point point;

    public Circle(int x, int y, double radius) {
            super(x, y);
            this.radius = radius;
    }

    public double getRadius(){
        return this.radius;
    }

    public Point getPoint(){
        return this.point;
    }

    public int area(){
        return (int) (Math.PI*radius*radius);
    }

    public int compareTo(Circle other){
        if(this.area()>other.area())
            return 1;

        if(this.area()<other.area())
            return -1;
        else if(this.getX()>other.getX())
                return 1;

        if (this.getX()<other.getX())
                return -1;
        else if(this.getY()<other.getY())
            return -1;
        else
            return 1;
    }

    @Override
    public String toString(){
        return "Circle of radius " + radius;
    }
}

}


text:
Q: How portlet producers initiate refresh/push to consumers on demand (I'm using Jdeveloper 11.1.1.6 ADF-JSF) I am new to the oracle Webcenter portlets:
My requirement is my Portlet Producer serves N number of consumers . I do need to refresh or push content to those consumers whenever changes occur at my producer .
My questions are :

*

*How to keep track of all active consumers for my portlet-producer ? what technique to use ?

*How producer could communicate with consumer and refresh or push the content?

I was able to refresh the consumer(Consumer side request initiated) by setting time interval in javascript(Jquery) and making ajax request to the producer. But i do like to know how can the refresh or push initiated from my producer?
I'am a beginner in Oracle webcenter so guide me regarding this in detail.

A: You can use the Active Data Service for server side push using ADF components, you can find the docs here.
For your first question you could keep track of the user's sessions by using some counter in the application scope.


text:
Q: Get beans that where created dynamically Im using BeanDefinitionRegistryPostProcessor to create beans at runtime based on entries in a database. How would I go about it getting to these beans later in the program?
I have the id's of the beans and have tried using the getBeans method but that returns a beanDefinition instead of the object.
I am trying to use a factory for instantiation passing in the id's of the beans.


text:
Q: MySQL UNION Statement to select two columns having a specific value and select two other columns having another specific value I have searched for this question on S/O but couldn't find anything.
What I'm trying to do is two select two rows containing a value plus two rows containing the other value.
Like:
Row1: val:1
Row1: val:1
Row2: val:20
Row3: val:20

What I though of was this:
SELECT * FROM breakfast WHERE valueforunit = '1' LIMIT 2
UNION ALL
SELECT * FROM breakfast WHERE valueforunit = '20' LIMIT 2

But an exception is thrown which says

LIMIT clause should come after UNION ALL not before

but I want it to exactly return two rows with the first value and two rows with the second value.
And I want the selection to be random too. Like:
SELECT * FROM breakfast WHERE valueforunit = '1' ORDER BY RAND() LIMIT 2
UNION ALL
SELECT * FROM breakfast WHERE valueforunit = '20'ORDER BY RAND() LIMIT 2

Any thoughts?

A: Wraps the two portions of the UNION in parentheses:
(SELECT * FROM breakfast WHERE valueforunit = '1' ORDER BY RAND() LIMIT 2)
UNION ALL
(SELECT * FROM breakfast WHERE valueforunit = '20' ORDER BY RAND() LIMIT 2)


text:
Q: what does this integer mean? hi people i am new at php and wondering what does int(4) mean in creating this table. thanks for helping.
CREATE TABLE mytable(
name VARCHAR (50),
age INT(4),
email VARCHAR (50)
);

A: If you are using MySQL, it is the display width of the integer.  You can find this sort of information in the MySQL user manual:

For example, INT(4) specifies an INT with a display width of four digits.

A: The code you have posted is no PHP, but a SQL statement for creating a database table called mytable with three columns - name, age and email. The statement also has the date types of the different columns, so the database system can know how to store and retrieve them.
Int is a data type in the database - an integer (whole number).
What it means depends on the database you use - in SQL Server the 4 specifies the field precision. However, this will always be the size of an int in SQL Server. It can holdvalues between -2,147,483,648 and 2,147,483,647.
If MySQL, it means the display width of the field.

A: It depends entirely on your RDBMS: there is no standard meaning. Most will simply ignore it, or treat it as a display hint (like MySQL).


text:
Q: Postfix mailbox_transport and mailbox_command I have Postfix set up in main.cf to use mailbox_transport=lmtp:unix:private/dovecot-lmtp as LDA, which works fine.
I also need to enable mailbox_command in order to pass internal sanity checks as Virtualmin expects in its configuration check to find a valid mailbox_command parameter.
The Postfix documentation says

The precedence of local(8) delivery features from high to low is:
  aliases, .forward files, mailbox_transport_maps, mailbox_transport,
  mailbox_command_maps, mailbox_command, home_mailbox,
  mail_spool_directory, fallback_transport_maps, fallback_transport and
  luser_relay.

For me this sounds as it would be of no harm to uncomment the mailbox_command line in order to satisfy the internal sanity checks while keeping the LMTP functionality in full working order.
Are there any known side effects?


text:
Q: Scroll one line HTML I am trying to create a div with a scrollbar and would like to be able to scroll vertically one line at a time. Currently it skips some lines. If i have 5 lines, it will skip every other line and show the next.
Please see my current code at the following link. When you scroll, you will notice it skips one line. Need to be able to view all lines. One at a time.
https://jsfiddle.net/vishism/fx8r15up/
My current CSS
#notesDiv {
line-height: 20px;
height: 23px;
overflow-y: scroll;
border: 1px solid #D8E8EC;
padding-left: 9px;
}

I have tried a few things and could not get it to work. Any assistance will be appreciated.
Thanks.


text:
Q: List Laravel table names without knowing database name This code works fine for a specific MySQL database whose name is literally 'db_name':
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
$tables = DB::select('SHOW TABLES');
foreach($tables as $table) {
  echo $table->Tables_in_impact . '
';
}

But I don't know the database name at the time I write the code. I can pick up the database name from Laravel's .env file as env('DB_DATABASE') but I can't figure out how to work that expression into the code above.
I tried many different approaches using eval() but couldn't make it work. Is there a better approach than eval()?

A: I finally figured it out. This works:
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
$key = 'Tables_in_' . env('DB_DATABASE') ;
$tables = DB::select('SHOW TABLES');
foreach($tables as $table) {
    echo $table->$key . '
';
}


text:
Q: Ubuntu - mount image file with r/w permission Host: Ubuntu 15.04
With Disk Image Mounter, I can mount the test.img and three directories popped up.

*

*system-a

*system-b

*writable

As I've searched around, I can not edit the directories since those are read-only.
The possible solution I found so far is to copy these directories to another new place and generate a new image file.
However, since the image file contains these three directories, how can I do it?
=============post update=============
mount: wrong fs type, bad option, bad superblock on /dev/loop1,
       missing codepage or helper program, or other error

       In some cases useful info is found in syslog - try
       dmesg | tail or so.

=====================================
Device                Start     End Sectors  Size Type
test_custom2.img1    8192   16383    8192    4M BIOS boot
test_custom2.img2   16384  147455  131072   64M EFI System
test_custom2.img3  147456 2244607 2097152    1G Linux filesystem
test_custom2.img4 2244608 4341759 2097152    1G Linux filesystem
test_custom2.img5 4341760 7614463 3272704  1.6G Linux filesystem

A: You need to make sure that your current user directory has read and write access to your operation
sudo mkdir -p /tmp/test && sudo mount -o loop,rw,sync image.img /tmp/test

A: The problem is that there are multiple partitions in your image. A plain old mount looks for filesystem information at offset 0, which in your case apparently points to some bios boot information, but not to the desired ext4 fs. You should succeed by creating the loopback-device with an offset to the desired partition.
This link may help you out.

A: Here's the full process, based on the answer here:
Your .img file is not an image of a partition, but of a whole disk. That means it starts with a bootloader and a partition table. You have to detect the offset of the partition and mount it specifically. Sadly I've never been able to find a Linux tool that automates that. So you have to do math, but it's easy. Here's the process:
fdisk -l raspberry_pi.img

Which gives the output below. Note the sector size in bytes (512 in this case; see line 2 below) and the Start sector of the partition (94208 for the Linux partition; see the last line below).
Disk raspberry_pi.img: 7.3 GiB, 7826571264 bytes, 15286272 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0xbeb1a7ff

Device          Boot Start      End  Sectors  Size Id Type
raspberry_pi.img1       8192    93813    85622 41.8M  c W95 FAT32 (LBA)
raspberry_pi.img2      94208 15069183 14974976  7.1G 83 Linux

Now, manually multiply the start sector * sector size to get the offset bytes that the mount command needs. In this case, 94208 * 512 = 48234496
sudo mkdir /media/sdcard
sudo mount -o loop,rw,sync,offset=48234496 printer_v5.img /media/sdcard

Now, the image's Linux partition is mounted at /media/sdcard and the root user can edit its files.
Finally, when you're finished:
sudo umount /media/sdcard

A: binwalk might be the tool to try in order to get the job done in this case. Many, many options but in it's simplest form:
#install binwalk
git clone https://github.com/ReFirmLabs/binwalk.git
cd binwalk
sudo python setup.py install
#cd to image folder
cd <path to image file>
#show info
binwalk yourimage.img
#auto extract all
binwalk -e yourimage.img


text:
Q: Creating JSON and editing a complex query (oracle 11g) I have 4 different tables:

table_price_product (contains information related to the products and
  their price)
table_price_list (contains the information related to the price list)
prices_per_client (contains the information related to the prices for
  the different clients given a specific product)
clients (contains the information related to the clients)

This is my SQL FIDDLE: LINK
I got this:
CUSTOMER_NUMBER  |  CUSTOMER_CLASS_CODE|    PRICE
(null)           |           A         |    29223
(null)           |           B         |    33223
112121           |           E         |    40340
119435           |           E         |    40340

Now, i want to obtain in a single query all the data related to the products and the clients, replace A,B,C etc with CLASS A, CLASS B, CLASS C respectively but if the customer_class_code is = 'E' i want to obtain the name from table clients AND finally, convert everything and get JSONs for every product. Take a look at this, somehow i would need to add column "PRICES_FOR_CLIENTS" and "groups" because i need those columns to generate the JSON.
SKU     |PRICE|PRICES_FOR_CLIENTS|groups|CLASS A|CLASS B|WALMART|SUPERMARKET
99342435|9999 |                  |      |29223  |33223  |40340  |40340

I would like to generate a JSON with that information:

{"sku":"99342435","PRICE":"9999",PRICES_FOR_CLIENTS:[{"group":"CLASS
  A", "PRICE":"29223"},{"group":"CLASS B",
  "PRICE":"33223"},{"group":"WALMART","PRICE":"40340"},{"group":"SUPERMARKET",
  "PRICE":"40340"}]};

Can you help me?
EDIT:
<Item SKU="99342435" Price="9999">
    <PRICES_FOR_CLIENTS>
        <CLIENT_PRICE>
            <Client>WALMART</Client>
            <Price>40340</Price>
            <Site>USSITE</Site>
        </CLIENT_PRICE>
        <CLIENT_PRICE>
            <Client>SUPERMARKET</Client>
            <Price>48343</Price>
            <Site>USSITE</Site>
        </CLIENT_PRICE>
        <CLIENT_PRICE>
            <Client>B</Client>
            <Price>33223</Price>
            <Site>USSITE</Site>
        </CLIENT_PRICE>
        <CLIENT_PRICE>
            <Client>A</Client>
            <Price>29223</Price>
            <Site>USSITE</Site>
        </CLIENT_PRICE>
    </PRICES_FOR_CLIENTS>
</Item>

A: I think you can replace most of your code with the following query.  You may need to adjust the IN clause, which is a pain if you are changing the customer list a lot.  But this replicates your results:
SELECT *
FROM (SELECT DECODE(ppc.customer_class_code, 'E', c.description, ppc.customer_class_code) AS IDENTIFIER, tpp.item_code, tpp.price AS ITEM_PRICE, ppc.price
      FROM table_price_list tpl
      INNER JOIN table_price_product tpp ON tpp.list_header_id = tpl.list_header_id AND tpp.request_id = tpl.request_id
      INNER JOIN prices_per_client ppc ON tpp.item_code = ppc.item_code
      LEFT JOIN clients c ON ppc.customer_number = c.account_number
      WHERE SYSDATE BETWEEN NVL(tpp.start_date_active, SYSDATE) AND NVL(tpp.end_date_active, SYSDATE+1))
PIVOT (AVG(PRICE) FOR IDENTIFIER IN ('A' AS CLASS_A , 'B' AS CLASS_B, 'SUPERMARKET' AS SUPERMARKET, 'WALMART' AS WALMART));

Here is an update fiddle.
As for the JSON output, it would be much easier if you were on a later version as it is now part of the core functionality.
EDIT: Adding XML Functionality per Comments
You could check out this query:
SELECT XMLSERIALIZE(CONTENT
                    XMLELEMENT("Item",
                               XMLATTRIBUTES(sub.item_code AS "SKU", sub.item_price AS "Price"),
                               XMLELEMENT("PRICES_FOR_CLIENTS",
                                          XMLAGG(XMLELEMENT("CLIENT_PRICE",
                                                            XMLFOREST(sub.identifier AS "Client", sub.price AS "Price"))))) AS CLOB INDENT)
FROM (SELECT DECODE(ppc.customer_class_code, 'E', c.description, ppc.customer_class_code) AS IDENTIFIER, tpp.item_code, tpp.price AS ITEM_PRICE, avg(ppc.price) AS PRICE
      FROM table_price_list tpl
      INNER JOIN table_price_product tpp ON tpp.list_header_id = tpl.list_header_id AND tpp.request_id = tpl.request_id
      INNER JOIN prices_per_client ppc ON tpp.item_code = ppc.item_code
      LEFT JOIN clients c ON ppc.customer_number = c.account_number
      WHERE SYSDATE BETWEEN NVL(tpp.start_date_active, SYSDATE) AND NVL(tpp.end_date_active, SYSDATE+1)
      GROUP BY DECODE(ppc.customer_class_code, 'E', c.description, ppc.customer_class_code), tpp.item_code, tpp.price) sub
WHERE sub.identifier IS NOT NULL
GROUP BY sub.item_code, sub.item_price;

Here is an updated fiddle with that query (Link).
Which produces the following output:
<Item SKU="99342435" Price="9999">
    <PRICES_FOR_CLIENTS>
        <CLIENT_PRICE>
            <Client>WALMART</Client>
            <Price>40340</Price>
        </CLIENT_PRICE>
        <CLIENT_PRICE>
            <Client>SUPERMARKET</Client>
            <Price>48343</Price>
        </CLIENT_PRICE>
        <CLIENT_PRICE>
            <Client>B</Client>
            <Price>33223</Price>
        </CLIENT_PRICE>
        <CLIENT_PRICE>
            <Client>A</Client>
            <Price>29223</Price>
        </CLIENT_PRICE>
    </PRICES_FOR_CLIENTS>
</Item>

Edit 2: Adding JSON via String Concatination
The following would output JSON via direct string concatination:
SELECT '{"sku":"'||sub.item_code||'","PRICE":"'||sub.item_price||'",PRICES_FOR_CLIENTS:['||listagg('{"group":"'||sub.identifier||'","PRICE":"'||sub.price||'"}',',') WITHIN GROUP (ORDER BY sub.identifier)||']};' AS JSON
FROM (SELECT DECODE(ppc.customer_class_code, 'E', c.description, ppc.customer_class_code) AS IDENTIFIER, tpp.item_code, replace(tpp.price, ',', '.') AS ITEM_PRICE, REPLACE(avg(ppc.price), ',', '.') AS PRICE,
      tpl.request_id, max(tpl.request_id) over (partition by tpp.item_code) as max_request
      FROM table_price_list tpl
      INNER JOIN table_price_product tpp ON tpp.list_header_id = tpl.list_header_id AND tpp.request_id = tpl.request_id
      INNER JOIN prices_per_client ppc ON tpp.item_code = ppc.item_code
      LEFT JOIN clients c ON ppc.customer_number = c.account_number
      WHERE SYSDATE BETWEEN NVL(tpp.start_date_active, SYSDATE) AND NVL(tpp.end_date_active, SYSDATE+1)
      GROUP BY DECODE(ppc.customer_class_code, 'E', c.description, ppc.customer_class_code), tpp.item_code, tpp.price, tpl.request_id) sub
WHERE sub.identifier IS NOT NULL
and sub.request_id = sub.max_request
GROUP BY sub.item_code, sub.item_price;

And an updated fiddle with this query (Link)
Edit 3: Added Replace
**Edit 4: Added analytical function **


text:
Q: Find the difference between total number of two different queries SQL I have got a table Vocab and i want to find number of total rows and number of duplicates,this is the code i tried
(SELECT COUNT(*) FROM Vocab) - (SELECT COUNT(*) FROM Vocab GROUP BY Word)
But it returned me an error Unexpected token. (near "-" at position 29),How can i achieve my goal?

A: I think you want count(distinct) and some arithmetic:
select count(*) as total_words,
       count(distinct word) as total_distinct_words,
       (count(*) - count(distinct word)) as must_be_duplicated
from Vocab;


text:
Q: Etoolbox's \patchcmd can't find search pattern due to hyperref package I use the report class and I have learned from other questions on this site (like Remove spacing between per-chapter figures in LoF) how I can adjust the spacing between per-chapter figures in the LoF. I would like to change the traditional
\addtocontents{lof}{\protect\addvspace{10\p@}}
in the report.cls file to
\addtocontents{lof}{\protect\addvspace{15\p@}} by using this patch :
\makeatletter
\patchcmd{\@chapter}%
  {\addtocontents{lof}{\protect\addvspace{10\p@}}}% <search>
  {\addtocontents{lof}{\protect\addvspace{15\p@}}}% <replace>
  {}{}% <success><failure>
\makeatother

However, by issuing \tracingpatches I can see the following :
[debug] analyzing '\@chapter'
[debug] ++ control sequence is defined
[debug] ++ control sequence is a macro
[debug] ++ macro can be retokenized cleanly
[debug] -- search pattern not found in replacement text

Am I doing something wrong ? I don't understand why \patchcmd can't find the specified code. For the record, there are 3 other patches in my document (not modifying \@chapter) and they all work well.
Edit: While preparing a MWE, I realized that the package hyperref is the culprit, since removing it solves the problem.
\documentclass[12pt,twoside,openright]{report}

\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[french]{babel}
\usepackage{lmodern}
\usepackage{microtype}

\usepackage{etoolbox}

\usepackage[pdftex,colorlinks,linkcolor=blue,citecolor=red]{hyperref}

%----------------------- Patch -----------------------
\tracingpatches
\makeatletter
\patchcmd{\@chapter}%
  {\addtocontents{lof}{\protect\addvspace{10\p@}}}% <search>
  {\addtocontents{lof}{\protect\addvspace{15\p@}}}% <replace>
  {}{}% <success><failure>
\makeatother
%-----------------------------------------------------

\begin{document}
\listoffigures
\chapter{A chapter}
\begin{figure}\caption{A figure}\end{figure}
\begin{figure}\caption{A figure}\end{figure}
\chapter{A chapter}
\begin{figure}\caption{A figure}\end{figure}
\begin{figure}\caption{A figure}\end{figure}
\appendix
\chapter{A chapter}
\addtocontents{lof}{\protect\addvspace{10pt}}%
\begin{figure}\caption{A figure}\end{figure}
\begin{figure}\caption{A figure}\end{figure}
\end{document}

Is there a way to fix this ? I need to keep loading the hyperref package.

A: hyperref has to define a great many internal commands to do its thing.
In this case the original definition of \@chapter is saved to \Hy@org@chapter by hyperref, \@chapter is then redefined to do some linking and then calls \Hy@org@chapter.
So the solution here is to patch \Hy@org@chapter instead of \@chapter when hyperref is loaded.
\documentclass[12pt,twoside,openright]{report}

\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[french]{babel}
\usepackage{lmodern}
\usepackage{microtype}

\usepackage{etoolbox}

\usepackage[pdftex,colorlinks,linkcolor=blue,citecolor=red]{hyperref}

%----------------------- Patch -----------------------
\tracingpatches
\makeatletter
\patchcmd{\Hy@org@chapter}%
  {\addtocontents{lof}{\protect\addvspace{10\p@}}}% <search>
  {\addtocontents{lof}{\protect\addvspace{15\p@}}}% <replace>
  {}{}% <success><failure>
\makeatother
%-----------------------------------------------------

\begin{document}
\listoffigures
\chapter{A chapter}
\begin{figure}\caption{A figure}\end{figure}
\begin{figure}\caption{A figure}\end{figure}
\chapter{A chapter}
\begin{figure}\caption{A figure}\end{figure}
\begin{figure}\caption{A figure}\end{figure}
\appendix
\chapter{A chapter}
\addtocontents{lof}{\protect\addvspace{10pt}}%
\begin{figure}\caption{A figure}\end{figure}
\begin{figure}\caption{A figure}\end{figure}
\end{document}

gives

and
[debug] tracing \patchcmd on input line 16
[debug] analyzing '\Hy@org@chapter'
[debug] ++ control sequence is defined
[debug] ++ control sequence is a macro
[debug] ++ macro can be retokenized cleanly
[debug] ++ search pattern found in replacement text
[debug] ++ patching possible
[debug] == retokenizing macro now

Alternatively, you can try to get your patch in before hyperref applies its redefinitions.
\documentclass[12pt,twoside,openright]{report}

\usepackage{etoolbox}

%----------------------- Patch -----------------------
\tracingpatches
\makeatletter
\patchcmd{\@chapter}%
  {\addtocontents{lof}{\protect\addvspace{10\p@}}}% <search>
  {\addtocontents{lof}{\protect\addvspace{15\p@}}}% <replace>
  {}{}% <success><failure>
\makeatother
%-----------------------------------------------------

\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[french]{babel}
\usepackage{lmodern}
\usepackage{microtype}

\usepackage[pdftex,colorlinks,linkcolor=blue,citecolor=red]{hyperref}

\begin{document}
\listoffigures
\chapter{A chapter}
\begin{figure}\caption{A figure}\end{figure}
\begin{figure}\caption{A figure}\end{figure}
\chapter{A chapter}
\begin{figure}\caption{A figure}\end{figure}
\begin{figure}\caption{A figure}\end{figure}
\appendix
\chapter{A chapter}
\addtocontents{lof}{\protect\addvspace{10pt}}%
\begin{figure}\caption{A figure}\end{figure}
\begin{figure}\caption{A figure}\end{figure}
\end{document}

Thanks to David Carlisle for suggesting that in the comments.


text:
Q: Ggplot subset data functions and dplyr When doing data analysis, we often use dplyr to modify the dataframe further in specific geoms. This allows us to change the default dataframe of a ggplot later, and have everything still work.
template <- ggplot(db, aes(x=time, y=value)) +
     geom_line(data=function(db){db %>% filter(event=="Bla")}) +
     geom_ribbon(aes(ymin=low, ymax=up))
ggsave( template, "global.png" )
for(i in unique(db$simulation))
     ggsave( template %+% subset(db, simulation==i), paste0(i, ".png")

Is there a nicer/shorter way to specify the filter command, e.g. using some magical .?
EDIT
To clarify some of the comments: By using geom_line(data = db %>% filter(event=="Bla")), the layer would not be updated when I change the default dataframe later using %+%. I am really aiming to use the data argument of geom_* as a function.

A: Upon reading the documentation of %>% better, I have found the solution:

Using the dot-place holder as lhs
      When the dot is used as lhs, the result will be a functional sequence, i.e. a function which applies the entire chain of right-hand sides in turn to its input. See the examples.

Therefore, the nicest way to formulate the above example, incorporating the suggestions from above as well:
db <- diamonds
template <- ggplot(db, aes(x=carat, y=price, color=cut)) +
  geom_point() +
  geom_smooth(data=. %>% filter(color=="J")) +
  labs(caption="Smooths only for J color")
ggsave( template, "global.png" )
db %>% group_by(cut) %>% do(
  ggsave( paste0(.$cut[1], ".png"), plot=template %+% .)
)


text:
Q: Add shape to sphere surface in SceneKit I'd like to be able to add shapes to the surface of a sphere using SceneKit. I started with a simple example where I'm just trying to color a portion of the sphere's surface another color. I'd like this to be an object that can be tapped, selected, etc... so my thought was to add shapes as SCNNodes using custom SCNShape objects for the geometry.
What I have now is a blue square that I'm drawing from a series of points and adding to the scene containing a red sphere. It basically ends up tangent to a point on the sphere, but the real goal is to draw it on the surface. Is there anything in SceneKit that will allow me to do this? Do I need to do some math/geometry to make it the same shape as the sphere or map to a sphere's coordinates? Is what I'm trying to do outside the scope of SceneKit?
If this question is way too broad I'd be glad if anyone could point me towards books or resources to learn what I'm missing. I'm totally new to SceneKit and 3D in general, just having fun playing around with some ideas.
Here's some playground code for what I have now:
import UIKit
import SceneKit
import XCPlayground

class SceneViewController: UIViewController {

    let sceneView = SCNView()

    private lazy var sphere: SCNSphere = {
        let sphere = SCNSphere(radius: 100.0)
        sphere.materials = [self.surfaceMaterial]
        return sphere
    }()

    private lazy var testScene: SCNScene = {
        let scene = SCNScene()
        let sphereNode: SCNNode = SCNNode(geometry: self.sphere)
        sphereNode.addChildNode(self.blueChildNode)

        scene.rootNode.addChildNode(sphereNode)
        //scene.rootNode.addChildNode(self.blueChildNode)
        return scene
    }()

    private lazy var surfaceMaterial: SCNMaterial = {
        let material = SCNMaterial()
        material.diffuse.contents = UIColor.redColor()
        material.specular.contents = UIColor(white: 0.6, alpha: 1.0)
        material.shininess = 0.3
        return material
    }()

    private lazy var blueChildNode: SCNNode = {
        let node: SCNNode = SCNNode(geometry: self.blueGeometry)
        node.position = SCNVector3(0, 0, 100)
        return node
    }()

    private lazy var blueGeometry: SCNShape = {
        let points: [CGPoint] = [
            CGPointMake(0, 0),
            CGPointMake(50, 0),
            CGPointMake(50, 50),
            CGPointMake(0, 50),
            CGPointMake(0, 0)]

        var pathRef: CGMutablePathRef = CGPathCreateMutable()
        CGPathAddLines(pathRef, nil, points, points.count)

        let bezierPath: UIBezierPath = UIBezierPath(CGPath: pathRef)
        let shape = SCNShape(path: bezierPath, extrusionDepth: 1)
        shape.materials = [self.blueNodeMaterial]
        return shape
    }()

    private lazy var blueNodeMaterial: SCNMaterial = {
        let material = SCNMaterial()
        material.diffuse.contents = UIColor.blueColor()
        return material
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        sceneView.frame = self.view.bounds
        sceneView.backgroundColor = UIColor.blackColor()
        self.view.addSubview(sceneView)

        sceneView.autoenablesDefaultLighting = true
        sceneView.allowsCameraControl = true

        sceneView.scene = testScene
    }
}

XCPShowView("SceneKit", view: SceneViewController().view)

A: If you want to map 2D content into the surface of a 3D SceneKit object, and have the 2D content be dynamic/interactive, one of the easiest solutions is to use SpriteKit for the 2D content. You can set your sphere's diffuse contents to an SKScene, and create/position/decorate SpriteKit nodes in that scene to arrange them on the face of the sphere.
If you want to have this content respond to tap events... Using hitTest in your SceneKit view gets you a SCNHitTestResult, and from that you can get texture coordinates for the hit point on the sphere. From texture coordinates you can convert to SKScene coordinates and spawn nodes, run actions, or whatever.
For further details, your best bet is probably Apple's SceneKitReel sample code project. This is the demo that introduced SceneKit for iOS at WWDC14. There's a "slide" in that demo where paint globs fly from the camera at a spinning torus and leave paint splashes where they hit it — the torus has a SpriteKit scene as its material, and the trick for leaving splashes on collisions is basically the same hit test -> texture coordinate -> SpriteKit coordinate approach outlined above.

A: David Rönnqvist's SceneKit book (available as an iBook) has an example (the EarthView example, a talking globe, chapter 5) that is worth looking at. That example constructs a 3D pushpin, which is then attached to the surface of a globe at the location of a tap.
Your problem is more complicated because you're constructing a shape that covers a segment of the sphere. Your "square" is really a spherical trapezium, a segment of the sphere bounded by four great circle arcs. I can see three possible approaches, depending on what you're ultimately looking for.
The simplest way to do it is to use an image as the material for the sphere's surface. That approach is well illustrated in the Ronnqvist EarthView example, which uses several images to show the earth's surface. Instead of drawing continents, you'd draw your square. This approach isn't suitable for interactivity, though. Look at SCNMaterial.
Another approach would be to use hit test results. That's documented on SCNSceneRenderer (which SCNView complies with) and SCNHitTest. Using the hit test results, you could pull out the face that was tapped, and then its geometry elements. This won't get you all the way home, though, because SceneKit uses triangles for SCNSphere, and you're looking for quads. You will also be limited to squares that line up with SceneKit's underlying wireframe representation.
If you want full control of where the "square" is drawn, including varying its angle relative to the equator, I think you'll have to build your own geometry from scratch. That means calculating the latitude/longitude of each corner point, then generating arcs between those points, then calculating a bunch of intermediate points along the arcs. You'll have to add a fudge factor, to raise the intermediate points slightly above the sphere's surface, and build up your own quads or triangle strips. Classes here are SCNGeometry, SCNGeometryElement, and SCNGeometrySource.


text:
Q: Moodle 3.7 & Apache & reverse proxy results ERR_TOO_MANY_REDIRECTS Moodle 3.7 Apache with reverse proxy results ERR_TOO_MANY_REDIRECTS.
I have an SSL site with following vhosts file:
<VirtualHost *:80>
    RewriteCond %{HTTPS} off
    RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
</VirtualHost>

<IfModule mod_ssl.c>
<VirtualHost *:443>
ServerName moodle.site.com:443

SSLEngine on
SecAuditEngine On
RewriteEngine On

    ProxyPreserveHost On
    ProxyPass / http://101.102.103.104:80/
    ProxyPassReverse / http://101.102.103.104:80/

</VirtualHost>
</IfModule>

I also redirect all 80 port requests to SSL port.
The command
curl -I https://moodle.site.com/

results:
HTTP/1.1 303 See Other
Date: Fri, 09 Aug 2019 19:13:33 GMT
Server: Apache/2.4.38 (Debian)
Strict-Transport-Security: max-age=15768000; includeSubDomains
Location: https://moodle.site.com
Content-Language: en
Content-Type: text/html; charset=UTF-8

In Moodle config.php I have:
$CFG->wwwroot   = 'https://moodle.site.com';
$CFG->reverseproxy = true;
$CFG->sslproxy  = 1;

Any idea why I get "ERR_TOO_MANY_REDIRECTS" error in Google Chrome, when I try to open https://moodle.site.com URL?

A: I had 4 problems, so I had to fix them (command line commands should be executed as root or use sudo):
1) mod_ssl Apache module was not activated. Test in the command line, if mod_ssl is active:
apache2ctl -M | grep ssl

Should display this (if active):
ssl_module (shared)

FIX (enable mod_ssl in the command line):
a2enmod ssl
# Considering dependency setenvif for ssl:
# Module setenvif already enabled
# Considering dependency mime for ssl:
# Module mime already enabled
# Considering dependency socache_shmcb for ssl:
# Enabling module socache_shmcb.
# Enabling module ssl.
# See /usr/share/doc/apache2/README.Debian.gz on how to configure SSL and create self-signed certificates.
# To activate the new configuration, you need to run:
# systemctl restart apache2

2) I use the Header directive in Apache SSL conf file, like this:
# Guarantee HTTPS for 180 days including sub domains
Header always set Strict-Transport-Security "max-age=15768000; includeSubDomains"

Because of this mod_headers Apache module is required, it was not activated. Test  in the command line, if mod_headers is active:
apache2ctl -M | grep headers

Should display this (if active):
headers_module (shared)

FIX (enable mod_headers in the command line):
a2enmod headers

3) I had to use https ProxyPass URL instead of http in Apache vhost conf file :
Wrong:
ProxyPass / http://101.102.103.104:80/
ProxyPassReverse / http://101.102.103.104:80/

GOOD:
ProxyPass / https://101.102.103.104/
ProxyPassReverse / https://101.102.103.104/

4) Had to turn on SSLProxyEngine directive to use SSL in ProxyPass in Apache vhost conf file.
FIX:
Added SSLProxyEngine on in /etc/apache2/sites-available/myvhost.conf
SSLProxyEngine on


text:
Q: Android Terminate application on-click and back button both in each activity In my app I have Multiple activities so here I want to terminate entire app In each activity..
on each activity I have options menu so at Options menu I have given this
else if (id == R.id.exit) {
        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(0);/*finish();
        System.exit(0);*/
    }

But its going to main activity
how to terminate entire application on back button pressed twice and on options menu exit..
can any one tell me..

A:  when you intent activity from splash screen need to add FLAG_ACTIVITY_NEW_TASK,FLAG_ACTIVITY_CLEAR_TASK,FLAG_ACTIVITY_NO_ANIMATION
  Intent mIntent = new Intent(context, mClass);
   mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    mIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
    mIntent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
    context.startActivity(mIntent);
    finishActivity();

1)declare this variable globally

private boolean doubleBackToExitPressedOnce;
private Handler mHandler = new Handler();

2)Then Implement this 3 below method
--------------------------------
 @Override
public void onBackPressed() {

    if (doubleBackToExitPressedOnce) {
        super.onBackPressed();
        finish();

    }

    this.doubleBackToExitPressedOnce = true;
     Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();

    mHandler.postDelayed(mRunnable, 2000);

}

 @Override
protected void onDestroy() {
    super.onDestroy();

    if (mHandler != null) {
        mHandler.removeCallbacks(mRunnable);
    }
}
@Override
protected void onResume() {
    super.onResume();
    this.doubleBackToExitPressedOnce = false;

}

private final Runnable mRunnable = new Runnable() {
    @Override
    public void run() {
        doubleBackToExitPressedOnce = false;
    }
};

A: Use this answer:
How to close an android application?
Intent homeIntent = new Intent(Intent.ACTION_MAIN);
homeIntent.addCategory( Intent.CATEGORY_HOME );
homeIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(homeIntent);

A: Please add finish(); method after startActivity(intent); method in every activity.


text:
Q: using forkJoin multiple times I am working on a Project where our client generates almost 500 request simultaneously. I am using the forkJoin to get all the responses as Array.
But the Server after 40-50 request Blocks the requests or sends only errors. I have to split these 500 requests in Chunks of 10 requests and loop over this chunks array and have to call forkJoin for each chunk, and convert observable to Promise.
Is there any way to get rid of this for loop over the chucks?

A: If I understand right you question, I think you are in a situation similar to this
const clientRequestParams = [params1, params2, ..., params500]
const requestAsObservables = clientRequestParams.map(params => {
  return myRequest(params)
})
forkJoin(requestAsObservables).subscribe(
  responses => {// do something with the array of responses}
)

and probably the problem is that the server can not load so many requests in parallel.
If my understanding is right and if, as you write, there is a limit of 10 for concurrent requests, you could try with mergeMap operator specifying also the concurrent parameter.
A solution could therefore be the following
const clientRequestParams = [params1, params2, ..., params500]
// use the from function from rxjs to create a stream of params
from(clientRequestParams).pipe(
   mergeMap(params => {
     return myRequest(params)
   }, 10) // 10 here is the concurrent parameter which limits the number of
          // concurrent requests on the fly to 10
).subscribe(
   responseNotification => {
      // do something with the response that you get from one invocation
      // of the service in the server
   }
)

If you adopt this strategy, you limit the concurrency but you are not guaranteed the order in the sequence of the responses. In other words, the second request can return before the first one has returned. So you need to find some mechanism to link the response to the request. One simple way would be to return not only the response from the server, but also the params which you used to invoke that specific request. In this case the code would look like this
const clientRequestParams = [params1, params2, ..., params500]
// use the from function from rxjs to create a stream of params
from(clientRequestParams).pipe(
   mergeMap(params => {
     return myRequest(params).pipe(
        map(resp => {
           return {resp, params}
        })
     )
   }, 10)
).subscribe(
   responseNotification => {
      // do something with the response that you get from one invocation
      // of the service in the server
   }
)

With this implementation you would create a stream which notifies both the response received from the server and the params used in that specific invocation.
You can adopt also other strategies, e.g. return the response and the sequence number representing that response, or maybe others.


text:
Q: C#: Sort json object by value How can we sort below json by 'FieldName'? Like ordering by 'FieldName' to asc/desc. It is a string value.
Json:
    {
      "Information": [
        {
          "FieldName": "Area04",
          "Draft": "Unknown",
        },
        {
          "FieldName": "Area02",
          "Draft": "Unknown",
        },
        {
          "FieldName": "Area01",
          "Draft": "Unknown",
        },
        {
          "FieldName": "Area03",
          "Draft": "Unknown",
        }
      ],
      "OtherInfo": []
    }

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

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

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

Kindly check and let me know, nothing could strike to my mind for ordering it, I tried using a couple of stackover flow answers too, it didnt work for my json object. I tried with above code and getting exception 'Cannot deserialize the current JSON object'.

A: did you sovle the problem? I have copy your whole code and run, it works due!
public class Informat
    {
        public Information[] Information { get; set; }
        public object[] OtherInfo { get; set; }
    }

public class Information
{
    public string FieldName { get; set; }
    public string Draft { get; set; }
}
class Program
{
    static void Main(string[] args)
    {
        string _json = "{'Information': [{'FieldName': 'Area04','Draft': 'Unknown'},{'FieldName': 'Area02','Draft': 'Unknown'},{'FieldName': 'Area01','Draft': 'Unknown'},{'FieldName': 'Area03','Draft': 'Unknown'}],'OtherInfo': []}";
        var jObj = JsonConvert.DeserializeObject<Informat>(_json);
        var test1 = jObj.Information.OrderBy(x => x.FieldName);
        string ss = JsonConvert.SerializeObject(test1);

        // My Code to Check if the result is correct
        var obj = JsonConvert.DeserializeObject<IEnumerable<Information>>(ss);
        foreach (var item in obj)
        {
            Console.WriteLine($"{item.FieldName} : {item.Draft}");
        }
    }
}


text:
Q: MSP430 MPU9250 MPU6050 I2C: After sending the address NACK I have a problem with read from my MPU6050/MPU9250. Both are connected with AD0 to ground so both should have the address 0x68. With both sensors the same behaviour occurs. I'm testing them individually. I recently bought the mpu9250 where i wasn't able to read data. In a another project i was able to read data from mpu6050 using a stm32.
If i used this code on MSP430FR5969 launchpad evaluation kit with P1.6 as SDA and P1.7 as SCK, after setting the start condition for I2C-communication using UCB0CTLW0 |= UCTR + UCTXSTT; the ´TXIEFG0´ flag and the ´NACKIE´ flag are set.
Afterwards 0x75 is written to the write buffer in ISR but never sent out.
I searched the internet for 4 hours but nobody seems to have ever discovered this problem. What are possible reasons?
After initialization my registers look like this:

#include "driverlib.h"
#include "MPU9250_reg.h"

/* Slave address */
// b110100X with X = 0 (ADO is connected to ground)=> 0x68
#define SLAVE_ADDRESS 0x68
#define SLAVE_ADDRESS_READ  0x11010001
#define SLAVE_ADDRESS_WRITE ((SLAVE_ADDRESS << 1)|0x00)

volatile uint8_t a;
volatile uint8_t byte_counter;
int main(void) {

    WDT_A_hold(WDT_A_BASE);

    // Configure Pins for I2C
       //Set P1.6 and P1.7 as Secondary Module Function Input.
       /*

       * Select Port 1
       * Set Pin 6, 7 to input Secondary Module Function, (UCB0SIMO/UCB0SDA, UCB0SOMI/UCB0SCL).
       */
       GPIO_setAsPeripheralModuleFunctionInputPin(
           GPIO_PORT_P1,
           GPIO_PIN6 + GPIO_PIN7,
           GPIO_SECONDARY_MODULE_FUNCTION
       );

           EUSCI_B_I2C_initMasterParam param = {0};
           param.selectClockSource = EUSCI_B_I2C_CLOCKSOURCE_SMCLK;
           param.i2cClk = CS_getSMCLK();
           param.dataRate = EUSCI_B_I2C_SET_DATA_RATE_100KBPS;
           param.byteCounterThreshold = 0;
           param.autoSTOPGeneration = EUSCI_B_I2C_NO_AUTO_STOP;
           EUSCI_B_I2C_initMaster(EUSCI_B0_BASE, &param);

           PMM_unlockLPM5();
           __bis_SR_register(GIE);

           //Specify slave address
           EUSCI_B_I2C_setSlaveAddress(EUSCI_B0_BASE,
                       SLAVE_ADDRESS_WRITE
                       );

           //Set Master in transmit mode
           EUSCI_B_I2C_setMode(EUSCI_B0_BASE,
                       EUSCI_B_I2C_TRANSMIT_MODE
                       );

           //Enable I2C Module to start operations
           EUSCI_B_I2C_enable(EUSCI_B0_BASE);

           // ensure it not busy
           while(UCB0STATW & UCBBUSY){}

           // send a Stop condition
           UCB0CTLW0 |= UCTXSTP;
           while(!(UCB0CTLW0 & UCTXSTP)){}

           EUSCI_B_I2C_enableInterrupt(EUSCI_B0_BASE, EUSCI_B_I2C_TRANSMIT_INTERRUPT0);
           byte_counter = 1;
           UCB0CTLW0 |= UCTR + UCTXSTT;
           // after this step the UCTXIEF0 and the UCNACKIFG flag are set

    while(1)
    {
        _nop();
    }
}

#if defined(__TI_COMPILER_VERSION__) || defined(__IAR_SYSTEMS_ICC__)
#pragma vector=USCI_B0_VECTOR
__interrupt
#elif defined(__GNUC__)
__attribute__((interrupt(USCI_B0_VECTOR)))
#endif
void USCIB0_ISR(void)
{
    switch(__even_in_range(UCB0IV, USCI_I2C_UCBIT9IFG))
    {
        case USCI_NONE:             // No interrupts break;
            break;
        case USCI_I2C_UCALIFG:      // Arbitration lost
            break;
        case USCI_I2C_UCNACKIFG:    // NAK received (master only)
            break;
        case USCI_I2C_UCSTTIFG:     // START condition detected with own address (slave mode only)
            break;
        case USCI_I2C_UCSTPIFG:     // STOP condition detected (master & slave mode)
            break;
        case USCI_I2C_UCRXIFG3:     // RXIFG3
            break;
        case USCI_I2C_UCTXIFG3:     // TXIFG3
            break;
        case USCI_I2C_UCRXIFG2:     // RXIFG2
            break;
        case USCI_I2C_UCTXIFG2:     // TXIFG2
            break;
        case USCI_I2C_UCRXIFG1:     // RXIFG1
            break;
        case USCI_I2C_UCTXIFG1:     // TXIFG1
            break;
        case USCI_I2C_UCRXIFG0:     // RXIFG0
            // will never be reached cause there a NACK after sending the slave address
            // would be used for receiving
            while(1){}
            break;
        case USCI_I2C_UCTXIFG0:     // TXIFG0
            if(byte_counter == 1)
            {
                // won't be send cause there the NACK before?
                UCB0TXBUF = 0x75;
                byte_counter--;
            }
            else if(byte_counter == 0)
            {
                // clear and disable interrupt
                EUSCI_B_I2C_clearInterrupt(EUSCI_B0_BASE, EUSCI_B_I2C_TRANSMIT_INTERRUPT0);
                EUSCI_B_I2C_disableInterrupt(EUSCI_B0_BASE, EUSCI_B_I2C_TRANSMIT_INTERRUPT0);

                // change to receive mode
                UCB0CTLW0 &= ~(UCTR);

                // enable receive interrupt
                EUSCI_B_I2C_enableInterrupt(EUSCI_B0_BASE, EUSCI_B_I2C_RECEIVE_INTERRUPT0);

                // send start signal with READ
                //Specify slave address
                EUSCI_B_I2C_setSlaveAddress(EUSCI_B0_BASE,
                            SLAVE_ADDRESS_READ
                            );
                UCB0CTLW0 |= UCTXSTT;
            }
            else
            {
                // not aloud
                while(1){}
            }
            break;
        case USCI_I2C_UCBCNTIFG:    // Byte count limit reached (UCBxTBCNT)
            break;
        case USCI_I2C_UCCLTOIFG:    // Clock low timeout - clock held low too long
            break;
        case USCI_I2C_UCBIT9IFG:    // Generated on 9th bit of a transmit (for debugging)
            break;
        default:
            break;
    }
}

A: I2C devices should have different addresses. Connect one device' A0 to Vcc via a pull up resistor, so it will have address 0x69.

A: The slave address is 0x68 (1101000), but the code uses address 0xD0 (11010000), which is not even possible because normal I²C slave addresses have only 7 bits.
And there is no reason to set the slave address again before the repeated start.
(It appears you have confused the I²C address with the first I²C byte, which combines the seven bits of the address with the read/write bit.)


text:
Q: How to call a function in a cog from a view using Nextcord? I have a Cog and a view in nextcord. I'm trying to call the function magic_function from my view, but I've found no way of achieving it. Do you know how is it possible ?
Here is a simplification of the situation :
class MyView(nextcord.ui.View):
    def __init__(self):
        super().__init__(timeout=None)

    @nextcord.ui.button(label='Send Magic', style=nextcord.ButtonStyle.primary)
    async def magicbutton(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
        magic_word = MyCog.get_magic_word() # Here, I would like to access MyCog, but can't figure how
        await interaction.response.send_message(magic_word)

class MyCog(commands.Cog):
    def __init__(self, client):
        self.client = client

    def get_magic_word(self):
        # Doing stuff
        return "Banana"

    @nextcord.slash_command(description="Sends the button")
    async def send_the_view(self, interaction: nextcord.Interaction):
        view = MyView()
        await interaction.response.send_message("Here is the view :", view=view)

def setup(client):
    client.add_cog(MyCog(client=client))

I thought I could define my view inside the Cog, but I find it useless, since i coulden't access the function either. Also, I thought I could bring the function get_magic_word() outside the cog, but this is a bad idea since the function needs to call self to do stuff.

A: An easy way to do this is to provide the view with a reference to the instantiated Cog object:
class MyView(nextcord.ui.View):
    def __init__(self, my_cog):
        super().__init__(timeout=None)
        self.my_cog = my_cog  # store the cog object as a class variable

    @nextcord.ui.button(label='Send Magic', style=nextcord.ButtonStyle.primary)
    async def magicbutton(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
        magic_word = self.my_cog.get_magic_word()  # interact with the cog object
        await interaction.response.send_message(magic_word)

class MyCog(commands.Cog):
    def __init__(self, client):
        self.client = client

    def get_magic_word(self):
        # Doing stuff
        return "Banana"

    @nextcord.slash_command(description="Sends the button")
    async def send_the_view(self, interaction: nextcord.Interaction):
        view = MyView(self)  # pass self to the view
        await interaction.response.send_message("Here is the view :", view=view)

This way, MyView can access methods/attributes on the instantiated MyCog.


text:
Q: How to subscribe a FB page to a facebook app? I'm trying to subscribe a Facebook page to my facebook app. It's a messenger app where I need to subscribe the page to my webhook added in the app.
Using the graph API, I have the page access token and page id, I have tried the subscribed_apps API but it didn't work
 FB.api('/' + page.id+ '/subscribed_apps?access_token=' +
         page.access_token,function (response) {
            console.log(response)
        });

Is there an API to make the page to subscribe to my webhook in the app.

A: It is described in the Graph API reference:
https://developers.facebook.com/docs/graph-api/reference/page/subscribed_apps/#Creating

A: You can you the below API to subscribe the page to your webhook. Specify the fields you want to subscribe to using the subscribed_fields query parameter depends on your use case.
`curl -i -X POST "https://graph.facebook.com/{page-id}/subscribed_apps
?subscribed_fields=feed
&access_token={page-access-token}"`

Example - If your use-case is related to page messaging use messages,message_echoes fields as subscribed_fields.
Note - Your page access token should have pages_messaging permission.


text:
Q: Register filetype with the browser? In Android, I am trying to make it so that the user downloads a font from the browser, and I am able to view the font when downloaded. After multiple issues, I still have one lingering one: Registering the filetype with the browser.
When trying to download with the Emulator (2.1-u1), I get "Cannot download. The content is not supported on this phone". Okay, so maybe its my manifest file. Updated with this:
    <activity android:name=".MainActivity" android:label="MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>
            <category android:name="android.intent.category.LAUNCHER"/>
            <catagory android:name="android.intent.category.BROWSABLE"/>
            <data android:scheme="http"/>
            <data android:scheme="https"/>
            <data android:scheme="ftp"/>
            <data android:host="*"/>
            <data android:mimeType="*/*"/>
            <data android:pathPattern=".*zip"/>
        </intent-filter>
    </activity>

Went back to the browser, and fails again. Restart the Emulator, still fails.
Note that I got this format from posts here.
Any suggestions on what to do?

A: Registering for a MIME type of */* and a host of * is rather impolite. You are attempting to handle every ZIP file from every Web site, whether it is a font or not.
Try an action of VIEW instead of MAIN.

A: <catagory android:name="android.intent.category.BROWSABLE"/>

The first word on that line, "catagory", should be "category". Maybe that typo is the cause of the problem.


text:
Q: Webwervice security header in java client code <soapenv:Header>
<UsernameToken xmlns="http://siebel.com/webservices">uname</UsernameToken>
<PasswordText xmlns="http://siebel.com/webservices">pass</PasswordText>
<SessionType xmlns="http://siebel.com/webservices">None</SessionType>
</soapenv:Header>

I have generated client code using axis runtime and I am getting this exception:Operation 'QueryByExample' with no authentication cannot be executed in an anonymous session pool. Please associate an authentication type with the web service operation.(SBL-EAI-04552).
I looked at others answers from stackoverflow for hours and nothing worked out for me. Please guide me....
Service code:
SOAPHeaderElement wsseSecurity = new SOAPHeaderElement(new PrefixedQName("http://schemas.xmlsoap.org/ws/2002/04/secext","Security", "wsse"));
        MessageElement username = new MessageElement("uname", "UsernameToken");
        MessageElement password = new MessageElement("pass", "PasswordText");
        username.setObjectValue("username");
        password.setObjectValue("password");
        wsseSecurity.addChild(username);
        wsseSecurity.addChild(password);
stub.setHeader(wsseSecurity);

A: You need to add few more things and the main problem is how you are deifning and using your password. You are on the correct path but here is how you would make a  SOAP Axis 1.4 client:
InputStream inConfig = BaseTestCase.class.getClassLoader().getResourceAsStream("axis_client_config.xml");
        EngineConfiguration config = new FileProvider(inConfig);
        PartnerAPILocator locator = new PartnerAPILocator(config);
        inConfig.close();

        stub = locator.getSoap();

        Stub axisPort = (Stub) stub;
        axisPort._setProperty(UsernameToken.PASSWORD_TYPE, WSConstants.PASSWORD_TEXT);
        axisPort._setProperty(WSHandlerConstants.USER, "ET USERNAME");
        axisPort._setProperty(WSHandlerConstants.PW_CALLBACK_REF, new PasswordTokenHandler());

here is my source and try to follow the tutorial and you can even download the code. Hope this helps you.


text:
Q: How do I kill the player in Minecraft when they enter a specific area (-131 5 236 to -122 5 227)? Am making a minigame where the player dies when they fall and I need to kill them without destroying items. I don't want to use tripwire hooks.

A: You can use the command /kill @a[x=-131,y=5,z=227,dx=9,dy=0,dz=9] in a repeating command block. Mcstacker is a great resource for advanced command generation. You can read more about the volume selector here.


text:
Q: php sql - select from table 1 when there is no entry in table 2 for a specific userID AND specific eventID I would like to show only the Event-Names - for which a specific (logged In user) has not already signed up.
There are two sql tables with the following rows:

Table1 Events: Event_ID (PK) | Event_Name
Table2 Signups: Signup_ID (PK, AI) | Event_ID | User_ID

The Event Signup works. BUT I am looking for a SELECT query where only the events are selected for which there is no corresponding signup for the specific (logged in) User?

A: Then Try like this:-
select * from table_1 where Event_ID NOT IN (SELECT Event_ID FROM table_2 where Signup_ID = mysignupid )

This query is only a logic. Put values of your's accordingly. Post back if you have errors


text:
Q: Git push again the same commit to remote My project has a remote and local synchronized repository.

*

*I did locally new branch -> than committed and pushed to the remote.

*Next, I have unaware deleted remote branch - operation is impossible to undo(in Gitlab).

So, locally I have everything OK only my remote repository need to be updated.
How to push again the same commit to remote?
(I do everything in Intellij and one time pushed commit is no more visible there and of course not possible to push again)
Thanks for any help.

A: If the remote branch is completely deleted, You can directly push your local branch to remote
git push origin <local-branch-name>
or in Intellij while on your branch press Ctrl+Shift+k and push
Every commit in your local branch should appear in remote


text:
Q: How to implement long-running transactions over a web service, like unit of work I'm designing a web service and a desktop client application that uses the web service. The interface has a requirement that you need to be able to perform multiple operations and commit them all at once. The operations are basic CRUD operations (create, read, update, delete).
Here's a rough, and Car-ified example of what the workflow would be:

The problem is that the service calls could be spread out over time. I originally had created a REST web service, but REST by definition shouldn't be transactional. The interface has to be able to commit all operations to the database in one go (upon a Save button click).
Edit: An important stipulation is that given the example above, a Car must exist in the database on the server in order to add seats to it. Within a transaction, that car should only be available to the person (session) who is working within that transaction. That limits the ability to send all the operations to the web service at one time at the end of the workflow.
The options I have considered so far are:
1) Implement distributed transactions using SOAP (WCF) and only commit when Save is clicked on the GUI. Is this possible/a good idea for longer transaction lifetimes?
2) Create a unit of work 'service' that takes operations and executes them all within one transaction on the server.
My question is, is 1) possible, or a good/bad idea? Is 2) a good idea, and are there any patterns/tools for implementing this across a web service (REST or SOAP)? Or is there a different way to handle this problem?

A: I would try this:
POST /unit-of-work
   create with response 200
POST /car
   create with response 202
POST /seat
   create with response 202
etc.
PUT /unit-of-work
   set "execute" bit, or somesuch

In this case, car, seat, etc have the unit-of-work specified when they're posted. When the unit-of-work is updated to be "done", all the items are executed.
Another approach would be:
POST /car
   create with response 202
POST /seat
   create with response 202
etc.
POST /unit-of-work response 200

In this case, car, seat, etc have a bit set saying they're not created yet. The unit-of-work should specify what resources belong to it, and then the back end can flip the bit on the other resources so they're created.


text:
Q: Maximum of function of three variables on the unit cube I am looking to prove that the function
$$f(x,y,z) = \frac{x(1-x)y(1-y)z(1-z)}{1 - (1-xy)z}$$
attains it's maximum at a point within the unit cube $[0,1] \times [0,1] \times [0,1]$ and NOT on the boundary.
Wolfram Alpha confirms that the max is attained not on the boundary, but actually within the cube. I have been able to show that there is a local maximum which gives this value inside the cube, but I can't see how to show that the values at the boundary don't go to infinity. For example, if we approach the vertex $(x,y,z) = (0,0,1)$ we get $0$ over $0$.

How do I know that the function doesn't go to infinity as we tend to this vertex?

Many thanks in advance.

A: The reciprocal $1/f$ can be written as $1/[(1-x)(1-y)]$ times the sum of two terms
$$\frac{1}{xyz}+\frac{1}{1-z}.$$
As $(x,y,z) \to (0,0,1)$ (through values interior to the cube) both terms go to $+\infty$ making $f$ itself tend to $0.$
The same happens whenever both the product $xy$ and $z$ tend to zero, and these are all the points where $f$ is not defined.