text:
Q: TextToSpeech - Unable to start activity: findViewById(R.id.srcText) must not be null in Kotlin Android Been working on a real-time Translation project combined with TTS, but I'm a total beginner in Android development. The OCR and translate functions are working properly since I referred to the codelab.
However, after I have added TTS to MainActivity with srcText(TextView) in main_fragment.xml the error showed up. Have read a number of posts regarding this problem, but can't seem to find a suitable solution since the structure of the project files from the codelab is quite complicated(activity, fragment, ViewModel...) .
MainActivity.kt
import android.os.Bundle
import android.speech.tts.TextToSpeech
import android.util.Log
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.mlkit.codelab.translate.main.MainFragment
import java.util.*

class MainActivity : AppCompatActivity(), TextToSpeech.OnInitListener {

    private var tts: TextToSpeech? = null //ADDED from TextToSpeech

    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)
        //setContentView(R.layout.main_fragment)
        setContentView(R.layout.main_activity) //Changed

        if (savedInstanceState == null) {
            supportFragmentManager.beginTransaction()
                .replace(R.id.container, MainFragment.newInstance())
                .commitNow()
        }

        //TextToSpeech starts here...
        //(Copied code) Button and etEnteredText need to be removed and modified respectively
        tts = TextToSpeech(this, this)
        //val btnSpeak: Button =findViewById(R.id.btnSpeak)
        //val etEnteredText: EditText =findViewById(R.id.etEnteredText)

        Log.i("123","Initialization Completed")

        val srcText: TextView = findViewById(R.id.srcText)
        val translatedText: TextView= findViewById(R.id.translatedText)
        //btnSpeak.setOnClickListener{ view ->

            if(srcText.text.isEmpty()){
                Toast.makeText(this@MainActivity,
                    "Enter a text to use TTS.", Toast.LENGTH_SHORT)
                    .show()
            }else{
                speakOut(srcText.text.toString())
            }

            //Do the same for ...

            if(translatedText.text.isEmpty()){
                Toast.makeText(this@MainActivity,
                    "Enter a text to use TTS.", Toast.LENGTH_SHORT)
                    .show()
            }else{
                speakOut(translatedText.text.toString())
            }

        //}
    }

    override fun onInit(status: Int) {

        if (status == TextToSpeech.SUCCESS) {
            // set US English as language for tts
            val result = tts!!.setLanguage(Locale.US)

            if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                Log.e("TTS","The Language specified is not supported!")
            }

        } else {
            Log.e("TTS", "Initialization Failed!")
        }

    }

    private fun speakOut(text: String){
        tts!!.speak(text, TextToSpeech.QUEUE_FLUSH, null, "")
    }

    public override fun onDestroy() {

        if (tts != null) {
            tts!!.stop()
            tts!!.shutdown()
        }
        super.onDestroy()
    }

}

main_activity.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" />

main_fragment.xml
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.google.mlkit.showcase.translate.main.MainFragment">

    <androidx.camera.view.PreviewView
        android:id="@+id/viewfinder"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintBottom_toTopOf="@id/middle"
        app:layout_constraintTop_toTopOf="parent" />
    <SurfaceView
        android:id="@+id/overlay"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintStart_toStartOf="@id/viewfinder"
        app:layout_constraintEnd_toEndOf="@id/viewfinder"
        app:layout_constraintBottom_toBottomOf="@id/viewfinder"
        app:layout_constraintTop_toTopOf="@id/viewfinder" />

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/middle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent=".5" />

    <TextView
        android:id="@+id/srcLang"
        style="@style/SrcLangText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="20dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="20dp"
        android:layout_marginBottom="4dp"
        app:layout_constraintBottom_toTopOf="@+id/srcTextScrollView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/middle"
        tools:text="source lang" />

    <ScrollView
        android:id="@+id/srcTextScrollView"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:layout_marginBottom="4dp"
        android:fillViewport="true"
        android:scrollbars="vertical"
        app:layout_constraintBottom_toTopOf="@+id/divider"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/srcLang">

        <TextView
            android:id="@+id/srcText"
            style="@style/SrcText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginStart="20dp"
            android:layout_marginEnd="20dp"
            tools:text="source text" />
    </ScrollView>

    <View
        android:id="@+id/divider"
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_marginStart="20dp"
        android:layout_marginEnd="20dp"
        android:background="?android:attr/listDivider"
        app:layout_constraintBottom_toTopOf="@+id/targetLangSelector"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/srcTextScrollView" />

    <Spinner
        android:id="@+id/targetLangSelector"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="20dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/divider" />

    <ScrollView
        android:id="@+id/translatedTextScrollView"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:layout_marginBottom="4dp"
        android:fillViewport="true"
        android:scrollbars="vertical"
        app:layout_constraintBottom_toTopOf="@+id/divider2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/targetLangSelector">

        <TextView
            android:id="@+id/translatedText"
            style="@style/TranslatedText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginStart="20dp"
            android:layout_marginEnd="20dp"
            android:layout_marginBottom="4dp"
            tools:text="translated text" />
    </ScrollView>

    <View
        android:id="@+id/divider2"
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_marginStart="20dp"
        android:layout_marginTop="4dp"
        android:layout_marginEnd="20dp"
        android:layout_marginBottom="4dp"
        android:background="?android:attr/listDivider"
        app:layout_constraintBottom_toTopOf="@id/imageView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/translatedTextScrollView" />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="18dp"
        android:layout_marginStart="4dp"
        android:layout_marginTop="4dp"
        android:layout_marginEnd="4dp"
        android:layout_marginBottom="4dp"
        android:contentDescription="@string/content_description_google_translate_attribution"
        android:scaleType="fitCenter"
        android:src="@drawable/greyscale_regular_3x"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/divider2" />

    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyle"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:visibility="invisible"
        app:layout_constraintStart_toEndOf="@+id/targetLangSelector"
        app:layout_constraintTop_toTopOf="@id/targetLangSelector"
        app:layout_constraintBottom_toBottomOf="@id/targetLangSelector" />

    <TextView
        android:id="@+id/progressText"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:text="@string/downloading_model_files"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/progressBar"
        app:layout_constraintBottom_toBottomOf="@id/progressBar"
        android:gravity="center_vertical"
        app:layout_constraintTop_toTopOf="@id/progressBar" />

</androidx.constraintlayout.widget.ConstraintLayout>

Logcat Error Message
2022-05-12 02:49:48.730 18411-18411/com.google.mlkit.codelab.translate E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.google.mlkit.codelab.translate, PID: 18411
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.google.mlkit.codelab.translate/com.google.mlkit.codelab.translate.MainActivity}: java.lang.IllegalStateException: findViewById(R.id.srcText) must not be null
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
     Caused by: java.lang.IllegalStateException: findViewById(R.id.srcText) must not be null
        at com.google.mlkit.codelab.translate.MainActivity.onCreate(MainActivity.kt:61)
        at android.app.Activity.performCreate(Activity.java:7994)
        at android.app.Activity.performCreate(Activity.java:7978)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)

Need a helping hand from my fellow developers and hopefully without making a whole lot of changes to the original structure. Thanks in advance :)

A: Do like this it might be Work :
private var srcText : TextView ? = null //Add this variable above onCreate

Find view by ID. Within on Create
srcText = findViewById(R.id.srcText)

So Your onCreate Code is like this :
override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)
        //setContentView(R.layout.main_fragment)
        setContentView(R.layout.main_activity) //Changed

        if (savedInstanceState == null) {
            supportFragmentManager.beginTransaction()
                .replace(R.id.container, MainFragment.newInstance())
                .commitNow()
        }

        //TextToSpeech starts here...
        //(Copied code) Button and etEnteredText need to be removed and modified respectively
        tts = TextToSpeech(this, this)
        //val btnSpeak: Button =findViewById(R.id.btnSpeak)
        //val etEnteredText: EditText =findViewById(R.id.etEnteredText)

        Log.i("123","Initialization Completed")

        srcText = findViewById(R.id.srcText)  // Find View By ID of srcText Here

        val translatedText: TextView= findViewById(R.id.translatedText)
        //btnSpeak.setOnClickListener{ view ->

            if(srcText.text.isEmpty()){
                Toast.makeText(this@MainActivity,
                    "Enter a text to use TTS.", Toast.LENGTH_SHORT)
                    .show()
            }else{
                speakOut(srcText.text.toString())
            }

            //Do the same for ...

            if(translatedText.text.isEmpty()){
                Toast.makeText(this@MainActivity,
                    "Enter a text to use TTS.", Toast.LENGTH_SHORT)
                    .show()
            }else{
                speakOut(translatedText.text.toString())
            }

        //}
    }

Hope this Will work.


text:
Q: LibreOffice Draw multiple jpg to pdf How can I use LibreOffice Draw to convert multiple jpg files which were scanned, to a pdf file in a short way. Last time I had to create "New page" then "Insert -> Image" which was a *** for about 50 pages.

A: IMHO this isn't a LO problem, but a workflow issue. The best solution depends on the specific requirements. If the requirements do vary, i would recommend trying to "modularize" the process, so variations will only affect one workflow module.
If you aren't sure which jpgs to convert (and if disk space isn't an issue), you should simply convert all of them (command line tool, e.g. imagemagick/convert).
To select the pdfs for merging, you could use a GUI tool like PDFShuffler. Just add all pdfs created in step one, and remove the ones that shouldn't be merged.
To edit the resulting single big PDF afterwards, use a tool like PDFSam that lets you insert a single PDF in the middle of another PDF file.
EDIT:
Use LO Impress' Photo Album feature: New Presentation -> Insert -> Media -> Photo Album. There, you can select multiple images to insert. If you're done, just export as PDF.

A: You can use ImageMagick (package name: imagemagick) for that job:
convert <SOURCE...> <TARGET>

Example:
convert *.jpg my-collection.pdf

A: Maybe you should have a look at online tools for this, like https://smallpdf.com/jpg-to-pdf it's sometime easier than try to find a way using a specific software

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to replicate SQL Server rowversion behaviour for some fields only SQL Server version 10.50.4000.
I have a table:
create table people
(
    national_id char(16),
    full_name char(255),
    last_visited datetime
)

I want to add a field that will work exactly like a rowversion field, except:

*

*It must update only when last_visited is changed.

*It needn't be unique on the database but must be unique on the table.

How can I do this?


text:
Q: Is there anyway to to "Template-like" check if there are missing or wrong values in an Object in JS? I'm receiving data from an API (one JS Object each time) and want to check if any of the values in there is missing or of the wrong datatype.
Is it possible to define something like a template:
e.g.
{"name": String, "Housenumber: "Integer}
and check if the actual object has the same keys and datatypes?

A: Yes you can just create an object with all the keys and datatypes. After that you can just loop over the object and check it against your data.
Be aware that you can't check the difference between floats and integers with the use of typeof. For that you need a custom check.
Though i suggest something like typescript for type checking since it has lots of build in functionality for it.

const personInterface = {
  name: "string",
  age: "number",
};

const persons = [
  {
    name: "bob",
    age: 18,
  },
  {
    name: "karen",
    age: "50",
  }
];

for(const person of persons) {
  for(const [key, value] of Object.entries(personInterface)) {
    if(typeof person?.[key] === value) {
      console.log(`${person[key]} matches ${value}`);
    } else {
      console.log(`${person[key]} does not match ${value}`);
    }
  }
}


text:
Q: Regex & BBCode - Perfecting Nested Quote I'm working on some BBcode for my website.
I've managed to get most of the codes working perfectly, however the [QUOTE] tag is giving me some grief.
When I get something like this:
[QUOTE=1]
[QUOTE=2]
This is a quote from someone else
[/QUOTE]
This is someone else quoting someone else
[/QUOTE]

It will return:
> 1 said:  [QUOTE=2]This is a quote from
> someone else

This is someone else quoting someone else[/QUOTE]

So what is happening is the [/quote] from the nested quote is closing the quote block.
The Regex I am using is:
"[quote=(.*?)\](.*?)\[/quote\]'is"

How can I make it so nested Quotes will appear properly?
Thank you.

A: You could construct recursive regular expression (available since libpcre-3.0 according to their changelog):
\[quote=(.*?)\](((?R)|.)*?)\[\/quote\]

But it would be better if you follow @codeka advice.
Update:
(?R) here means «insert the whole regular expression in place where (?R) occurs». So a(?R)?b is equivalent (if you forget about capturing groups) to a(a(?-1)?b)?b which is equivalent to a(a(a(?-1)?b)?b)?b and so on. Instead of (?R) you can use (?N), (?+N), (?-N) and (?&a) which means «substitute with N'th capturing group», «substitute with N'th next capturing group», «substitute with N'th previous capturing group» and «substitute with capturing group named «a»».

A: This is not really a task that regular expressions are good for. It's almost like trying to parse HTML with regular expressions, and we know what happens when you do that...
What you could do, and even then I don't think it's all that great an idea, is to use preg_split to split your input text into tags-and-non-tags. So you'll end up with a list like this:

*

*[QUOTE=1]

*(blank)

*[QUOTE=1]

*This is a quote from someone else

*[/QUOTE]

*This is someone else quoting someone else

*[/QUOTE]

Then you run through the list converting the tags to HTML and outputting the plain-text unmodified. You can even get fancy and keep "nesting" counts so that if you encounter a "[/quote]" when you're not expecting it, you can handle the situation a bit better than just outputting invalid HTML. Alternatively, you just output things as you find them and let HTMLPurify or something clean it up later.

A: I dealt with this problem for quite a long time and would like to completely close the question by supplementing the answer of the respected ZyX.
He suggested an excellent search template, but as Moe said, nested quotes themselves are not processed this way.
To solve this problem, I used a while loop and ZyX's pattern with preg_replace_callback function:

$text =
'
[QUOTE=ctmcn]
    [quote="John Doe;1000"]Lorem ipsum dolor sit amet[/quote]
    Lorem ipsum dolor sit amet
[/QUOTE]
-----------------------------
[QUOTE="John Doe;103318"]
 [QUOTE]
  [QUOTE="John-Doe;103318"]
   Lorem ipsum dolor sit amet
  [/QUOTE]
 Lorem ipsum dolor sit amet
 [/QUOTE]
Lorem ipsum dolor sit amet

 [QUOTE="John-Doe;103318"]
 Lorem ipsum dolor sit amet
 [/QUOTE]
Lorem ipsum dolor sit amet
 [QUOTE="John-Doe;103318"]
 Lorem ipsum dolor sit amet
 [/QUOTE]
Lorem ipsum dolor sit amet
[/QUOTE]
Lorem ipsum dolor sit amet
----------------------------
[QUOTE="John-Doe;103318"]Lorem ipsum dolor sit amet[/QUOTE]
----------------------------
[QUOTE="Максим;103318"]Lorem ipsum dolor sit amet[/QUOTE]
Lorem ipsum dolor sit amet
'

$text = nestedQuotes($text);

function nestedQuotes($text) {
    while (preg_match('#\[quote=?(.*?)\](((?R)|.)*?)\[\/quote\]#is', $text)) {
        $text = preg_replace_callback (
            '#\[quote=?(.*?)\](((?R)|.)*?)\[\/quote\]#is',
            function($m) {
                if ($m[1]) {
                    if (strpos(';', $m[1])) {
                        list($qname, $qpostid) = str_replace('"', '', explode(";", $m[1]));
                        if ($qname && !$qpostid) return 'here code with quotet username and without source post_id, LIKE: [qoute="username";]text[/quote]';
                        if ($qname && $qpostid) return 'here code with quotet username and with source post_id, LIKE: [qoute="username;postid"]text[/quote]';
                    } else {
                        $qname = str_replace('"', '', $m[1]);
                        return 'here code with quotet username and without source post_id [qoute=username]text[/quote]';
                    }
                } else {
                    return 'here anonymous quote, LIKE: [quote]text/quote]';
                }
            },
            $text
        );
        echo $text;
    }
}

Like this you can beat any level nested and any type quotes.
preg_replace_callback function, allow to use function as replacement parameter, thanks to which, we can find out which response to return based on the form in which the original quote is (is it possible to get the name of the quoted user, id of the quoted message, etc.).
Variable $m is array with  captured groups.
$m[0] its all captured pattern.
$m[1] its first captured group
$m[2] its second captured group...

and so on..
But this method has a drawback. The search template is quite "greedy" and on large amounts of text I encountered a problem in the work of php. It does not return any values and does not report any errors.
If anyone adds a more optimal search template that would be the perfect solution.
Hope this help somebody!


text:
Q: Спавн локального игрока или нелокальных игроков с разными префабами с помощью Mirror'а Использую для мультиплейера Mirror
Здравствуйте, у меня возникла проблема, со спавном локального игрока и других игроков, мне нужно, чтобы префаб локального игрока отличался при спавне от префабов других игроков. Проще говоря, чтобы у игрока на его устройстве он был префабом "А", а другие игроки - префабами "Б". Как это можно реализовать?
Я знаю, что можно всех спавнить одинаковыми, а потом удалять,добавлять и изменять нужные компоненты, но я не хочу так делать.


text:
Q: A combinatorics problem related to Bose-Einstein statistics Problem
Given $N$ and $E$, how many solutions $(n_0,n_1,...,n_E)$ are there to:
$$\sum_{k=0}^En_k = N$$
$$\sum_{k=0}^Ek.n_k = E$$
where everything is non-negative integer ($N,E,n_k \in \mathbb{Z}_{\geq 0}$ )?

Context
$N$ is the number of indistinguishable particles that can occupy $Q+1$ distinguishable energy levels, with energies $E_k=0,1,2,...,Q$. In this case, $Q=E$, which is the total energy of the system.
Here's an example for $N=6$ and $E=9$:

Each rectangle represents a solution. There are 26 in total. The solution on the top left, for example, is $(5,0,0,0,0,0,0,0,0,1)$.
Source: HyperPhysics.

Attempts
The equivalent problem for distinguishable particles is trivial if solved by the stars and bars method. The solution is given by:
$$\binom{E+N-1}{E}$$
For $N=6$ and $E=9$ it would be:
$$\binom{9+6-1}{9} = \frac{14!}{9!\;5!} = 2002$$
I don't know if this is relevant, but I noticed that $2002 = 77\times 26$, or $77$ times the number of solutions to the problem I want to solve.
There might not even be a closed formula. Many simple combinatorics problems don't seem to have a simple solution.
Maybe the problem can be solved by generating functions, as suggested by the answer to this related question, but I have no idea how that works.

A: You're right about there not being a closed form, but there being a generating function solution.
In combinatorics, the objects you are counting are called partitions, which are ways of writing one number as a sum of positive integers.
Interpret $n_k $ as the number of times the integer $k $ appears in the sum. Then
$$ \sum_{k =1}^E k \cdot n_k = E $$
means that the numbers sum up to $E $, so we are interested in partitions of $E $ (note that we can ignore $k=0$ here as it does not affect this sum).
The first condition, $\sum_{k=0}^E n_k = N $, or equivalently $\sum_{k=1}^E n_k \le N $, means that we are interested in partitions of $E $ with at most $N $ parts.
Now unfortunately there is no closed solution to this problem. There is, however, a generating function. We first make a transformation.
We claim that the number of partitions of $E $ into at most $N $ parts is the same as the number of partitions of $E $ into parts of size at most $N $. To see this, let $m_j = \sum_{k=j}^E n_k $ count the number of parts of size at least $j $. Clearly $m_j=0$ for $j>N $, and
$$ \sum_j m_j = \sum_j \sum_{k \ge j} n_k = \sum_k \sum_{j \le k} n_k = \sum_k k \cdot n_k, $$
so given our partition $(k \cdot n_k)_k $ [that is, $n_k$ copies of $k$ as $k$ ranges from $1$ to $E$] of $E $ with at most $N $ parts, we formed a partition $(m_j)_j $ of $E $ with parts of size at most $N $.  One can check that this is in fact a bijection, so we can count either type of partition.
Now for the generating function. A partition represents the (unordered) sum $m_1 + m_2 + ... + m_n = E$, where $n$ is the largest integer for which $m_j \ge 1$. One convenient way of representing such sums is through polynomial multiplication: $x^{m_1} \cdot x^{m_2} \cdot ... \cdot x^{m_n} = x^{E} $.
When multiplying out these monomials, we can group them together by their powers. So the terms with $m_j =1$ can be collected into the factor $x^{1 \cdot 0} + x^{1 \cdot 1} + x^{1 \cdot 2} + ... + x^{1 \cdot s_1} + ... $, where in $1 \cdot s_1$, the $1$ indicates we are dealing with parts of size $1$, and the $s_1$ keeps track of how many there are.  The cool thing is that this is a geometric series, so we have
$$ x^{1 \cdot 0} + x^{1 \cdot 1} + x^{1 \cdot 2} + ... + x^{1 \cdot s_1} + ... = \frac {1}{1-x^1}. $$
We can do this for every other part size, and the factor corresponding to the parts of size $j$ will be $\frac {1}{1-x^j} $.
Finally, to get the generating function, we multiply these factors together, because remember that adding the parts corresponds to multiplying the monomials. Since we only want parts of size up to $N $, we take the product over $1 \le j \le N $, giving
$$ F_N (x) = \prod_{j=1}^N (1-x^j)^{-1}. $$
This gives a power series, and the coefficient of $x^E $ counts the partitions of $E $ into parts of size at most $N $ (or, equivalently, with at most $N $ parts), which is what you are looking for.
Even more finally, what good is a generating function? Well, it gives a systematic way to approach these problems. Note that the function $F_N $ doesn't just encode the solution to your problem, but to the problem for every possible value of $E $, all at once! In practical terms, it gives an algorithm for finding the solution, since the power series can be computed efficiently. We humans can also use analytic tools to extract the asymptotics of the solution, although that is not something I can do off the top of my head, so I'll leave that part to someone else.


text:
Q: Change size of /root patition in ubuntu 16.04 LVM I installed ubuntu 16.04 with these settings
"Erase Disk and install Ubuntu" with "Use LVM with the new Ubuntu installation" checked
I have a 1tb hard drive and all that 1tb is now in the root partition excluding 4gb swap. How do I decrease the partition of root and make a new partition.

A: The first thing you should do is backup your most important data in case of a mistake.  Then use the LVM resize commands.
You can find images of procedures on this link:
How to Extend/REduce LVM's in Linux - Part II
The actuall commands to reduce the size are:
resize2fs - Reduce a file-system
lvreduce  - Reduce a Logical volume

For GUI you can try system-config-lvm from the Ubuntu repository.
You might consider installing Ubuntu on a Pen-drive.  Boot to the pen-drive then install the LVM gui on that drive and manage your hard drive from that session.

A: This has worked for me all days:
Check disk
e2fsck -ff /dev/vg0/test-disk

Resize filesystem to 4G:
resize2fs /dev/vg0/test-disk 4G

Check disk again just for the sake of it (first command).
Remember to backup important files.


text:
Q: Translate text to numbers with coordinates I thought of making something for fun today and decided to make a simple program that'll translate a peace of text into numbers. I tried this code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AlphaNumCrypt
{
public partial class Form1 : Form
{
    public String input;
    public String output;
    public Form1()
    {
        InitializeComponent();
    }

    private void translateButton_Click(object sender, EventArgs e)
    {
        // Encrypt/Decrypt input
        if (toText.Checked == true)
        {
            // Decrypt input
            input = "";
            input = inputTextBox.Text.ToString();
            decrypt();
        }
        else if (toAlphaNum.Checked == true)
        {
            // Encrypt input
            input = "";
            input = inputTextBox.Text.ToString();
            encrypt();
        }
    }

    private void encrypt()
    {
        // Encrypt the plain text input
        output = input;
        output.Replace("a", "11");
        output.Replace("b", "12");
        output.Replace("c", "13");
        output.Replace("d", "14");
        output.Replace("e", "15");
        output.Replace("f", "16");
        output.Replace("g", "17");
        output.Replace("h", "18");
        output.Replace("i", "19");
        output.Replace("j", "21");
        output.Replace("k", "22");
        output.Replace("l", "23");
        output.Replace("m", "24");
        output.Replace("n", "25");
        output.Replace("o", "26");
        output.Replace("p", "27");
        output.Replace("q", "28");
        output.Replace("r", "29");
        output.Replace("s", "31");
        output.Replace("t", "32");
        output.Replace("u", "33");
        output.Replace("v", "34");
        output.Replace("w", "35");
        output.Replace("x", "36");
        output.Replace("y", "37");
        output.Replace("z", "38");
        output.Replace("æ", "39");
        output.Replace("ø", "41");
        output.Replace("å", "42");
        outputTextBox.Text = output;
    }

    private void decrypt()
    {
        // Decrypt the AlphaNum input
        output = input;
        output.Replace("11", "a");
        output.Replace("12", "b");
        output.Replace("13", "c");
        output.Replace("14", "d");
        output.Replace("15", "e");
        output.Replace("16", "f");
        output.Replace("17", "g");
        output.Replace("18", "h");
        output.Replace("19", "i");
        output.Replace("21", "j");
        output.Replace("22", "k");
        output.Replace("23", "l");
        output.Replace("24", "m");
        output.Replace("25", "n");
        output.Replace("26", "o");
        output.Replace("27", "p");
        output.Replace("28", "q");
        output.Replace("29", "r");
        output.Replace("31", "s");
        output.Replace("32", "t");
        output.Replace("33", "u");
        output.Replace("34", "v");
        output.Replace("35", "w");
        output.Replace("36", "x");
        output.Replace("37", "y");
        output.Replace("38", "z");
        output.Replace("39", "æ");
        output.Replace("41", "ø");
        output.Replace("42", "å");
        outputTextBox.Text = output;
    }
}
}

But for some reason the output is equal to the input, what am I doing wrong here?
Regards,
Erik

A: It's because you don't use the result of the output.Replace method. It returns a new string and doesn't modify an existing. You should modify your code as follows:
output = output.Replace("a", "11");
...

UPDATE. To make a code more convenient you can store your conversion rules as the array of Tuple<string, string>. Thus you can use loops to encode and decode a text. Here is an example:
private readonly Tuple<string, string>[] rules = new[]
    {
        new Tuple<string, string>("a", "11"),
        new Tuple<string, string>("b", "12"),
        new Tuple<string, string>("c", "13"),
        ...
    };

private string Encrypt(string input)
{
    return rules.Aggregate(input, (current, rule) => current.Replace(rule.Item1, rule.Item2));
}

private string Decrypt(string input)
{
    return rules.Aggregate(input, (current, rule) => current.Replace(rule.Item2, rule.Item1));
}

A: You have to store the result returned by the output.Replace, something like:
output = input;
output = output.Replace("11", "a");
output = output.Replace("12", "b");
        ...
outputTextBox.Text = output;

A: The .Replace() method is non-destructive. It doesn't modify the original object. It only returns a new value based on the original with the function applied. So all you have to do is reassign the object to what is returned:
output = output.Replace("o", "26");

You may also consider creating a couple of dictionaries to handle the mapping and just loop through each letter instead of calling every letter whether it appears in the original string or not.

A: Just for completeness:
In your code use StringBuilder instead of string for output and input.
Then you would'nt have to reassign in all the replacement lines. Your code should work as -is. Just remove the output = input and input = output lines from the encrypt() and decrypt() functions
From MSDN:
Although StringBuilder and String both represent sequences of characters, they are implemented differently. String is an immutable type. That is, each operation that appears to modify a String object actually creates a new string.
For routines that perform extensive string manipulation (such as apps that modify a string numerous times in a loop), modifying a string repeatedly can exact a significant performance penalty. The alternative is to use StringBuilder, which is a mutable string class. Mutability means that once an instance of the class has been created, it can be modified by appending, removing, replacing, or inserting characters.


text:
Q: React router link keeps pushing to history same url? I'm using React Router 4. One concern I have is that if you use the <Link /> component to navigate between routes, lets say in your header, and you click on that same link again it will keep pushing the same url to browser history? Is there any way to prevent this behaviour, or is it completely up to me as developer to either replace that <Link /> with something something like a  element (if I dont want users to be able to click that link)?
Or should I do my own version of the <Link /> component and then inside that prevent from firing events when on the same route?

A: Yes, agree with @MaximeGirou. You can use your own trick.
Or another way is to define a class with some CSS properties [like cursor:not-allowed etc.] and give that class name in activeClassName attribute.
<NavLink to="/dashboard" activeClassName="linkActive">
    Dashboard
</NavLink>


text:
Q: How to fix these errors arising due to server blocking web scraping? I am trying to get the text from a web page using the "get_text" function as described here.
import urllib.request
from inscriptis import get_text

url = "http://www.informationscience.ch"
html = urllib.request.urlopen(url).read().decode('utf-8')

text = get_text(html)

print(text)

This works fine for this particular website, but when I try to scrape from another website, I get the 403 Error:
import urllib.request
from inscriptis import get_text

url = "https://economictimes.indiatimes.com/markets/stocks/news/birla-group-enters-the-fray-to-acquire-idbi-federal-life/articleshow/64251332.cms"
html = urllib.request.urlopen(url).read().decode('utf-8')

text = get_text(html)

print(text)

This gives the following error in the line html = urllib.request.urlopen(url).read().decode('utf-8'):
HTTPError: HTTP Error 403: Forbidden

I tried to fix it by specifying a user agent as follows:
import urllib.request
from inscriptis import get_text

url = "https://economictimes.indiatimes.com/markets/stocks/news/birla-group-enters-the-fray-to-acquire-idbi-federal-life/articleshow/64251332.cms"
html = urllib.request.urlopen(url, headers={'User-Agent': 'Mozilla/5.0'}).read().decode('utf-8')

text = get_text(html)

print(text)

but I get the following error:
TypeError: urlopen() got an unexpected keyword argument 'headers'

Since the error said headers is undefined for urlopen, I tried to specify the user agent with the requests module as follows:
from inscriptis import get_text
import requests
url = requests.get('https://economictimes.indiatimes.com/markets/stocks/news/birla-group-enters-the-fray-to-acquire-idbi-federal-life/articleshow/64251332.cms', "lxml", headers={'User-Agent': 'Mozilla/5.0'})

print(get_text(url))

But this gives the following error:
AttributeError: 'Response' object has no attribute 'strip'

How do I get this damn server to stop blocking my web crawls please?

A: You need to process the body of the response, not the response object itself:
response = requests.get('https://economictimes.indiatimes.com/markets/stocks/news/birla-group-enters-the-fray-to-acquire-idbi-federal-life/articleshow/64251332.cms', "lxml", headers={'User-Agent': 'Mozilla/5.0'})

print(get_text(response.text))


text:
Q: How to change start directory of an scheduled task with schtasks.exe in Windows programatically? I am trying to schedule a task with this command
SCHTASKS /Create  /TN MyTaks  /SC minute /MO 1 /TR "%cd%\myfile.exe"

I need Task Scheduler run my file inside current directory of myfile.exe.
How this can be done considering that I tested this command also.
SCHTASKS /Create  /TN MyTaks  /SC minute /MO 1 /TR "\%cd%"%cd%\myfile.exe"

A: I solved it with adding /V1
SCHTASKS  /Create /V1 /TN MyTask /SC minute /MO 1 /TR "%cd%\myfile.exe"


text:
Q: Pros/cons to using char for small integers in C Is there any disadvantage to using char for small integers in C? Are there any advantages other than the occupancy/memory benefit?
In particular, is the processor likely to cope with integer arithmetic on a char better or worse than it would on a (long/short) int?
I know this will be processor/system/compiler specific, but I'm hoping for an answer in the general case, or, at least, the general case for 32-bit Windows and Solaris, being the systems I'm currently working on. I'm also assuming that things like overflow/wraparound issues have already been dealt with.
Update: Visual Studio 6.0 doesn't actually have stdint.h as suggested by Christoph. A little benchmarking on Windows (VS 6.0, debug build, 32-bit) with a handful of stacked loops gives int and long as providing similar performance, which is about twice as fast as char. Running the same test on Linux with gcc similarly pegs int and long as similar, and both faster than char, although the difference is less pronounced.
As a side note, I've not spent much time looking, but the first implementation of stdint.h for VS 6.0 I found (via Wikipedia) defines uint_fast8_t as unsigned char, despite this seeming to be slower in my tests at least. Thus, the moral of the story, as Christoph rightly suggested: always benchmark!

A: Well, the first issue is that it's not defined by the C standard whether plain char is signed or unsigned - so the only range you can portably rely on is 0 to 127.
Other than that, in general int is supposed to be the type corresponding to the native word size of the architecture (but of course this isn't enforced by anything).  This would tend to be the type with the best arithmetic performance, but that's about all you can say.
Note that operands narrower than int are widened either to int or unsigned int during expression evaluation anyway.

A: Another con I can think of is that (as far as I know) "modern" processors do all their math in "full" integers, generally 32 bits. So dealing with a char usually means pulling a single byte out of memory, filling up with 0's in transferring to a register, doing something with it and then squeezing only the least significant bits of the result back into memory. Especially if the char is not aligned on a handy boundary, this memory access takes a lot more work to accomplish.
Using char for int is really only useful when you have a lot of numbers (i.e. a large array) and you need to conserve space.

A: Arithmetic on chars will almost certainly actually performed using the same registers as arithmetic on ints. For example:
char c1 = 1;
char c2 = c1 + 2;

The addition compiles to the following with VC++:
00401030   movsx       eax,byte ptr [ebp-4]
00401034   add         eax,2
00401037   mov         byte ptr [ebp-0Ch],al

where eax is a 32-bit register.
There is therefore no adavantage for using chars over ints when it comes to arithmetic performance.

A: Internally, processors generally perform arithmetic on machine words. This means that when calculations on other types are performed, although the calculation itself will take the same length of time, depending on the available instruction set extra work may have to be done to read inputs and to coerce calculation results into the target type (e.g. sign-extending/zero-filling, shifting/masking to avoid unaligned memory accesses, etc).
This is why C defines types and operations as it does - the size of int is not mandated by the standard, allowing compiler authors to make it correspond to a machine word, and expression evaluation is defined to promote smaller integer types to int, greatly reducing the number of points at which results must be coerced to some target type.
Valid reasons to use char for storing integer values are when the space really matters that much (not as often as you might think), and when describing some external data format / protocol that you are marshalling data to / from. Expect uses of char to incur a slight loss of performance, especially on hardware such as Cell SPU where only machine word size memory accesses are available so accessing a char in memory requires several shifts and masks.

A: C99 added so-called 'fastest' minimum-width integer types to solve this problem. For the range you're interested in, the types would be int_fast8_t and uint_fast8_t, which can be found in stdint.h.
Keep in mind that there might be no performance gain (the increase in memory consumption might even slow things down); as always, benchmark! Don't optimize prematurely or solely on potentially flawed assumptions of what should work.

A: The main con I would see is that your code is using a type that means one thing for values that mean something else -- e.g., there's a semantic problem which could be a maintenance problem. If you did it, I'd probably recommend typedefing it:
typedef char REALLYSHORT;

That way, A) It's clearer what you're doing, and B) You can change it easily (e.g., just the one place) if you run into trouble.
Do you have a really good reason not to use int?


text:
Q: MySQL join query for more than 1 id So i encountered this problem when I was specifying a query for 2 connected tables with more than 1 id.
Suppose there are 2 tables:
Table Competition

*

*p1_id(varchar)(FK)

*p2_id(varchar)(FK)

*p3_id(varchar)(FK)

table Competition refers to table Player by the player.id
Table Player

*

*id (PK)

*name

*level

*gender

The problem is I want to retrieve the p1 name, p2 name and p3 name from table Competition...

A: join the table player thrice to get it's equivalent values,
SELECT  a.*,
        b.name Player1_Name,
        c.name Player2_Name,
        d.name Player3_Name
FROM    Competition a
        INNER JOIN player b
            a.p1_ID = b.ID
        INNER JOIN player c
            a.p2_ID = c.ID
        INNER JOIN player d
            a.p3_ID = d.ID

If one of the columns in table competition is nullable, better use LEFT JOIN than INNER JOIN.
To fully gain knowledge about joins, kindly visit the link below:

*

*Visual Representation of SQL Joins


text:
Q: Trying to use quickselect by hand I have a sub array that is {8,9,7}. Assume the pivot that was picked is 8. Running Quickselect on this array is giving me some issue.
So the left pointer starts from the left looking for elements greater than 8 it finds 9. The right pointer starts from the right look for elements smaller than 8 it finds 7. 7 and 9 swap places. {8,7,9} now the left pointer finds 9 again and the right pointer finds 7. But now they have crossed each-other so we don't perform that swap. Instead the left pointer is swapped with the pivot creating the array {9,7,8} but this is not good since smaller elements are not to the left of the pivot now. So what did I do wrong?

A: This is much later, so you no doubt already figured it out, but for posterity:
The first part of your description above matches the first partition step in QuickSelect (or QuickSort) using a zero index (value 8 here) as the pivot.
The {8,7,9} variation is correct - the two parts {8,7} and {9} meet the partition criterion for a pivot value of 8. These are then recursively processed to complete the sort, if sorting. Of course, if you're (quick)selecting, you only process the part that the index you seek is in.
The left pointer is swapped with the pivot step does not apply here. You should only do that if you use the variation where you move the pivot to the front or the back, if it's not already there, and then exclude the pivot index from the partitioning process. Only if you did that would the pivot value need to be moved to the where the two partitions meet.


text:
Q: Authentication Microsoft OneDrive REST services Java/Ionic 2 I'm trying to authenticate to Microsoft OneDrive, with REST service, in my app, using Java for backend and Ionic 2. The authentication now works if I call my service directly from Chrome.
I post the code:
private static final String REDIRECT_URI = "http://localhost:8080/CloudToCloud/onedrive/getToken";

@RequestMapping(value = { "/getAccess" }, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public void authorizationFlow(HttpServletRequest request, HttpServletResponse response)
        throws IOException, InterruptedException {
    try {
        String authURL = "https://login.live.com/oauth20_authorize.srf?client_id=" + CLIENT_ID
                + "&scope=wl.signin%20wl.basic%20wl.offline_access%20wl.skydrive_update&response_type=code&redirect_uri="
                + REDIRECT_URI;
        response.sendRedirect(authURL);
    } catch (Exception e) {
        logger.severe(e.getMessage());
    }
}

@RequestMapping(value = { "/getToken" }, params = { "code" }, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<JSONObject> getToken(@RequestParam("code") String code)
        throws IOException, InterruptedException, ParseException {
    JSONObject json = null;
    try {
        logger.info("Auth CODE: " + code);
        String url = "https://login.live.com/oauth20_token.srf";
        URL obj = new URL(url);
        HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

        con.setRequestMethod("POST");
        con.setRequestProperty("User-Agent", "Mozilla/5.0");
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

        String urlParameters = "client_id=" + CLIENT_ID + "&" + "redirect_uri=" + REDIRECT_URI + "&"
                + "client_secret=" + SECRET + "&" + "code=" + code + "&" + "grant_type=authorization_code";
        logger.info(url + urlParameters);

        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

        int responseCode = con.getResponseCode();
        logger.info("REQUEST SENT. Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        String risposta = response.toString();
        JSONParser parser = new JSONParser();
        json = (JSONObject) parser.parse(risposta);
        String token = json.get("access_token").toString();

        FileWriter file = new FileWriter(DATA_STORE_DIR);
        file.write(json.toJSONString());

        logger.info("\nTOKEN:\n" + token);

        file.flush();
        file.close();
        return new ResponseEntity<JSONObject>(json, HttpStatus.OK);
    } catch (Exception e) {
        logger.info("ERRORE: " + e.getMessage());
        return new ResponseEntity<JSONObject>(HttpStatus.BAD_REQUEST);
    }
}

I call the first service, I get a code, and I make a redirect on the second service, which provides me a json with the token, to be used for all other calls. Up to this everything works.
The problem comes using Ionic 2. I post the code:
The service:
getAuthOneDrive(){
  var url = 'http://localhost:8080/CloudToCloud/onedrive/getAccess';
  var response = this.http.get(url).map(res => res.json());
  return response;
}

The component:
getAuthOneDrive(){
  this.cloudServiceAuthentication.getAuthOneDrive().subscribe(
    err => {
      console.log(err);
    },
    () => console.log('getAuthOneDrive Complete')
  );
}

And my proxy, that I've configured in ionic.config.json:
{
  "name": "C2C",
  "app_id": "c6203dd8",
  "v2": true,
  "typescript": true,
  "proxies": [
    {
      "path": "/",
      "proxyUrl": "http://localhost:8080/"
    }
  ]
}

If I try to call the same service (http://localhost:8080/CloudToCloud/onedrive/getAcces), from the app in Ionic2, by a click on a button, I get this error.
XMLHttpRequest cannot load http://localhost:8080/CloudToCloud/onedrive/getAccess. Redirect from 'http://localhost:8080/CloudToCloud/onedrive/getAccess' to 'https://login.live.com/oauth20_authorize.srf?client_id=ae9573ba-6bc0-4a87-8…ype=code&redirect_uri=http://localhost:8080/CloudToCloud/onedrive/getToken' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access.

I really tried everything. If someone can give me a help I would be grateful. Thanks! ;)
EDIT:
This is what I've tried to do:
1- add "'Access-Control-Allow-Origin', '*' header, I've got this error:
XMLHttpRequest cannot load http://localhost:8080/CloudToCloud/onedrive/getAccess. Redirect from 'http://localhost:8080/CloudToCloud/onedrive/getAccess' to 'https://login.live.com/oauth20_authorize.srf?client_id=ae9573ba-6bc0-4a87-8…ype=code&redirect_uri=http://localhost:8080/CloudToCloud/onedrive/getToken' has been blocked by CORS policy: Request requires preflight, which is disallowed to follow cross-origin redirect.

2- do not use response.sendRedirect in the first service, but satisfy the request with HttpsURLConnection or Spring RestTemplate;
3- trying to call the Microsoft service directly from Ionic;
4- use the Spring annotation @CrossOrigin, but I've got the same error.

A: Cross-origin requests are restricted by the browser for security reasons.  Take a look at HTTP access control (CORS) for a detailed explaination of how this works.
Setting the following header should allow you to work around the issue in development:
Access-Control-Allow-Origin: *

Just make sure you remove this header (or at least restrict it beyond '*') in your production deployment.

A: I solved by modifying the first service /getAccess, adding the header Access-Control-Allow-Origin and using my REDIRECT_URI and no longer the sendRedirect which gave problems.
@CrossOrigin(origins = "*")
@RequestMapping(value = { "/getAccess" }, method = RequestMethod.GET)
public void authenticate() throws IOException {
    try {
        OneDriveSDK sdk = OneDriveFactory.createOneDriveSDK(CLIENT_ID, SECRET, REDIRECT_URI,
                OneDriveScope.READWRITE);
        String url = sdk.getAuthenticationURL();
        logger.info(url);
        openWebpage(url);
        URL obj = new URL(url);
        HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
        con.setRequestMethod("GET");
        con.setRequestProperty("Access-Control-Allow-Origin", "*");
        con.setDoOutput(true);
        int responseCode = con.getResponseCode();
        logger.info("REQUEST SENT. Response Code : " + responseCode);
    } catch (Exception e) {
        e.printStackTrace();
    }
}


text:
Q: Share the results of a mySQL to all active sessions I am looking to make my web app adjust itself depentent on the mysql serves load. To do this I am using this query.
SELECT (COUNT(*)-1) P.QUERYCOUNT, SUM(P.TIME) QUERYTIME
FROM information_schema.PROCESSLIST P
WHERE P.COMMAND = 'Query'

However it does not make much sense for all the active sessions to run this query incrementally. Instead it seems more logical for a cron job to save the results to a flat file for the others to read incrementally.
Is this the best way to share out the results or is there a better solution?

A: If you want to share the results inside of MySQL than you will probably have to create a table to store it.
MySQL does not support global user variables as far as I know.
However... you could also do this from php ofcourse.


text:
Q: Showing $X^*$ is separable implies $X$ is separable using the Riesz lemma
If $X$ is a Banach space and $X^*$ is separable, then $X$ is
  separable.

Here, David Mitra mentions a proof using the Riesz lemma. However, I do not fully understand it.

You could also use Riesz' lemma:
Let $Y$ be a  proper closed subspace of the normed space $X$ and
  $0<\theta<1$. Then there is an $x_\theta$ of norm 1 for which $\Vert
 x_\theta-y\Vert>\theta$ for all $y\in Y$.
If $X$ were not seperable, you could use Hahn Banach to   construct
  uncountably many functionals $f_\alpha\in X^*$ with  $\Vert
 f_\alpha-f_\beta\Vert\ge \theta$ whenever $\alpha\ne\beta$.

If $X$ is not separable, why does that allow us to construct uncountably many separated functionals $f_\alpha$?
I see why this fact would imply the theorem. Taking a countable dense set and $\epsilon$ balls around each point in that set, we see that two elements of the uncountable set $\{ f_\alpha\}$ must lie in a single ball. But then they are at most $2\epsilon$ apart. Making $\epsilon$ small shows we can find two elements of the set less than $\theta$ apart, a contradiction.

A: Here is my favorite proof, which I think is simpler than both the one suggested by David C. Ullrich and the one I had given earlier, elaborating on David Mitra's hint. It uses only the Hahn–Banach theorem, but not Riesz's lemma. It is based on the hint presented in Exercise 5.25, Folland (1999, p. 160).
If $X^*$ is separable, let $\{f_n\}_{n\in\mathbb N}$ be a countable dense subset of it. By the definition of the operator norm $$\|f_n\|\equiv\sup_{\substack{x\in X\\\|x\|\leq 1}}|f_n(x)|,$$ it is possible, for each $n\in\mathbb N$, to choose some $x_n\in X$ such that $\|x_n\|\leq 1$ and $$|f_n(x_n)|\geq\frac{1}{2}\|f_n\|\tag{$\clubsuit$}$$ (if $f_n=0$, then simply choose $x_n=0$; if $\|f_n\|>0$, use the definition of the supremum).
Let $C\equiv\{x_1,x_2,\ldots\}$. I claim that $\operatorname{span} C$ is dense, which implies that $X$ is separable (see the last claim in my previous post). To see this, suppose, for the sake of contradiction, that $\operatorname{span} C$ is not dense; then $Y\equiv\overline{\operatorname{span} C}$ is a proper closed subspace. By the Hahn–Banach theorem, it is possible to choose $f\in X^*$ such that
\begin{align*}
f(y)=&\,0\quad\forall y\in Y,\\
\|f\|=&\,1;
\end{align*}
see again Theorem 5.8(a) in Folland (1999, p. 159). Since $\{f_n\}_{n\in\mathbb N}$ is dense in $X^*$, there exists some $n\in\mathbb N$ such that $\|f_n-f\|< 1/3$. But then
\begin{align*}
|f_n(x_n)|=|f_n(x_n)-\underbrace{f(x_n)}_{=0}|\leq\|f_n-f\|<\frac{1}{3},\tag{$\diamondsuit$}
\end{align*}
whereas
\begin{align*}
1=\|f\|\leq\|f-f_n\|+\|f_n\|<\frac{1}{3}+\|f_n\|,
\end{align*}
so that $\|f_n\|>2/3$. Putting this into ($\diamondsuit$),
$$|f_n(x_n)|<\frac{1}{3}<\frac{1}{2}\|f_n\|,$$ which contradicts ($\clubsuit$).

A: Third version - maybe this one is right.
Lemma. If $K$ is a separable compact Hausdorff space then $C(K)$ is separable. (And it follows that $K$ is metrizable, but we won't be using that.)
Proof. Wlog $K$ is infinite. Say $p_1,\dots$ are dense, $p_j\ne p_k$ for $j\ne k$. Choose  $f_{j,k}:K\to\Bbb R$, such that $f_{j,k}(p_j)\ne f_{j,k}(p_k)$. The algebra generated by $1$ and the $f_{j,k}$ is separable, and Stone-Weierstrass shows it's dense in $C(K)$.
Now suppose $X^*$ is separable, and let $K$ be the closed unit ball of $X^*$ with the weak* topology. The lemma implies that $C(K)$ is separable.
But the map $x\mapsto f_x$, where $f_x(x^*)=x^*(x)$, is an isometry from $X$ into $C(K)$. So $X$ is separable.

A: Suppose that $X$ is not separable and fix $\theta\in(0,1)$. Let $\Omega$ be the set of countable ordinals. Fix $\alpha\in\Omega$ and using transfinite induction, suppose that $x_{\beta}\in X$ and $f_{\beta}\in X^*$ have already been defined for all $\beta\in\Omega$ such that $\beta<\alpha$ (if $\alpha=\min\Omega$, simply define $x_{\alpha}\equiv0$ and $f_{\alpha}\equiv 0$).
Let $$X_{\alpha}\equiv\{x_{\beta}\,|\,\beta\in\Omega,\,\beta<\alpha\}.$$
Since $X_{\alpha}$ is countable and $X$ is not separable, it follows that $Y_{\alpha}\equiv\overline{\operatorname{span}X_{\alpha}}$ is a proper closed subspace (I will prove this at the end of the post). Pick any $x_{\alpha}\in X\setminus Y_{\alpha}$ such that
\begin{align*}
\|x_{\alpha}\|=&\,1,\\
\inf_{y\in Y_{\alpha}}\|x_{\alpha}-y\|\geq&\,\theta,
\end{align*} which is possible by Riesz's lemma. Now, using the Hahn—Banach theorem, there exists $f_{\alpha}\in X^*$ such that
\begin{align*}f_{\alpha}(y)=&\,0\quad\forall y\in Y_{\alpha},\\
\|f_{\alpha}\|=&\,1,\\
f_{\alpha}(x_{\alpha})=&\,\inf_{y\in Y_{\alpha}}\|x_{\alpha}-y\|\geq\theta;
\end{align*}
see, for example, Theorem 5.8(a) in Folland (1999, p. 159).
Now, the family $\{f_{\alpha}\}_{\alpha\in\Omega}$ is uncountable (given that $\Omega$ is uncountable and, as the next argument will reveal, $f_{\alpha}$ and $f_{\beta}$ are distinct for distinct $\alpha,\beta\in\Omega$). Suppose that $\alpha,\beta\in\Omega$ and $\alpha\neq\beta$. Without loss of generality, assume that $\beta<\alpha$. Then, $x_{\beta}\in X_{\alpha}\subseteq Y_{\alpha}$, so $f_{\alpha}(x_{\beta})=0$. Also, $f_{\beta}(x_{\beta})\geq\theta$. Therefore, $$\|f_{\alpha}-f_{\beta}\|=\sup_{\substack{x\in X\\\|x\|\leq1}}|f_{\alpha}(x)-f_{\beta}(x)|\geq|f_{\alpha}(x_{\beta})-f_{\beta}(x_{\beta})|\geq\theta.$$

The following claim reveals that if $X$ is not separable, then the subspace $\operatorname{span} X_{\alpha}$ is not dense for any $\alpha\in\Omega$.

Claim: If $C\equiv\{x_1,x_2,\ldots\}\subseteq X$ is a countable subset and $\operatorname{span}C$ is a dense subspace, then $X$ is separable.

Proof: Let $\mathbb S$ be a countable dense subset of the underlying field ($\mathbb R$ or $\mathbb C$, presumably). Define, for each $n\in\mathbb N$, $$L_n\equiv\{q_1 x_1+\ldots+q_n x_n\,|\,q_1,\ldots,q_n\in\mathbb S\}$$ and $L\equiv\bigcup_{n=1}^{\infty} L_n$. It is easy to see that $L$ is countable.
I claim that $L$ is dense. To see this, pick any $x\in X$ and $\varepsilon>0$. Since $\operatorname{span} C$ is dense, there exist some $n\in\mathbb N$ and members of the underlying field $p_1,\ldots,p_n$ such that $$\left\|x-\sum_{m=1}^np_mx_m\right\|<\frac{\varepsilon}{2}.$$ Now, for each $m\in\{1,\ldots, n\}$, pick $q_m\in\mathbb S$ such that $$|p_m-q_m|<\frac{\varepsilon}{2n(\|x_m\|+1)}.$$ Then, $y\equiv\sum_{m=1}^n q_m x_m\in L$ and $$\|x-y\|\leq\left\|x-\sum_{m=1}^np_mx_m\right\|+\left\|\sum_{m=1}^n(p_m-q_m)x_m\right\|<\frac{\varepsilon}{2}+\sum_{m=1}^n|p_m-q_m|\|x_m\|<\frac{\varepsilon}{2}+\frac{\varepsilon}{2}=\varepsilon.$$ Hence, $x\in\overline{L}$ and the proof is complete. $\quad\blacksquare$


text:
Q: AST for UML Activity diagram I am currently doing a project to convert uml diagrams to java code,in one of the step I have to create an ast for general activity diagram and write a java code for the ast. The problem is I am not sure how to represent it in java code to accept any activity diagram as an input. Please need some help.
This is the meta-model of a general activity diagram, I want to represent this diagram as a java code to accept inputs.
Activity Diagram Metamodel
The first diagram on the second page of the pdf

A: What tool are you using to create your activity diagrams?  Most will provide an API to query models and/or an XMI export*.  In either case you don't get an AST as such, more an Object structure of your model.  But it's still pretty easy to iterate that structure and generate code.
One option worth considering is the Eclipse Modeling Framework (EMF).  There are tools available for both creating diagrams (e.g. Papyrus) and a multitude of options for generating code from models (e.g. Acceleo) - have a look at the 'Model to Text' (M2T) sub-project.
Even if you decide to use another tool for diagram creation, it's possible to use Eclipse M2T for code generation; most tools will export XMI in the eclipse dialect.
hth.
--
*XMI is the 'standard' for UML model interchange.  It was plagued with inconsistency in interpretation originally, and there are still some problems among tools today.  However: it is an XML dialect so even if tool B can't directly import XMI from tool A, it's usually possible to convert between the two.


text:
Q: Three or more backgrounds stacked CSS I'm trying to have three backgrounds stacked under each other using CSS but only two appear at maximum. Basically I want to make something like this:

Here is the code I'm using:
body{
  font-size: 100%;
  background-image: url(ex1.png), url(ex2.png), url(ex3.png);
  background-repeat: no-repeat;
}

Is there any simple way to achieve this result using the body or am I forced to use divs instead?

A: When you set multiple images on a single element without specifying the background-position, they all are placed on the same position and so they will be one below the other. As long as the images are of the same size only one will show. If the images are of different size, say first is 100px tall, second is 200px, third is 300px then for the first 100px the first image will show up, for 100 - 200px the bottom of second image will show and for 200-300px the last third of the final image will show up.
Here is how you can stack the images within a single element.

*

*If all three images are same height then just mention background-position: top,center,bottom. This setting means the top of the first image will be aligned with top of the container, second one's center will be aligned with center of container and third one's bottom will be at container's bottom.

*If the images are of different height then the above approach will not work as-is, the positions will have to be set in actual pixels values such that the position of the second and subsequent image are offset by the sum total of heights of previous image. So, the background-position should be like 0px 0px, 0x [height of image1], 0px [height of image1 + height of image2]. This can still be done with percentages (to make it work for image of any size) but it would need algebraic equations to be used because of how background-positioning with percentages works.

Note: Height of the element should be equal to the height of all three images put together for all of them to show up completely.

div {
  height: 300px;
  width: 100px;
  background-image: url(http://lorempixel.com/100/100/nature/1), url(http://lorempixel.com/100/100/nature/2), url(http://lorempixel.com/100/100/nature/3);
  background-repeat: no-repeat;
  border: 1px solid;
  }
.bg-stack-with-pos {
  background-position: top, center, bottom;
}
.bg-stack-without-pos-diff-height {
  background-image: url(http://lorempixel.com/100/100/nature/1), url(http://lorempixel.com/100/200/nature/2), url(http://lorempixel.com/100/300/nature/3);
}
.bg-stack-with-pos-diff-height {
  height: 600px;
  background-image: url(http://lorempixel.com/100/100/nature/1), url(http://lorempixel.com/100/200/nature/2), url(http://lorempixel.com/100/300/nature/3);
  background-position: 0px 0px, 0px 100px, 0px 300px;

}

Stacked Images with Background Position - One below the other

Stacked Images w/o Background Position - One behind the other

Stacked Images w/o Background Position and different heights - One below the other

Stacked Images w/o Background Position and different heights - One behind the other


text:
Q: Base64 / SVG HTML image is not displayed I tried to use this icon
<img src="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4NCjwhLS0gR2VuZXJhdG9yOiBBZG9iZSBJbGx1c3RyYXRvciAxNi4wLjAsIFNWRyBFeHBvcnQgUGx1Zy1JbiAuIFNWRyBWZXJzaW9uOiA2LjAwIEJ1aWxkIDApICAtLT4NCjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+DQo8c3ZnIHZlcnNpb249IjEuMSIgaWQ9IkxheWVyXzEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93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NCgk8cGF0aCBkPSJNNjguNzM0LDgwLjloNDkuOTU4YzAuODA3LDAsMS40Ni0wLjY1MywxLjQ2LTEuNDZWMTcuNTM0YzAtMC44MDYtMC42NTMtMS40NTktMS40Ni0xLjQ1OWgtMTQuNTI0VjkuOTYxDQoJCWMwLTAuODA3LTAuNjUzLTEuNDYtMS40Ni0xLjQ2aC0xOWMtMC44MDcsMC0xLjQ2LDAuNjUzLTEuNDYsMS40NnY2LjExNUg2OC43MzRjLTAuODA3LDAtMS40NiwwLjY1My0xLjQ2LDEuNDU5Vjc5LjQ0DQoJCUM2Ny4yNzQsODAuMjQ3LDY3LjkyNyw4MC45LDY4LjczNCw4MC45eiBNODYuNjM4LDEyLjg5aDEzLjEzOXYzLjE4Nkg4Ni42MzhWMTIuODl6Ii8+DQo8L2c+DQo8L3N2Zz4NCg==5324e483b5f25ab4badb7c52c102103e"/>

from this page
http://www.flaticon.com/free-icon/baggage-on-conveyor-band_48876
I just copy and paste the html code (Base64 / svg)  into my website.
But the icon is not displayed. why?
Here is an example
http://jsfiddle.net/Lsr4s/
UPDATE:
I dont get it. I copy another image/icon and it is broken too, but the base64 code has no "=" jsfiddle.net/TYb59 Is the flatIcon.com page so buggy?
Can I fix this images/icons?

A: The base64 code that you have copied is broken. Close to the end there is == in the middle of the code. That is a filler that is placed at the end of a base64 code.
Remove the part after ==, and it will work fine.
<img src="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4NCjwhLS0gR2VuZXJhdG9yOiBBZG9iZSBJbGx1c3RyYXRvciAxNi4wLjAsIFNWRyBFeHBvcnQgUGx1Zy1JbiAuIFNWRyBWZXJzaW9uOiA2LjAwIEJ1aWxkIDApICAtLT4NCjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZC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jk5LTEuNTYzLTEuNTYyLTEuNTYzaC0zLjU4MmMtMC44NjMsMC0xLjU2MiwwLjY5OS0xLjU2MiwxLjU2M3Y0LjAwNg0KCQlIMTAuNTQ0VjQyLjY3OHoiLz4NCgk8cGF0aCBkPSJNNjguNzM0LDgwLjloNDkuOTU4YzAuODA3LDAsMS40Ni0wLjY1MywxLjQ2LTEuNDZWMTcuNTM0YzAtMC44MDYtMC42NTMtMS40NTktMS40Ni0xLjQ1OWgtMTQuNTI0VjkuOTYxDQoJCWMwLTAuODA3LTAuNjUzLTEuNDYtMS40Ni0xLjQ2aC0xOWMtMC44MDcsMC0xLjQ2LDAuNjUzLTEuNDYsMS40NnY2LjExNUg2OC43MzRjLTAuODA3LDAtMS40NiwwLjY1My0xLjQ2LDEuNDU5Vjc5LjQ0DQoJCUM2Ny4yNzQsODAuMjQ3LDY3LjkyNyw4MC45LDY4LjczNCw4MC45eiBNODYuNjM4LDEyLjg5aDEzLjEzOXYzLjE4Nkg4Ni42MzhWMTIuODl6Ii8+DQo8L2c+DQo8L3N2Zz4NCg=="/>

Demo: http://jsfiddle.net/Lsr4s/2/
Edit:
Downloading the svg file from the site and base64 encoding it gives exactly the same result. If there is no signature that you can use to easily fix the code, that is what you would need to do.
I used C# code like this to base64 encode the image to a text file:
File.WriteAllText(@"d:\temp\baggage19.txt", Convert.ToBase64String(File.ReadAllBytes(@"d:\temp\baggage19.svg")));

A: So, after trying a few things (I really needed to display SVG as src="data:"). I came across a couple key points:

*

*You don't have to encode it as base64, pure svg can be used, this makes it much more readable, as well as smaller both in length and after gzip. It's also much easier to test/debug/edit.

*It is imperitive to have the xmlns attribute in the svg tag regardless of whether you use base64, or utf8. That was the piece that eluded me the most.

Now without further ado, a simple example:
<img src="data:image/svg+xml;utf8, <svg xmlns='http://www.w3.org/2000/svg'><line x1='0' y1='0' x2='200' y2='200' style='stroke:rgb(255,0,0);stroke-width:2'/></svg>" />

For completeness: http://jsfiddle.net/y1akw1fd/

A: I had a similar problem today and came to the following conclusion:
Usage of the <embed> tag as described here had the best compatibility over the tested browsers (Firefox, Safari, Chrome on Mac OS). The above code would be written as:
<embed src="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4NCjwhLS0gR2VuZXJhdG9yOiBBZG9iZSBJbGx1c3RyYXRvciAxNi4wLjAsIFNWRyBFeHBvcnQgUGx1Zy1JbiAuIFNWRyBWZXJzaW9uOiA2LjAwIEJ1aWxkIDApICAtLT4NCjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+DQo8c3ZnIHZlcnNpb249IjEuMSIgaWQ9IkxheWVyXzEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIHg9IjBweCIgeT0iMHB4Ig0KCSB3aWR0aD0iMTI2cHgiIGhlaWdodD0iMTI2cHgiIHZpZXdCb3g9IjAgMCAxMjYgMTI2IiBlbmFibGUtYmFja2dyb3VuZD0ibmV3IDAgMCAxMjYgMTI2IiB4bWw6c3BhY2U9InByZXNlcnZlIj4NCjxnPg0KCTxyZWN0IHg9IjEuMDk1IiB5PSI5OC4yMjQiIHdpZHRoPSIxMjMuODEiIGhlaWdodD0iMTkuMjc1Ii8+DQoJPHJlY3QgeD0iMS4wOTUiIHk9Ijg1Ljc0IiB3aWR0aD0iMTIzLjgxIiBoZWlnaHQ9IjUuMjA1Ii8+DQoJPHBhdGggZD0iTTE4LjQwNCw5NS43MjFjMC43NjcsMCwxLjM4OS0wLjYyMywxLjM4OS0xLjM5cy0wLjYyMi0xLjM4OC0xLjM4OS0xLjM4OEgzLjQ4MWMtMC43NjcsMC0xLjM4OCwwLjYyMS0xLjM4OCwxLjM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kJYzAtMC44NjEtMC42OTgtMS41NjItMS41NjEtMS41NjJIMjMuNDI4Yy0wLjg2MywwLTEuNTYyLDAuNy0xLjU2MiwxLjU2MnY2LjU0SDcuNDFjLTAuODYyLDAtMS41NjIsMC43LTEuNTYyLDEuNTYzdjM5Ljc5NQ0KCQlDNS44NDgsODAuMjAxLDYuNTQ3LDgwLjksNy40MSw4MC45eiBNMzQuNDkyLDU3Ljg3NGgtMS43OTZ2LTYuNzY4aDEuNzk2VjU3Ljg3NHogTTI2LjU2MywzNC41NzRoMTQuMDU1djMuNDA2SDI2LjU2M1YzNC41NzR6DQoJCSBNMTAuNTQ0LDQyLjY3OGg0Ny4xNzN2MTEuOThIMzYuOTQydi00LjAwNmMwLTAuODYzLTAuNjk5LTEuNTYzLTEuNTYyLTEuNTYzaC0zLjU4MmMtMC44NjMsMC0xLjU2MiwwLjY5OS0xLjU2MiwxLjU2M3Y0LjAwNg0KCQlIMTAuNTQ0VjQyLjY3OHoiLz4NCgk8cGF0aCBkPSJNNjguNzM0LDgwLjloNDkuOTU4YzAuODA3LDAsMS40Ni0wLjY1MywxLjQ2LTEuNDZWMTcuNTM0YzAtMC44MDYtMC42NTMtMS40NTktMS40Ni0xLjQ1OWgtMTQuNTI0VjkuOTYxDQoJCWMwLTAuODA3LTAuNjUzLTEuNDYtMS40Ni0xLjQ2aC0xOWMtMC44MDcsMC0xLjQ2LDAuNjUzLTEuNDYsMS40NnY2LjExNUg2OC43MzRjLTAuODA3LDAtMS40NiwwLjY1My0xLjQ2LDEuNDU5Vjc5LjQ0DQoJCUM2Ny4yNzQsODAuMjQ3LDY3LjkyNyw4MC45LDY4LjczNCw4MC45eiBNODYuNjM4LDEyLjg5aDEzLjEzOXYzLjE4Nkg4Ni42MzhWMTIuODl6Ii8+DQo8L2c+DQo8L3N2Zz4NCg==5324e483b5f25ab4badb7c52c102103e"/>

A: did not displayed,  according to https://www.base64decode.org/ your  base64 contains error
in the end you add ==5324e483b5f25ab4badb7c52c102103e - that had an incorrect data !
So i advise you use some tool to correctly convert image data  to base64 string. like in  https://www.base64encode.org/  and all will be ok !

A: I would recommend downloading the image. Upload it yourself and putting it with the link.
Look at my comment above. Not letting me post jsfiddle..


text:
Q: Mac OSX LaunchDaemon on Startup, Shell Script with SSH I'm hoping someone can help me with this. I've been working on it literally all day...
I want a LaunchDaemon to execute a shell script at startup. Here is my plist file, located at /Library/LaunchDaemons/com.mhi.backup.plist:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.mhi.backup</string>
  <key>UserName</key>
  <string>Joel</string>
  <key>GroupName</key>
  <string>Admin</string>
    <key>ProgramArguments</key>
    <array>
        <string>/usr/local/bin/mhi_websites_backup.sh</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
</dict>
</plist>

It executes correctly when I load it from the terminal (launchctl load /Library/LaunchDaemons/com.mhi.backup.plist), but not on startup.
Here is my script, for reference:
#!/bin/bash
sleep 15 #delay script to ensure time for network connection
ssh user@hostname << HERE
  mysqldump -u <user_name> -pPASSWORD --all-databases | lzma > alldatabases.sql.lzma
  tar cfa backup-`date '+M%mD%dY%y'`.tar.lzma webapps alldatabases.sql.lzma
  exit
HERE
scp user@hostname:backup-`date '+M%mD%dY%y'`.tar.lzma /Users/Joel/Desktop

Could someone please help?
Thanks so much,
JG

A: What errors are you seeing? I would expect that you may have a PATH problem here. Where is mysqldump? If it's in /usr/local/bin, then you probably want to make that explicit, or set the default path in /etc/launchd.conf.

A: Is the plist owned by root? If a plist in /Library/Launch{Agents,Daemons}/ is not owned by root, it can be loaded with launchctl without sudo, but it is not loaded at login.
You could also try moving the plist to /Library/LaunchAgents/ and adding a LimitLoadToSessionType key:
<key>LimitLoadToSessionType</key>
<array>
  <string>LoginWindow</string>
  <string>Aqua</string>
</array>

See the Daemons and Agents tech note.


text:
Q: React can't read property of undefined, even though I can see value at console, and it changes the name of the component to  I'm trying to display a prop of an element ( I can see it in console)
 the child element (I'm using react materialize):
export default class MyLastWorkout extends React.Component {
   render(){
      return (
        <Card results ={this.props.results}
          className='blue-grey darken-1'
          textClassName='white-text'
          title='Card title'
          actions={[This is a link]}
        >

            { this.props.results[0].exercise}

        </Card>
      )
   }

React changes element to <e> and even though I see props at console, I can't get them  in
! I've also tried to use simple div instead, but it didn't work.
Parent Element:
var Exercises = React.createClass({

  getInitialState: function(){
    return {
      exercise: "",
      type: "",
      weight: "",
      sets: "",
      reps: "",
      searchTerm: "",
      results: [],
      history: []
    }
  },

  getResults: function(){
    return axios.get('/exercisesadd')
    .then(function(response){
      return response;
    });
  },

  render: function() {
    return (

        <LastWorkout/>

    );
  }
});


text:
Q: multiple ports server not getting all transmissions I wrote a single threaded server in c under linux,
this server listens to multiple ports,the server supposed to get text messages,
I use this code to listen to the sockets:
while(1){
FD_ZERO(&socks);
for (i = 0 ; i < IndexConnctedSocket ; i++ )
    FD_SET(newSocketFds[i],&socks);

readsocks = select(highNewSocket + 1,&socks,(fd_set*) 0,
        (fd_set*) 0 ,&timeout);

    for (j = 0 ; j <= index ; j++ ){
        if ( FD_ISSET(newSocketFds[j],&socks) != 0 ){
            bzero(buffer, 2048);
            n = read(newSocketFds[j], buffer, 2048);
            if (n < 0)
                error("ERROR reading from socket");
            i = 0;

            n = write(newSocketFds[j], "I got your message  ",18);
            if (n < 0)
                error("ERROR writing to socket");
            }
}

but when i send messages to the server (via a client that connects to all the sockets) some of the messages are lost,and when i connect from different clients to the server this works perfectly.

A: TCP does not have messages, so multiple "messages" can be obtained in one read().
Try checking the result (n) of your read() call.
You could check the buffer with
printf("read(%d): %*.*s\n", n, n, n , buffer);


text:
Q: How to remove spaces from list of integers? My question seems to be very simple, but I still don't find the right answer for me. Maybe, if I am writing the specific explanation somebody can help me out.
So following case:
I have this list a (if I do print(type(a)) it will also return "class list"), which I have manually inserted into the script. Unfortunately if I do this programmatically it will always return list b in the example, which then isn't recognized correctly by the following program.
a = [1,2,3,4,5,6,7,8,9,10]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

My question is: How do I remove the spaces in list b to be like list a?

A: If the lazy automatic formatting doesn't suit your needs, then do it yourself:
print( '[' + (','.join(str(i) for i in b)) + ']' )

A: You can convert list to a string and then use the replace function to replace all ', ' to ','.
a = [1, 2, 3]
new_list = str(a)
print(new_list.replace(", ", ","))


text:
Q: ambiguity of `<<-` when defining it for `x < y <- z` @g-grothendieck's answer to this question inspired me to play with some assignment functions such as ==<- or ><-.
See the following :
`><-` <- function(e1,e2,value) replace(e1, e1 > e2, value)
x <- c(5,15)
x > 10 <- 42
x
# [1]  5 42

I can also define it for < :
`<<-` <- function(e1, e2, value) replace(e1, e1 < e2, value)
x <- c(5,15)
x < 10 <- 42
x
# [1] 42 15

But the problem is that now the <<- operator is redefined and this doesn't work anymore :
x <<- "hello"

Error in replace(e1, which(e1 < e2), value) :    argument "value" is
  missing, with no default

Interestingly x < y <- z calls <<- even when it's not been overwritten.
rm(`<<-`)
x < 10 <- 42

Error in x < 10 <- 42 : incorrect number of arguments to "<<-"

Would there be a way to keep the original behavior of <<- while still defining this custom behavior ?

A: This seems to work :
`<<-` <- function(e1, e2, value){
  if(missing(value))
    eval.parent(substitute(.Primitive("<<-")(e1, e2)))
  else
    replace(e1, e1 < e2,value)
}

x <- c(5,15)
x < 10 <- 42
x
# [1] 42 15

x <<- "hello"
x
# [1] "hello"


text:
Q: How to execute gcloud build trigger using curl in us-central1 region? In Google Cloud Build I select Triggers -> Create Trigger. For region I use us-central1. Event: Webhook Event.
Webhook URL preview shows me the following url:
https://cloudbuild.googleapis.com/v1/projects/PROJECT_ID/triggers/TRIGGER_NAME?key=XXXXXXXX&secret=XXXXXXXX

When I try to curl it I got:
{
  "error": {
    "code": 404,
    "message": "triggerError spanner trigger (11111111111, TRIGGER_NAME) not found",
    "status": "NOT_FOUND"
  }
}

This only happens when I create trigger in us-central1 region. Triggers created in global region works fine.
How should I tell cloudbuild.googleapis.com to look for a trigger from region us-central1?
--- Update ---
This is the way I execute webhooks:
$ curl https://cloudbuild.googleapis.com/v1/projects/{PROJECT}/triggers/hello-central1:webhook \
    -d key=xxx \
    -d secret=xxx
# {
#   "error": {
#     "code": 404,
#     "message": "triggerError spanner trigger (11111111111, hello-central1) not found",
#     "status": "NOT_FOUND"
#   }
# }

$ curl https://cloudbuild.googleapis.com/v1/projects/{PROJECT}/locations/us-central1/triggers/hello-central1:webhook \
    -d key=xxx \
    -d secret=xxx
# {
#   "error": {
#     "code": 400,
#     "message": "Request contains an invalid argument.",
#     "status": "INVALID_ARGUMENT"
#   }
# }

$ curl https://cloudbuild.googleapis.com/v1/projects/{PROJECT}/triggers/{TRIGGER}:webhook \
    -d name=projects/{PROJECT}/locations/us-central1/triggers/{TRIGGER} \
    -d key=xxx \
    -d secret=xxx
# {
#   "error": {
#     "code": 400,
#     "message": "Request contains an invalid argument.",
#     "status": "INVALID_ARGUMENT"
#   }
# }

A: This is the way to execute trigger from region different from global:
curl https://cloudbuild.googleapis.com/v1/projects/$PROJECT/locations/$REGION/triggers/$TRIGGER:webhook \
    -d key=$KEY \
    -d secret=$SECRET \
    -d trigger=$TRIGGER \
    -d projectId=$PROJECT

Another way:
curl "https://cloudbuild.googleapis.com/v1/projects/$PROJECT/locations/$REGION/triggers/$TRIGGER:webhook?key=$KEY&secret=$SECRET&trigger=$TRIGGER&projectId=$PROJECT" -d {}

Yet another way:
curl -X POST -H Content-Type:application/json "https://cloudbuild.googleapis.com/v1/projects/$PROJECT/locations/$REGION/triggers/$TRIGGER:webhook?key=$KEY&secret=$SECRET&trigger=$TRIGGER&projectId=$PROJECT"


text:
Q: Two metrics producing different ordering of distances What is it called when two metrics disagree on the order of distances? That is, there exists two pairs $\left( \{x_1,y_1\} , \{x_2,y_2\} \right)$ such that
Metric A : $d(x_1,y_1) > d(x_2,y_2)$
Metric B : $d(x_1,y_1) < d(x_2,y_2)$
Is there a stricter set of metrics that preserve order among metrics within that set?
Example:
WLOG assume both start at the origin and destination is either $P=(20,15)$ or $Q=(24,10)$. And $d_p$ is the p-norm. (1: Taxi-cab distance, 2: Euclidean)
$d_2(P) = 25 \qquad d_2(Q)=26$
$d_1(P) = 35 \qquad d_1(Q)=34$
According to $L_2$ metric,  $d_2(P)<d_2(Q)$, but $L_1$ has $d_1(P)>d_1(Q)$. Which point is closer depends on the metric. (I knew the distances would numerically be different, but thought metrics preserved the order)
Is there a name for this property? Is there a class or metrics which preserve ordering?

A: I would describe the two metrics as "not comparable", i.e. neither one is consistently less than or equal to the other. But I don't think this is common language, as I've not seen any math that worries about this particular property of metrics.
And while I don't think this answers your particular questions, I will mention that taking the max of two metrics, i.e. defining $d_{max}(x,y) = \max \{d_1(x.y), d_2(x.y)\}$ is a very common construction when you are concerned with two different properties simultaneously. E.g. $x_n \rightarrow x$ w.r.t. $d_{max}$  if and only if $x_n \rightarrow x$ w.r.t. $d_1$ and $x_n \rightarrow x$ w.r.t. $d_2$. Also note that $d_1 \le d_{max}$ and $d_2 \le d_{max}$. This gives the set of metrics a natural structure of an upper semilattice, and a class of metrics that preserve ordering that you asked about would be a totally ordered sub-lattice of that lattice.


text:
Q: I want the highest and the lowest value of a table, why can't I save that value in PHP? $category = htmlspecialchars($_GET['category']);

$sql = "(SELECT number
        FROM german
        WHERE german.category_german LIKE ".$category."
        ORDER BY number DESC
        LIMIT 1) as 'high',
        (SELECT number
        FROM german
        WHERE german.category_german LIKE ".$category."
        ORDER BY number ASC
        LIMIT 1) as 'low'";
    if ($result = $conn -> query($sql)) {
      while ($row = $result -> fetch_row()) {

          $high_value = $row[high];
          $low_value = $row[low];
          $r_n = rand($low_value,$high_value).PHP_EOL;
          echo $r_n;
          }

      }

What am I missing? I want the highest and the lowest value of a table, why can't I save that value in PHP? I just can't access the values. And I tried out MIN and MAX as well, but they didn't function neither:
$category = htmlspecialchars($_GET['category']);

$sql = "SELECT MIN('number') AS 'low', MAX('number') AS 'high' FROM german WHERE german.category_german LIKE ".$category."";
    if ($result = $conn -> query($sql)) {
      while ($row = $result -> fetch_row()) {
          $high_value = $row[high];
          $low_value = $row[low];
          $r_n = rand($low_value,$high_value).PHP_EOL;
          echo $r_n;
          }

      }

As a result of $r_n I only get 0. The database shouldn't be the problem. Beforehand (where I only used the highest value) everything functioned:
$category = htmlspecialchars($_GET['category']);

$sql = "SELECT number FROM german WHERE german.category_german LIKE ".$category." ORDER BY number DESC LIMIT 1";
if ($result = $conn -> query($sql)) {
  while ($row = $result -> fetch_row()) {

      $r_n = $row[0];
      $r_n = rand(1,$r_n).PHP_EOL;
      echo $r_n;
      }

  }

A: You can't use multiple SELECT statements at top-level of a query. They would have to be subqueries:
SELECT (SELECT ...) AS high, (SELECT ...) AS low

Your second query would have worked, but you shouldn't have quotes around number. That makes it a literal string, not the column values. So MAX('number') should be MAX(number), MIN('number') should be MIN(number). See When to use single quotes, double quotes, and backticks in MySQL
And if category is a string, you need to put quotes around $category:
WHERE german.category_german LIKE '".$category."'"

But the better way to resolve that problem is to use a prepared statement with parameters, How can I prevent SQL injection in PHP? than substituting variables directly into the query. See


text:
Q: How to call a php script/function on a html button click Before someone has a go at me or marks this down, I have looked all over the internet to find out how to do this (including the same question on stackoverflow). I'm new, and I am finding it very hard to learn new concepts so please be easy on me.
What I want to do is call a php script/function on a button click. I have this running in WAMP if that helps. Here's my code:
<?php include 'the_script.php'; ?>

<button type="button" onclick="the_function()">Click Me</button>

the_script.php has this in it:
the_function() {
    echo "You win";
}

Why isn't this working? I've heard about the button being client side etc. and PHP being server-side, which means that you cannot link the two together. I know that you have to use AJAX to make this work, however I legitimately have absolutely no clue how to do it. I've tried googling it etc., however I can't find anything. I know how to use AJAX and call events with it, however I still have no idea how to make it call a PHP script.
Can you please make your answers as clear and simple as possible, I'm new to this
Thanks for the help :)
EDIT ***
For some reason wherever I go everyone's code is different. The way I have been taught AJAX looks completely different. Can you please write it this way so I can understand? Thanks, here's an example:
var request;

if (window.XMLHttpRequest) {
    request = new XMLHttpRequest();
} else {
    request = new ActiveXObject("Microsoft.XMLHTTP");
}

request.open('GET', 'file.php', true);

request.onreadystatechange = function() {

    if (request.readyState===4 && request.status===200) {
        do stuff
    }
}

request.send();

A: You can also use
   $(document).ready(function() {

    //some even that will run ajax request - for example click on a button

    var uname = $('#username').val();
    $.ajax({
    type: 'POST',
    url: 'func.php', //this should be url to your PHP file
    dataType: 'html',
    data: {func: 'toptable', user_id: uname},
    beforeSend: function() {
        $('#right').html('checking');
    },
    complete: function() {},
    success: function(html) {
        $('#right').html(html);
    }
    });

    });
And your func.php:

  function toptable()
 {
  echo 'something happens in here';
 }

Hope it helps somebody

A:

Just try this:

<button type="button">Click Me</button>

In script.php
<?php
  echo "You win";
 ?>

A: Use jQuery.In the HTML page -
<button type="button">Click Me</button>

Php page -
echo "Hello";

A: Of course AJAX is the solution,
To perform an AJAX request (for easiness we can use jQuery library).
Step1.
Include jQuery library in your web page
a. you can download jQuery library from jquery.com and keep it locally.
b. or simply paste the following code,

Step 2.
Call a javascript function on button click
<button type="button" onclick="foo()">Click Me</button>

Step 3.
and finally the function
 function foo () {
      $.ajax({
        url:"test.php", //the page containing php script
        type: "POST", //request type
        success:function(result){
         alert(result);
       }
     });
 }

it will make an AJAX request to test.php when ever you clicks the button and alert the response.
For example your code in test.php is,
<?php echo 'hello'; ?>

then it will alert "hello" when ever you clicks the button.

A: First understand that you have three languages working together.

PHP: Is only run by the server and responds to requests like clicking on a link (GET) or submitting a form (POST).
  HTML & Javascript: Is only run in someone's browser (excluding NodeJS)
  I'm assuming your file looks something like:

<?php
function the_function() {
echo 'I just ran a php function';
 }

 if (isset($_GET['hello'])) {
  the_function();
  }
   ?>

 Run PHP Function

Because PHP only responds to requests (GET, POST, PUT, PATCH, and DELETE via $_REQUEST) this is how you have to run a php function even though their in the same file. This gives you a level of security, "Should I run this script for this user or not?".
If you don't want to refresh the page you can make a request to PHP without refreshing via a method called Asynchronous Javascript and XML (AJAX).

A: the_function() {

$.ajax({url:"demo_test.php",success:function(result){

   alert(result); // will alert 1

 }});

}

// demo_test.php
<?php echo 1; ?>

Notes

*

*Include jquery library for using the jquery Ajax

*Keep the demo_test.php file in the same folder where your javascript
file resides

A: Modify the_script.php like this.


text:
Q: regex extract data from raw text I work in hotel. here is raw file from rapports i have.I need to extract data in order to have something like data['roomNumber']=('paxNumber',isbb,)
Here is a sample that concern only 2 room, the 10 and 12 so the data i need should be BreakfastData = {'10':['2','BB'],'12':['1','BB']}
1)roomNumber : 'start and ends with number' or 'start with number and strictly one or more space followd by string'
  2)paxNumber are the two numbers just before the 'VA' string
  3)isbb is defined by the 'BB' or 'HPDJ' occurrence which can be find between two '/'. But sometimes the format is not good so it can be '/HPDJ/' or '/ HPDJ /' or '/ HPDJ/' etc

10 PxxxxD,David,Mme, Mr T- EXPEDIA TRAVEL
08.05.17 12.05.17 TP
SUP DBL / HPDJ / DEBIT CB AGENCE - NR
2 0 VA
NR
12
LxxxxSH,Claudia,Mrs
08.05.17 19.05.17 TP
1 0 VA
NR BB
SUP SGL / BB / EN ATTENTE DE VIREMENT- EVITER LA 66 -
.... etc

edit :latest
import re
data = {}
pax=''
r = re.compile(r"(\d+)\W*(\d+)\W*VA")
r2 = re.compile(r"/\s*(BB|HPDJ)\s*/")
r3 = re.compile(r"\d+\n")
r4 = re.compile(r"\d+\s+\w")
PATH = "/home/ryms/regextest"

with open(PATH, 'rb') as raw:
    text=raw.read()
#roomNumber = re.search(r4, text).group()
#roomNumber2 = re.search(r3, text).group()
roomNumber = re.search(r4, text).group().split()[0]
roomNumber2 = re.search(r3, text).group().split()[0]

pax = re.findall(r, text)
adult = pax[0]; enfant = pax[1]
# if enfant is '0':
#   pax=adult
# else:
#   pax=(str(adult)+'+'+str(enfant))
bb = re.findall(r2, text)       #On recherche BB ou HPDJ
data[roomNumber]=pax,bb

print(data)
print(roomNumber)
print(roomNumber2)

return
{'10': ([('2', '2'), ('1', '1')], ['HPDJ', 'BB'])}
10
12
[Finished in 0.1s]

How can i get the two roomNumber in my return?
I have lot of trouble with the \n issue and read(), readline(), readlines().what is the trick?
When i will have all raw data, how will i get the proper BreakfastData{}? will  i use .zip()?
At the bigining i wanted to split the file and then parse it , but i try so may things, i get lost. And for that i need a regex that match both pattern.

A: On first case you want to select two numbers which are followed by 'VA' you can do like this
 r = re.compile(r"(\d+)\W*(\d+)\W*VA")

In second case you can get HPDJ or BB like this
r = re.compile(r"/\s*(HPDJ|BB)\s*/")

this will handle all cases you mentioned >>  /HPDJ/' or '/ HPDJ /' or '/ HPDJ/'

A: The regex expression to get the text before the VA is as follows:
r = re.compile(r"(.*) VA")

Then the "number" (which will be a string) will be stored in the first group of the search match object, once you run the search.
I am not quite sure what the room number even is, because your description is a bit unclear, so I cannot help with that unless you clarify.