text:
Q: Cannot use kotlin-gradle-dsl scripts while using android gradle plugin version 7.0.0-alpha15 I updated my Android Studio Canary to version 2020 3.1 Canary 15 which also required me to update my AGP to version 7.0.0-alpha15. I am using kotlin-gradle-dsl as my gradle build files which are now failing to build with an Unresolved reference.
Note that the gradle was successfully building before updating to version 7.0.0-alpha15.
My app level build.gradle.kts is as follows:
import com.android.build.gradle.internal.cxx.configure.gradleLocalProperties

plugins {
    id("com.android.application")
    id("kotlin-android")
    id("kotlin-kapt")
    id("dagger.hilt.android.plugin")
}

val apiKey: String = gradleLocalProperties(rootDir).getProperty("API_KEY")

android {
    compileSdkVersion(30)
    buildToolsVersion("30.0.3")

    defaultConfig {
        applicationId("com.training.flicker")
        minSdkVersion(21)
        targetSdkVersion(30)
        versionCode(1)
        versionName = "1.0"

        testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
        vectorDrawables {
            useSupportLibrary = true
        }

        buildConfigField("String", "API_KEY", apiKey)
    }

    buildTypes {
        release {
            minifyEnabled(false)
            proguardFiles(
                getDefaultProguardFile("proguard-android-optimize.txt"),
                "proguard-rules.pro"
            )
        }
    }
    compileOptions {
        sourceCompatibility = JavaVersion.VERSION_1_8
        targetCompatibility = JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = "1.8"
        useIR = true
    }

    buildFeatures.compose = true
    composeOptions.kotlinCompilerExtensionVersion = Version.compose
}

dependencies {

    implementation(Android.coreKtx)
    implementation(Android.appCompat)
    implementation(Android.material)

    implementation(Retrofit.retrofit)
    implementation(Retrofit.convertorGson)

    implementation(Hilt.hiltAndroid)
    kapt(Hilt.hiltKapt)

    implementation(Compose.material)
    implementation(Compose.tooling)
    implementation(Compose.ui)
    implementation(Compose.activity)

    implementation(Coroutines.android)

    implementation(Arch.runtime)
    implementation(Arch.viewModel)
    implementation(Arch.liveData)

    testImplementation(Test.junit)
    androidTestImplementation(Test.androidJunit)
    androidTestImplementation(Test.espressoCore)
    androidTestImplementation(Test.composeUi)
}

This is the error that I am getting
Unresolved reference. None of the following candidates is applicable because of receiver type mismatch:
public inline operator fun <T : Any, C : NamedDomainObjectContainer<TypeVariable(T)>> TypeVariable(C).invoke(configuration: Action<NamedDomainObjectContainerScope<TypeVariable(T)>>): TypeVariable(C) defined in org.gradle.kotlin.dsl
public operator fun <T> Closure<TypeVariable(T)>.invoke(): TypeVariable(T) defined in org.gradle.kotlin.dsl
public operator fun <T> Closure<TypeVariable(T)>.invoke(x: Any?): TypeVariable(T) defined in org.gradle.kotlin.dsl
public operator fun <T> Closure<TypeVariable(T)>.invoke(vararg xs: Any?): TypeVariable(T) defined in org.gradle.kotlin.dsl
public operator fun <V> Callable<TypeVariable(V)>.invoke(): TypeVariable(V) defined in org.gradle.kotlin.dsl
public operator fun <T, R> DeepRecursiveFunction<TypeVariable(T), TypeVariable(R)>.invoke(value: TypeVariable(T)): TypeVariable(R) defined in kotlin
...

A: Actually there was an issue with the AGP, because of which gradle was crashing.
The issue was fixed in the next release of AGP. Currently I am using AGP 7.0.0 with dagger hilt version 2.37 in android studio Arctic Fox with no issues.
// project level build.gradle
dependencies {
    classpath "com.android.tools.build:gradle:7.0.0"
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.10"
    classpath "com.google.dagger:hilt-android-gradle-plugin:2.37"
}
...

// app level build.gradle
implementation "com.google.dagger:hilt-android:2.37"
kapt "com.google.dagger:hilt-android-compiler:2.37"
...


text:
Q: How do i play audio file from url in android? I am developing an app with audio player.I want to play audio from url i am doing code but its plays audio from local directory i.e raw folder.I want to play song from single url at a time from play list, how to implement code in doinbackground method to play single file. What change i have to do in following code to play audio from url? Suggest me!
public class RelaxationLvAudioPlayerActivity1 extends Activity implements  SeekBar.OnSeekBarChangeListener {

    private ImageButton btnPlay;
    private ImageButton btnForward;
    private ImageButton btnBackward;
    private ImageButton btnNext;
    private ImageButton btnPrevious;
    private ImageButton btnPlaylist;
    private ImageButton btnRepeat;
    private ImageButton btnShuffle;
    private SeekBar songProgressBar;
    private TextView songTitleLabel;
    private TextView songCurrentDurationLabel;
    private TextView songTotalDurationLabel;
    // Media Player
    private MediaPlayer mp;
    // Handler to update UI timer, progress bar etc,.
    private Handler mHandler = new Handler();;
    private AudioPlayerManager songManager;
    private Utilities utils;
    private int seekForwardTime = 5000; // 5000 milliseconds
    private int seekBackwardTime = 5000; // 5000 milliseconds
    private int currentSongIndex = 0;
    private boolean isShuffle = false;
    private boolean isRepeat = false;
    private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_relaxationlv_audioplayer);

        // All player buttons
        btnPlay = (ImageButton) findViewById(R.id.btnPlay);
        //   btnForward = (ImageButton) findViewById(R.id.btnForward);
        //    btnBackward = (ImageButton) findViewById(R.id.btnBackward);
        btnNext = (ImageButton) findViewById(R.id.btnNext);
        btnPrevious = (ImageButton) findViewById(R.id.btnPrevious);
        btnPlaylist = (ImageButton) findViewById(R.id.btnPlaylist);
        //    btnRepeat = (ImageButton) findViewById(R.id.btnRepeat);
        //     btnShuffle = (ImageButton) findViewById(R.id.btnShuffle);
        songProgressBar = (SeekBar) findViewById(R.id.songProgressBar);
        songTitleLabel = (TextView) findViewById(R.id.songTitle);
        songCurrentDurationLabel = (TextView) findViewById(R.id.songCurrentDurationLabel);
        songTotalDurationLabel = (TextView) findViewById(R.id.songTotalDurationLabel);

        // Mediaplayer
        mp = new MediaPlayer();
        songManager = new AudioPlayerManager();
        utils = new Utilities();

        // Listeners
        songProgressBar.setOnSeekBarChangeListener(this); // Important

        // Getting all songs list
        songsList = songManager.getPlayList();

        // By default play first song
        playSong(0);

        /**
         * Play button click event
         * plays a song and changes button to pause image
         * pauses a song and changes button to play image
         * */
        btnPlay.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // check for already playing
                if(mp.isPlaying()){
                    if(mp!=null){
                        mp.pause();
                        // Changing button image to play button
                        btnPlay.setImageResource(R.drawable.btn_play);
                    }
                }else{
                    // Resume song
                    if(mp!=null){
                        mp.start();
                        // Changing button image to pause button
                        btnPlay.setImageResource(R.drawable.btn_pause);
                    }
                }

            }
        });

        btnNext.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // check if next song is there or not
                if(currentSongIndex < (songsList.size() - 1)){
                    playSong(currentSongIndex + 1);
                    currentSongIndex = currentSongIndex + 1;
                }else{
                    // play first song
                    playSong(0);
                    currentSongIndex = 0;
                }

            }
        });

        /**
         * Back button click event
         * Plays previous song by currentSongIndex - 1
         * */
        btnPrevious.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                if(currentSongIndex > 0){
                    playSong(currentSongIndex - 1);
                    currentSongIndex = currentSongIndex - 1;
                }else{
                    // play last song
                    playSong(songsList.size() - 1);
                    currentSongIndex = songsList.size() - 1;
                }

            }
        });

        btnPlaylist.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                Intent i = new Intent(getApplicationContext(), AudioPlayerListActivity.class);
                startActivityForResult(i, 100);
            }
        });

    }

    /**
     * Receiving song index from playlist view
     * and play the song
     * */
    @Override
    protected void onActivityResult(int requestCode,
                                    int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == 100){
            currentSongIndex = data.getExtras().getInt("songIndex");
            // play selected song
            playSong(currentSongIndex);
        }

    }

    /**
     * Function to play a song
     * @param songIndex - index of song
     * */
    public void  playSong(int songIndex){
        // Play song
        try {
            mp.reset();
            mp.setDataSource(songsList.get(songIndex).get("songPath"));
            mp.prepare();
            mp.start();
            // Displaying Song title
            String songTitle = songsList.get(songIndex).get("songTitle");
            songTitleLabel.setText(songTitle);

            // Changing Button Image to pause image
            btnPlay.setImageResource(R.drawable.btn_pause);

            // set Progress bar values
            songProgressBar.setProgress(0);
            songProgressBar.setMax(100);

            // Updating progress bar
            updateProgressBar();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Update timer on seekbar
     * */
    public void updateProgressBar() {
        mHandler.postDelayed(mUpdateTimeTask, 100);
    }

    /**
     * Background Runnable thread
     * */
    private Runnable mUpdateTimeTask = new Runnable() {
        public void run() {
            long totalDuration = mp.getDuration();
            long currentDuration = mp.getCurrentPosition();

            // Displaying Total Duration time
            songTotalDurationLabel.setText(""+utils.milliSecondsToTimer(totalDuration));
            // Displaying time completed playing
            songCurrentDurationLabel.setText(""+utils.milliSecondsToTimer(currentDuration));

            // Updating progress bar
            int progress = (int)(utils.getProgressPercentage(currentDuration, totalDuration));
            //Log.d("Progress", ""+progress);
            songProgressBar.setProgress(progress);

            // Running this thread after 100 milliseconds
            mHandler.postDelayed(this, 100);

           /// mHandler.removeCallbacks(mUpdateTimeTask);  //add this line
        }
    };

    /**
     *
     * */
    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {

    }

    /**
     * When user starts moving the progress handler
     * */
    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        // remove message Handler from updating progress bar
        mHandler.removeCallbacks(mUpdateTimeTask);
    }

    /**
     * When user stops moving the progress hanlder
     * */
    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        mHandler.removeCallbacks(mUpdateTimeTask);
        int totalDuration = mp.getDuration();
        int currentPosition = utils.progressToTimer(seekBar.getProgress(), totalDuration);

        // forward or backward to certain seconds
        mp.seekTo(currentPosition);

        // update timer progress again
        updateProgressBar();
    }
    @Override
    protected void onDestroy() {
        if (mUpdateTimeTask != null)
            mHandler.removeCallbacks(mUpdateTimeTask );
        super.onDestroy();
        mp.release();
    }
}

public class AudioPlayerManager{
    //    SDCard Path
    //    final String MEDIA_PATH = new String(Environment.getExternalStorageDirectory().getPath());
          final String MEDIA_PATH = "/sdcard/songs/";
    //      private String MEDIA_PATH =Environment.getExternalStorageDirectory().getPath();

    private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();

    // Constructor
    public AudioPlayerManager(){

    }

    /**
     * Function to read all mp3 files from sdcard
     * and store the details in ArrayList
     * */
    public ArrayList<HashMap<String, String>> getPlayList(){
        //  File home = new File(MEDIA_PATH);
        File home = new File(MEDIA_PATH);

        if (home.listFiles(new FileExtensionFilter()).length > 0) {
            for (File file : home.listFiles(new FileExtensionFilter())) {
                HashMap<String, String> song = new HashMap<String, String>();
                song.put("songTitle", file.getName().substring(0, (file.getName().length() - 4)));
                song.put("songPath", file.getPath());

                // Adding each song to SongList
                songsList.add(song);
            }
        }
        // return songs list array
        return songsList;
    }

    /**
     * Class to filter files which are having .mp3 extension
     * */
    class FileExtensionFilter implements FilenameFilter {
        public boolean accept(File dir, String name) {
            return (name.endsWith(".mp3") || name.endsWith(".MP3"));
        }
    }
}

A: you can try this
try {

  mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
  mp.setDataSource("your url");
  mp.prepare();
  mp.start();
 } catch (Exception e) {
   // handle exception
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: CVE-2021-38628 in nodeJs Description:
Disable the use of TLSv1.0 protocol in favor of a cryptographically stronger protocol such as TLSv1.2.

The following openssl commands can be used to do a manual test: openssl s_client -connect ip:port -tls1 If the test is successful, then the target support TLSv1

Env:
Nuxt application in dockerfile (same as any other nodejs web application)

A: To fix this issue either you'll need to add in your nginx conf file:
ssl_protocols TLSv1.2;
don't forget to replace the default configuration in nginx using docker file:
COPY ./nginx/conf.d /etc/nginx/conf.d
this may not solve the issue, if it's the case upgrade your node version (in my case i'm using 16.17.0-alphine)
you can test it locally before deploying running this cmd:
openssl s_client -connect ip:port -tls1 (and  openssl s_client -connect ip:port -tls1_1)
should not show your certificate, then run: openssl s_client -connect ip:port -tls1_2
if now you're able to see your certificate only in the second command then you have successfully fixed the issue.


text:
Q: Can't compile rtl8821ce wifi driver on Lubuntu 18.10 I'm trying to get Linux working with my Lenovo Yoga 530-14ARR laptop. It has a wireless Realtek "rtl8821ce" card, which is not recognized out of the box by my brand new Lubuntu 18.10 install (I tried other lightweight distros before, without success). According to this question's top answer, compiling this and modprobe the resulting module should do the trick.
Unfortunately, I can't get it to compile on my machine:
liloboot@lubuntu:~/rtl8821ce$ make
make ARCH=x86_64 CROSS_COMPILE= -C /lib/modules/4.18.0-10-generic/build M=/home/liloboot/rtl8821ce  modules
make[1]: Entering directory '/usr/src/linux-headers-4.18.0-10-generic'
Makefile:982: "Cannot use CONFIG_STACK_VALIDATION=y, please install libelf-dev, libelf-devel or elfutils-libelf-devel"
  CC [M]  /home/liloboot/rtl8821ce/os_dep/linux/os_intfs.o
    /home/liloboot/rtl8821ce/os_dep/linux/os_intfs.c:1325:22: error: initialization of 'u16 (*)(struct net_device *, struct sk_buff *, void *, u16 (*)(struct net_device *, struct sk_buff *))' {aka 'short unsigned int (*)(struct net_device *, struct sk_buff *, void *, short unsigned int (*)(struct net_device *, struct sk_buff *))'} from incompatible pointer type 'u16 (*)(struct net_device *, struct sk_buff *, struct net_device *, u16 (*)(struct net_device *, struct sk_buff *))' {aka 'short unsigned int (*)(struct net_device *, struct sk_buff *, struct net_device *, short unsigned int (*)(struct net_device *, struct sk_buff *))'} [-Werror=incompatible-pointer-types]
  .ndo_select_queue = rtw_select_queue,
                      ^~~~~~~~~~~~~~~~
/home/liloboot/rtl8821ce/os_dep/linux/os_intfs.c:1325:22: note: (near initialization for 'rtw_netdev_ops.ndo_select_queue')
cc1: some warnings being treated as errors
make[2]: *** [scripts/Makefile.build:327: /home/liloboot/rtl8821ce/os_dep/linux/os_intfs.o] Error 1
make[1]: *** [Makefile:1546: _module_/home/liloboot/rtl8821ce] Error 2
make[1]: Leaving directory '/usr/src/linux-headers-4.18.0-10-generic'
make: *** [Makefile:1902: modules] Error 2

EDIT: Following chili555's comment, I tried this. It finally worked but I had several problems that I want to point out in an answer. See below.

A: Problems and solutions when following the steps of this answer:

*

*Coming from a Windows PC, all script files where in a wrong format, resulting in a 'no such file or directory' error when trying to sudo ./dkms-install.sh. I had to dos2unix all of them.

*I had to manually sudo-run some of the dkms commands in dkms-install.sh because sudo ./dkms-install.sh was reporting errors that I finally interpreted as a lack of privileges. Don't know why.

sudo dkms build -m rtl8821ce -v v5.2.5_1.26055.20180108
sudo dkms install -m rtl8821ce -v v5.2.5_1.26055.20180108

*

*Then I rebooted and  ip a showed the new wlp1s0 network interface. But I was not out of the woods yet.

*The wifi module was still hard-blocked, as shown by the outputs of nmcli radio and rfkill list. I had to add an entry to /etc/modprobe.d/blacklist.conf as explained in this: append blacklist ideapad_laptop at the end of the file, then reboot.

And the wifi module is now working properly.


text:
Q: Showing Shannon's formula Well, I'm having this in a textbook [1] :
\begin{align*}
H(U_N) &= H_1 + H_2 \\
\log_2 N &= H_1 + \sum_{k=1}^n \frac{N_k}{N} \log_2 N_k \\
\sum_{k=1}^n \frac{N_k}{N}\log_2 N &= H_1 + \sum_{k=1}^n \frac{N_k}{N} \log_2 N_k \\
\Rightarrow H_1 &= - \sum_{k=1}^N \frac{N_k}{N} \log_2 \frac{N_k}{N}
\end{align*}
Which is supposed to show Shannon's formula.
However, I just don't get the step from line 1 to line 2. I tried to get there myself but it actually looks kind of wrong. I don't want to disgrace myself here but how does this make sense? Also notice the upper limit of the sum changing from $n$ to $N$ which is also rather weird. $n$ should be the number of groups, if I got that right and $N$ should be the number oh how many different numbers one can represent in base 2 using a certain number of bits as in:
How many times do I have to ask at most to guess a binary digit?
\begin{align*}
n &= \log_2 2^n = \log_2 N
\end{align*}
so we have
\begin{align*}
H(U_N) = \log_2 N \text{ bit}
\end{align*}
to store a corresponding message.
Also we're demanding that
\begin{align*}
H(U_{N \cdot M}) = H(U_N) + H(U_M)
\end{align*}

The only possibility for
\begin{align*}
\sum_{k=1}^n \frac{N_k}{N} \log_2 N &= \log_2 N
\end{align*}
is if
\begin{align*}
\frac{1}{N} \sum_{k=1}^n N_k &= 1
\end{align*}
but would only work if we actually have something like
\begin{align*}
\frac{1}{N} \sum_{k=1}^n w_k N &= 1 \Rightarrow \sum_{k=1}^n w_k = 1
\end{align*}
or
\begin{align*}
\sum_{k=1}^n N_k  &= N
\end{align*}
But from what I saw I expected each $N_k$ to be $2^\text{something}$.

[1] Elements of Information Theory, Thomas M. Cover, Joy A. Thomas

A: Okay, I think I get it now. We have $\log_2(2^n) = \log_2(N) = n$ as the answer to the question

"How many times do I have to ask to identify a number written in base 2 in a set of $N = 2^n$ different numbers?"

We define Hartley's function $H(U_N)$ where $U_N$ is a set with $N$ different elements with equal probability. Thus, the required amount of information to identify an element in $U_N$ is
\begin{align*}
H(U_N) &= \log_2 N \text{ bit}
\end{align*}
We also require
\begin{align*}
\text{1.  }&H(U_2) = 1 \\
\text{2.  }&H(U_N) \leq H(U_{N+1}) \\
\text{3.  }&H(U_{N\cdot M}) = H(U_N) + H(U_M)
\end{align*}
Example:
If we want to know an element in $N = 2^3$ different elements, we can e.g. group them in $G_1 = \{000,001,010,011\}$ and $G_2 = \{100,101,110,111\}$ (Note that $N = |G_1| + |G_2| = N_1 + N_2)$. We already see, that we need 3 bits to encode all these elements. If we decide e.g. the first bit as identifier for one of the two groups we have:
Group 1 | Group 2
-----------------
  000   |   100
  001   |   101
  010   |   110
  011   |   111

and we can calculate this with
\begin{align*}
H(U_{2 \cdot 4}) &= H(U_{2}) + H(U_{4}) \\
&= \log_2(2) + \log_2(4) \\
&= 3
\end{align*}
Now we want to know the following: If we take such a $H(U_N)$ that we group in the described manner as above we can "split" the question "Which element in the set $G_1 \cup G_2$ are you?" by asking the question $H_1$ ("in which group do you belong?") and $H_2$ ("Knowing the group, which element in that group are you?").
\begin{align*}
H(U_N) = H_1 + H_2
\end{align*}
For $H_2$ we know that we need $\log_2 N_k$ questions to identify an object in the group. The average number of questions with respect to a group depends on the size of the group and thus we have
\begin{align*}
H_2 &= \sum_{k=1}^n \frac{N_k}{N} \log_2 N_k
\end{align*}
What's now missing is $H_1$. We want to know the missing part of information to calculate $H(U_N)$ or in other words: Not knowing $H_1$, how much information would I gain if I knew it?
\begin{align*}
H(U_N) &= H_1 + H_2 \\
\log_2 N &= H_1 + H_2 \\
\log_2 N  &= H_1 + \sum_{k=1}^n \frac{N_k}{N} \log_2 N_k \\
\Rightarrow H_1 &= \log_2 N - \sum_{k=1}^n  \frac{N_k}{N} \log_2 N_k \\
&= \sum_{k=1}^n  \frac{N_k}{N} \log_2 N - \sum_{k=1}^n  \frac{N_k}{N} \log_2 N_k & \text{Because: } \sum_{k=1}^n \frac{N_k}{N} = 1 \\
&= \sum_{k=1}^n  \frac{N_k}{N} \Big( \log_2 N -  \log_2 N_k \Big) \\
&= -\sum_{k=1}^n  \frac{N_k}{N} \Big( \log_2 N_k -  \log_2 N \Big) \\
&= -\sum_{k=1}^n  \frac{N_k}{N} \log_2 \frac{N_k}{N}
\end{align*}
We now know that
\begin{align*}
H_1 &= - \sum_{k=1}^n p_k \log_2 p_k
\end{align*}
where $p_k = \frac{N_k}{N}$ which is the amount of information we would gain if we knew in which group our element falls into.

The reason why I didn't get it was actually just because I didn't see that $\sum_{k=1}^n N_k = N$.


text:
Q: Laravel, where to place the logic for the app.blade.php file? I'm using Laravel 5 for my new project and I want to follow best practices. I have my layout wrapper as resources/views/app.blade.php and it 'yields' every view. I need to show some dynamically generated data in app.blade.php, where should I place the logic to generate the data? For any other view I would do it in the corresponding controller, but for the whole app?
Thanks

A: <?php namespace App\Http\Composers;

use Illuminate\Contracts\View\View;
use Illuminate\Users\Repository as UserRepository;

class ProfileComposer {

    /**
     * The user repository implementation.
     *
     * @var UserRepository
     */
    protected $users;

    /**
     * Create a new profile composer.
     *
     * @param  UserRepository  $users
     * @return void
     */
    public function __construct(UserRepository $users)
    {
        // Dependencies automatically resolved by service container...
        $this->users = $users;
    }

    /**
     * Bind data to the view.
     *
     * @param  View  $view
     * @return void
     */
    public function compose(View $view)
    {
        $view->with('count', $this->users->count());
    }

}

And bind to view!
View::composer(['profile', 'dashboard'], 'App\Http\ViewComposers\MyViewComposer');


text:
Q: Strange 404 error on local host So I have a mySQL database and i have it hooked up to some php and html files. My php file is in the localhost folder. When i run my test html file which is also in my localhost folder, it has no problem finding the file, but when i have a subfolder within my localhost folder called "SriMeru" where i have my actual html file with formatting and other things along with the final php file, the html file cannot locate the php file. Here's some code in the html file:

no

     Message <input type= "text" id="messbox">
     <button type= "button" onclick="loadPHPDoc(document.getElementById('messbox').value)">input</button>

and here's my php file code:
<?php

    $q = $_POST["q"];

    $messData = mysqli_connect("localhost", "root", "chendu", "SriMeru");
    if (mysqli_connect_errno()){
        echo "Failed to connect to Server";
    }
    $sql = "INSERT INTO messages VALUES ('".$q."')";
    mysqli_query($messData, $sql);
    echo "
success
";

   mysqli_close($messData);
?>

Other places in the html file, i have some weird formatting involving marquee and timers, i dont know if this could mess things up.

A:
"but when i have a subfolder within my localhost folder called "SriMeru" where i have my actual html file"

You say your folder is named SriMeru
On many systems (including UNIX/LINUX), SriMeru and srimeru are not the same thing; they are case-sensitive.
Therefore, either rename your folder to be all in lowercase letters, or change srimeru/forumSubmit.php to SriMeru/forumSubmit.php


text:
Q: how to make linear gradient worked in IE9 i want to show background image, with a color over it, but color have a opacity so that background image become visible. this worked in Chrome and Firefox with linear-gradient, but not in IE9. How it can work in ie.?
linear-gradient( rgba(0, 0, 0, 0.50), rgba(0, 0, 0, 0.50) ), url(images/expand.jpg)

A: You can use following CSS code

note: the last line is hack for IE6 to IE9

CSS
.gradient {
    background: #1e5799;
    /* Old browsers */

    background: -moz-linear-gradient(top, #1e5799 0%, #2989d8 50%, #207cca 51%, #7db9e8 100%);
    /* FF3.6+ */

    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #1e5799), color-stop(50%, #2989d8), color-stop(51%, #207cca), color-stop(100%, #7db9e8));
    /* Chrome,Safari4+ */

    background: -webkit-linear-gradient(top, #1e5799 0%, #2989d8 50%, #207cca 51%, #7db9e8 100%);
    /* Chrome10+,Safari5.1+ */

    background: -o-linear-gradient(top, #1e5799 0%, #2989d8 50%, #207cca 51%, #7db9e8 100%);
    /* Opera 11.10+ */

    background: -ms-linear-gradient(top, #1e5799 0%, #2989d8 50%, #207cca 51%, #7db9e8 100%);
    /* IE10+ */

    background: linear-gradient(to bottom, #1e5799 0%, #2989d8 50%, #207cca 51%, #7db9e8 100%);
    /* W3C */

    filter: progid: DXImageTransform.Microsoft.gradient( startColorstr='#1e5799', endColorstr='#7db9e8', GradientType=0);
    /* IE6-9 *
}

A: Support for full multi-stop gradients with IE9 (using SVG).
Add a "gradient" class to all your elements that have a gradient, and add the following override to your HTML to complete the IE9 support:
<!--[if gte IE 9]>
  <style type="text/css">
    .gradient {
       filter: none;
    }
  </style>
<![endif]-->

Single Ex:
/* IE9 SVG, needs conditional override of 'filter' to 'none' */

background: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/Pgo8c3ZnIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgdmlld0JveD0iMCAwIDEgMSIgcHJlc2VydmVBc3BlY3RSYXRpbz0ibm9uZSI+CiAgPGxpbmVhckdyYWRpZW50IGlkPSJncmFkLXVjZ2ctZ2VuZXJhdGVkIiBncmFkaWVudFVuaXRzPSJ1c2VyU3BhY2VPblVzZSIgeDE9IjAlIiB5MT0iMCUiIHgyPSIwJSIgeTI9IjEwMCUiPgogICAgPHN0b3Agb2Zmc2V0PSIwJSIgc3RvcC1jb2xvcj0iIzFlNTc5OSIgc3RvcC1vcGFjaXR5PSIxIi8+CiAgICA8c3RvcCBvZmZzZXQ9IjUwJSIgc3RvcC1jb2xvcj0iIzI5ODlkOCIgc3RvcC1vcGFjaXR5PSIxIi8+CiAgICA8c3RvcCBvZmZzZXQ9IjUxJSIgc3RvcC1jb2xvcj0iIzIwN2NjYSIgc3RvcC1vcGFjaXR5PSIxIi8+CiAgICA8c3RvcCBvZmZzZXQ9IjEwMCUiIHN0b3AtY29sb3I9IiM3ZGI5ZTgiIHN0b3Atb3BhY2l0eT0iMSIvPgogIDwvbGluZWFyR3JhZGllbnQ+CiAgPHJlY3QgeD0iMCIgeT0iMCIgd2lkdGg9IjEiIGhlaWdodD0iMSIgZmlsbD0idXJsKCNncmFkLXVjZ2ctZ2VuZXJhdGVkKSIgLz4KPC9zdmc+);

Multi Ex:
background: #1e5799; /* Old browsers */
/* IE9 SVG, needs conditional override of 'filter' to 'none' */
background: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/Pgo8c3ZnIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgdmlld0JveD0iMCAwIDEgMSIgcHJlc2VydmVBc3BlY3RSYXRpbz0ibm9uZSI+CiAgPGxpbmVhckdyYWRpZW50IGlkPSJncmFkLXVjZ2ctZ2VuZXJhdGVkIiBncmFkaWVudFVuaXRzPSJ1c2VyU3BhY2VPblVzZSIgeDE9IjAlIiB5MT0iMCUiIHgyPSIwJSIgeTI9IjEwMCUiPgogICAgPHN0b3Agb2Zmc2V0PSIwJSIgc3RvcC1jb2xvcj0iIzFlNTc5OSIgc3RvcC1vcGFjaXR5PSIxIi8+CiAgICA8c3RvcCBvZmZzZXQ9IjUwJSIgc3RvcC1jb2xvcj0iIzI5ODlkOCIgc3RvcC1vcGFjaXR5PSIxIi8+CiAgICA8c3RvcCBvZmZzZXQ9IjUxJSIgc3RvcC1jb2xvcj0iIzIwN2NjYSIgc3RvcC1vcGFjaXR5PSIxIi8+CiAgICA8c3RvcCBvZmZzZXQ9IjEwMCUiIHN0b3AtY29sb3I9IiM3ZGI5ZTgiIHN0b3Atb3BhY2l0eT0iMSIvPgogIDwvbGluZWFyR3JhZGllbnQ+CiAgPHJlY3QgeD0iMCIgeT0iMCIgd2lkdGg9IjEiIGhlaWdodD0iMSIgZmlsbD0idXJsKCNncmFkLXVjZ2ctZ2VuZXJhdGVkKSIgLz4KPC9zdmc+);
background: -moz-linear-gradient(top,  #1e5799 0%, #2989d8 50%, #207cca 51%, #7db9e8 100%); /* FF3.6+ */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#1e5799), color-stop(50%,#2989d8), color-stop(51%,#207cca), color-stop(100%,#7db9e8)); /* Chrome,Safari4+ */
background: -webkit-linear-gradient(top,  #1e5799 0%,#2989d8 50%,#207cca 51%,#7db9e8 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(top,  #1e5799 0%,#2989d8 50%,#207cca 51%,#7db9e8 100%); /* Opera 11.10+ */
background: -ms-linear-gradient(top,  #1e5799 0%,#2989d8 50%,#207cca 51%,#7db9e8 100%); /* IE10+ */
background: linear-gradient(to bottom,  #1e5799 0%,#2989d8 50%,#207cca 51%,#7db9e8 100%); /* W3C */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#1e5799', endColorstr='#7db9e8',GradientType=0 ); /* IE6-8 */


text:
Q: Blackberry: setTitle with image displays a black border in os 5.0 Bitmap image = Bitmap.getBitmapResource(stage+"-whatson-header_"+reslabel+".png");
    BitmapField title = new BitmapField();
    title.setBitmap(image);
    setTitle(title);

In os 5.0, below the image is a black line or border, and I have no idea what is causing it. I made sure my image does not have any transparency that may be causing a glitch.


text:
Q: String initializer for optional primitive types: Int? Double? Float? etc Is it possible to have an extension for all of the above types without specifying each type individually?
For example, here is such extension for Double:
extension String {
  init?(_ value: Double?) {
    if let nonOpt = value {
      self.init(nonOpt)
    } else {
      return nil
    }
  }
}

let nonOpt: Double = 1

let opt: Double? = 1

let string = String(opt)

print(string)

I'd like to allow string initialization with optional type if it is possible to initialize string with the original type.

A: Do you mean something like this
extension String {
    init?<T : CustomStringConvertible>(_ value : T?) {
        guard let value = value else { return nil }
        self.init(describing: value)
    }
}

or
extension String {
    init?<T : LosslessStringConvertible>(_ value : T?) {
        guard let value = value else { return nil }
        self.init(value)
    }
}

A: Rather than declaring an custom initializer, just use map to map the value to a String as such:
let optDouble: Double? = nil
let optionalDoubleString = opt.map { String($0) }
let optInt: Int? = nil
let optionalIntString = opt.map { String($0) }


text:
Q: Entity Framework Core does not recognize an existent column in a PostgreSQL table In a DataBase first .net 6 app I get the following error
"Npgsql.PostgresException (0x80004005): 42703: no existe la columna b.CampusId"
Hint: Probablemente quiera hacer referencia a la columna «b.campusid».

Which means that the column b.CampusId does not exist as a column, and as a hit it tells me you are probably looking for b.campusid.
But I have the following schema:
CREATE TABLE "Campus" (
    "CampusId" SERIAL PRIMARY KEY,
    "Name" varchar(250) NOT NULL,
    "UniversityId" int NOT NULL,
    "StateId" int NOT NULL,
    "CreatedAt" TIMESTAMP NOT NULL DEFAULT NOW(),
    "ModifiedAt" TIMESTAMP,
    UNIQUE("Name", "UniversityId", "StateId"),
    FOREIGN KEY ("UniversityId")
        REFERENCES "University" ("UniversityId"),
    FOREIGN KEY ("StateId")
        REFERENCES "State" ("StateId")
);

And the part where the code breaks is in this one:
var campus_ids = await _context.Set<Campus>().FromSqlRaw<Campus>(
    $"SELECT * FROM \"Campus\" c WHERE LOWER(UNACCENT(c.\"Name\")) LIKE '%{search}%' LIMIT {MAX_RESULTS} ")
    .AsNoTracking()
    .Select(x => x.CampusId) // This part is the one it complains about
    .ToListAsync();

I do not get why the error ocurs in the Select part, since the Campus Model has the exact property name as the column in the Campus TABLE, both are named exactly CampusId, and I created them with quotes so it could be case sensitive, but still npgsql hints me about the correct name being in lowercase, notwithstanding the data base shows the column exactly like CampusId.
The generated code by EF is:
SELECT b.campusid
FROM (
    SELECT * FROM "Campus" c WHERE LOWER(UNACCENT(c."Name"))
    LIKE '%universidad%' LIMIT 20
) AS b

So, my questions are:

*

*Why it yielded that bad translation when the entity name is CampusId?

*How can I make EF to translate its queries to the appropiate property model and column names?

It should have been 'SELECT b.CampusId' instead of what it actually yielded.


text:
Q: In Power BI how can I plot values of 2 or more columns on a line graph I have some timeseries data i.e value of voltage for every minute. It is stored in a database. I can plot this value using a Line chart. But now I have values from another table which is the allowed ranges of this voltage(I have this per min too..this is a sql view and I can change it to suit my needs.) I need to plot a graph with the actual value and the range data...so it would be 3 lines...2 constant(showing the max and min) and the actual value in the middle...In the Line graph, I cannot pull in multiple columns and plot the line. Is there any other visualization available?

A: It is possible to plot several series on the same line chart. They way I do it is by first putting the multiple series on the same table.
Your new table would have three columns:

*

*Date, that you would assign to "Axis" in your line chart.

*Series, that contains a description of the line (e.g. voltage, min and max) and you would assign to "Legend".

*Value, that contains the actual value for each series and you assign to "Values" on the visual.

You can create this new table by doing a union query between your two original tables and adding the "Series" column to describe the Voltage the min and the max data.
I hope it helps.


text:
Q: Computing the expectation of the number of balls in a box

*

*There are $r$ boxes and $n$ balls.

*Each ball is placed in a box with equal probability, independently of the other balls.

*For each $1 \leq i\leq r$, let $X_{i}$ be the number of balls in box $i$.

*Compute $\mathbb{E}\left[X_{i}\right],\ \mathbb{E}\left[X_{i}X_{j}\right]$.

I am preparing for an exam, and I have no idea how to approach this problem. Can someone push me in the right direction?
Symmetry reasoning makes it clear that $\mathbb{E}\left[X_{i}\right]$ doesn't depend on $i$. Likewise, $\mathbb{E}\left[X_{i}X_{j}\right]$ doesn't depend on the concrete values of $i$ and $j$ but only (if at all) on whether $i=j$ or $i\neq j$. But this doesn't actually compute these expectations.

A: For the first part, you can use linearity of expectation to compute $\mathbb{E}[X_i]$.
Specifically, you know that for a fixed box, the probability of putting a ball in it
is $\frac{1}{r}$. Let
$$
Y_k^{(i)} = \begin{cases}
   1 &, \text{ if ball $k$ was placed in box $i$} \\
   0 &, \text{ otherwise}
\end{cases},
$$
which satisfies $\mathbb{E}[Y_k^{(i)}] = \mathbb{P}(Y_k^{(i)} = 1) = \frac{1}{r}.$
Then you can write
$$
X_i = \sum_{j=1}^n Y_j^{(i)} \Rightarrow \mathbb{E}X_i = \sum_{j=1}^n \frac{1}{r} = \frac{n}{r}.
$$

For the second part, you can proceed similarly: $X_i = \sum_{k=1}^n Y_k^{(i)}$ and $X_j = \sum_{\ell=1}^n Y_{\ell}^{(j)}$, so:
$$
X_i X_j = \sum_{k=1}^n \sum_{\ell=1}^n Y_k^{(i)} Y_{\ell}^{(j)} \implies
\mathbb{E}(X_i X_j) = \sum_{k=1}^n \sum_{\ell=1}^n \mathbb{E}(Y_k^{(i)} Y_{\ell}^{(j)}).
$$
We will first treat the case where $i \ne j$.  Then, for each term in the sum such that $k = \ell$, we must have $Y_k^{(i)} Y_{\ell}^{(j)} = Y_k^{(i)} Y_k^{(j)} = 0$ since it impossible for ball $k$ to be placed both in box $i$ and in box $j$.  On the other hand, if $k \ne \ell$, then the events corresponding to $Y_k^{(i)}$ and $Y_{\ell}^{(j)}$ are independent since the placement of balls $k$ and $\ell$ are independent, which implies that $Y_k^{(i)}$ and $Y_{\ell}^{(j)}$ are independent random variables.  Therefore, in this case,
$$\mathbb{E}(Y_k^{(i)} Y_{\ell}^{(j)}) = \mathbb{E}(Y_k^{(i)}) \mathbb{E}(Y_{\ell}^{(j)}) = \frac{1}{r} \cdot \frac{1}{r}.$$
In summary, if $i \ne j$, then
$$\mathbb{E}(X_i X_j) = \sum_{k=1}^n \sum_{\ell=1}^n \delta_{k \ne \ell} \cdot \frac{1}{r^2} = \frac{n(n-1)}{r^2}$$
where $\delta_{k \ne \ell}$ represents the indicator value which is 1 when $k \ne \ell$ and 0 when $k = \ell$.
For the case $i = j$, I will leave the similar computation of $\mathbb{E}(X_i^2)$ to you, with just the hint that the difference is in the expected value of $\mathbb{E}(Y_k^{(i)} Y_{\ell}^{(j)})$ for the case $k = \ell$.

A: Since there are $r$ boxes and $n$ balls, and each ball is placed in a box with equal probability, we have:
$$ \mathbb{E}[X_i] = \frac{n}{r} $$
Now, we would like to know what is $\mathbb{E}[X_i X_j] $.
We begin by making the following observation:
$$X_i = n - \sum_{j\neq i}X_j $$
Which gives us:
$$ X_i\sum_{j\neq i}X_j = nX_i - X_i^2$$
Now, fix $i$ (we can do this because of the symmetry in the question), and thus we have:
\begin{align}\mathbb{E}[X_i X_j] &= \frac{1}{r}\Big(\mathbb{E}[X_i \sum_{j\neq i} X_j] + \mathbb{E}[X_i^2]\Big) \\
&= \frac{1}{r} \mathbb{E}[nX_i] \\
&= \frac{n^2}{r^2}
\end{align}

A: Think of placing the ball in box "$i$" as success and not placing it as a failure.
This situation can be represented using the Hypergeometric Distribution.
$$
P(X=k) = \frac{{K \choose k} {N- K\choose n - k}}{{N \choose n}}.
$$
$N$ is the population size (number of boxes $r$)
$K$ is the number of success states in  the population (just $1$ because the success is defined as placing the ball in box "$i$".)
$n$ is the number of draws (the number of balls $n$).
$k$ is the number of observed successes (the number of balls in box "$i$").
The expectation of the Hypergeometric Distribution is $n\frac{K}N$, hence the mean of your variable
$$E[X_i]=n\frac{1}{r}=\frac{n}{r}$$


text:
Q: Correct Combinatorial reasoning for constant positions Suppose we have an array $A$ indexed from $1$ to $n$. Let a constant position be any index $i$ for $1 \leq i \leq n$ of the array such that:
\begin{equation}
A_i = i
\end{equation}
For example the array $\lbrack1,4,3,5, 2 \rbrack$ has the constant positions $1$ and $3$.
I want to the prove the number of constant positions over all permutations of $\lbrack n\rbrack$ is $n!$. Consider $n=3$ we have the following permutations:
\begin{align}
&\lbrack 1, 2, 3\rbrack \implies 3 \text{    constant positions}\\
&\lbrack 1, 3, 2\rbrack \implies 1\text{    constant positions}\\
&\lbrack 2, 1, 3\rbrack \implies 1\text{    constant positions}\\
&\lbrack 2, 3, 1\rbrack \implies 0\text{    constant positions}\\
&\lbrack 3, 1, 2\rbrack \implies 0\text{    constant positions}\\
&\lbrack 3, 2, 1\rbrack \implies 1\text{    constant positions}\\
\end{align}
Thus, for $n=3$ we have $3!=6$ permutations.
Here is my proof:
We have $n$ disjoint cases:
Suppose there is a $1$ in position $1$ of the array $A$. Then there are $(n-1)!$ ways to rearrange the remaining elements.
Suppose there is a $2$ in position $2$ of the array $A$. Then there are $(n-1)!$ ways to rearrange the remaining elements.
$\vdots$
Suppose there is an $n$ n in the $n^{th}$ position of the array $A$. Then there are $(n-1)!$ ways to rearrange the other elements.
Now, since each case is disjoint of every other case we can invoke the addition rule and therefore we have $n$ copies of $(n-1)!$:
\begin{align}
=& n(n-1)! \\
=& n!
\end{align}

*

*Is my reasoning correct?

*I think these cases are not necessarily disjoint in terms of the permutations that you can generate, but maybe in terms of what I am actually counting, perhaps they are.

All help is greatly appreciated!

A: Your proof is essentially correct, for the reasons given in the comments.  Here's a somewhat more systematic approach which shows that the main trick to the problem is to change the order of summation in a double sum.
For a permutation $\sigma$ of $\{1,2,\dots,n\}$, let $\text{Fix}(\sigma) = \{ 1 \leq i \leq n : \sigma(i) = i \}$.  You are asking to compute
$$
\sum_{\sigma \in S_n} |\text{Fix}(\sigma)| = \sum_{\sigma \in S_n} \sum_{i \in \text{Fix}(\sigma)} 1.
$$
But this is equal to
$$
\sum_{i=1}^n \sum_{\sigma \in S_n : \sigma(i) = i} 1 = \sum_{i=1}^n (n-1)! = n \cdot (n-1)! = n!.
$$


text:
Q: java.lang.IllegalStateException: Could not execute method for android:onClick when trying to click a button When I click the buttons on my page, I get an "IllegalStateException" in my logcat. I'm new at Java development, so I don't really know if it's something simple that i'm doing wrong. All I'm trying to do is get the button to open the activity. It worked fine until i started playing with the fragments etc for the layout.
log cat
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.as1.app172, PID: 5621
    java.lang.IllegalStateException: Could not execute method for android:onClick
        at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
        at android.view.View.performClick(View.java:5637)
        at android.view.View$PerformClick.run(View.java:22429)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6119)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
    Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Method.invoke(Native Method)
        at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
        at android.view.View.performClick(View.java:5637)
        at android.view.View$PerformClick.run(View.java:22429)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6119)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
     Caused by: android.content.ActivityNotFoundException: Unable to find explicit activity class {com.as1.app172/com.as1.app172.LoginActivity}; have you declared this activity in your AndroidManifest.xml?
        at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1805)
        at android.app.Instrumentation.execStartActivity(Instrumentation.java:1523)
        at android.app.Activity.startActivityForResult(Activity.java:4225)
        at android.support.v4.app.BaseFragmentActivityApi16.startActivityForResult(BaseFragmentActivityApi16.java:54)
        at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:67)
        at android.app.Activity.startActivityForResult(Activity.java:4183)
        at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:720)
        at android.app.Activity.startActivity(Activity.java:4522)
        at android.app.Activity.startActivity(Activity.java:4490)
        at com.as1.app172.Import1.BtnLogin_Click(Import1.java:25)
        at java.lang.reflect.Method.invoke(Native Method)
        at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
        at android.view.View.performClick(View.java:5637)
        at android.view.View$PerformClick.run(View.java:22429)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6119)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

java
package com.as1.app172;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

public class Import1 extends AppCompatActivity {

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

    public void BtnRegister_Click (View v) {
        Intent i = new Intent (Import1.this, RegistrationActivity.class);
        startActivity(i);

    }

    public void BtnLogin_Click(View v) {
        Intent i = new Intent (Import1.this, LoginActivity.class);
        startActivity(i);
    }
}

A: Check your AndroidManifest.xml and make sure you are already declared the activity LoginActivity.  <activity android:name=".view.acitvity.LoginActivity" />


text:
Q: PHP how to create a function named "do"? I saw a library with a method named "do"
public function do

totally bugs out parser
Parse error: syntax error, unexpected T_DO, expecting T_STRING in ...
//same on call
$obj->do()

Parse error: syntax error, unexpected T_DO, expecting T_STRING or T_VARIABLE or '$' in
Gearman Uses a "do" function by the way.
http://www.php.net/manual/en/gearmanclient.do.php

A: Its a bad idea to name a function that is a keyword. Its also, maybe even worse name because do isn't very descriptive.
Choose a better name.

A: "do" is a reserved keyword: http://www.php.net/manual/en/reserved.keywords.php
On that same page, in the comments, you see a user mention a way around this. Bear in mind that this method must be used with care:
// Now define a __call() method (requires PHP > 5.2.3 to take effect)
public function __call($func, $args)
{
    switch ($func)
    {
        case 'list':
            return $this->ls((isset($args[0]))? $args[0]: null);
        break;
        case 'unset':
            return $this->rm($args[0]);
        break;
        default:
            trigger_error("Call to undefined method ".__CLASS__."::$func()", E_USER_ERROR);
        die ();
    }

So you see, you could use a do method (or some other reserved word) in any class by using the __call overload. Externally, this method would be indistinguishable from a traditionally defined method.

A:     class MyClass {
        function _do() {
            echo "doing something";
        }

        function __call( $methodName, $arguments ) {
            if( $methodName == 'do' ) {
                $this->_do();
            }
        }
    }

    $myObject = new MyClass();
    $myObject->do();

A: gearman is a pecl extension, written in c. as such, it is not parsed by the php parser. PHP actually allows you to call a do() method, but wont let you define or use this reserved keyword for anything else when declaring stuff. If you look at the gearman code, you will notice:
__PHP_ME_MAPPING(do, gearman_client_do, arginfo_oo_gearman_client_do, 0)

so that's how they did it and you cant do it from php itself


text:
Q: JSJaC+Openfire works only local so far I developed completey locally, having everything (Apache, Openfire, JSJaC application) on my laptop, running quite fine. Now I want to use remote server for Apache/Openfire. I did basically the same steps, incl. the whole http-bind stuff. I test the setting with simpleclient.html provided by JSJaC.
Now here's the deal, if I use the simpleclient directly on the remote server - e.g., http://here.domain.org/simpleclient.html - it works. If I use it locally - e.g., http://[local_machine]/simpleclient.html - and with the same settings I get an 503 (service unavailable). It seems to be more a network/Apache issue than Openfire/JSJaC one, but I'm not an expert.
My parameters for the simpleclient:

*

*HTTP Base:      http://here.domain.org/http-bind/

*JabberServer:   here.domain.org

So in my apache virtual host conf file I have the lines:

*

*AddDefaultCharset UTF-8

*ProxyReqests On

*ProxyPass /http-bind/ http://127.0.0.1:7070/http-bind/
So basically the http bind works since I can connect when the simpleclient.html resides on the server. What I tried so far:

*

*checked if 7070 open from extern: yes

*checked etc/hosts - here the relevant lines

*

*127.0.0.1  localhost

*123.123.123.123   here.domain.org  here

*checked Apache conf for restrictions: can't find any, basically i have an "Allow from all" everywhere (but I'm not completely sure where to look at)

By the way, with,e.g., Pidgin I can connect from my laptop to the remote server. Just the JSJaC simpleclient won't do. So I assume it's the http-bind that causes the trouble. I would understand if port 7070 weren't open, but it is.
Any hints or help are much appreciated!
Christian

A: Ok, I got it. It was a cross-domain scripting issue. I started looking into the JSJaC library and noticed that it makes XmlHttpRequests which by default won't work across different domains. I therefore had to allow this with Apache on the Openfire-Server. I added the follwing entries in the VirtualHost conf file:
    Header always set Access-Control-Allow-Origin "*"
    Header always set Access-Control-Methods "POST, GET, OPTIIONS"
    Header always set Access-Control-Allow-Credentials true
    Header always set Access-Control-Allow-Headers "Content-Type, *"

Of course the mod_headers module must be loaded for this.
I'm not sure which entries are actually required, I didn't try every combinations. I think the always is needed since the request to the http-bind address is a proxy thingy.


text:
Q: How to create calculator with bash? How to create calculator with bash ?
example
    read -p "calculator count: "  calc
    echo '$((calc))' | bc

i input
2+2

output
(standard_in) 1: illegal character: $

how to fix ?
I just want to make text input in the script, so for the addition of + , - , x - and / . I input manually
for example I want 2+2+1*3/2
After I enter, the result will appear

A: As already pointed out by Terrance, you need double quotes; otherwise, the $ sign is sent literally.
Also, remove the double parentheses which ask Bash to do the calculation. In which case you wouldn't need to pipe to bc, but Bash only does integer arithmetic.
So it should be either
echo "$((calc))" # evaluated by Bash

or
echo "$calc" | bc


text:
Q: How to display lightning checkboxGroup in 2 column without disturbing other slds form elements? What CSS would be required to make the items in a lightning:checkboxGroup display horizontally in two or three columns?
i have tried this Css
.THIS .slds-form-element__control {
display: grid !important;
grid-template-columns: 1fr 1fr !important;}

it displays checkboxGroup horizontally and the breaks it in two columns but it's affecting other lightning:input fields layout as well.

A: The following code resolved my issue.
Cmp:
 <div class=" multiSelect">
            <lightning:checkboxGroup aura:id="selectReason"
                                     required="true"
                                     label="Select Reason/s"
                                     options="{!v.options}"
                                     value="{!v.value}"
                                     onchange="{!c.handleReasonChange}"/>
            </div>

Css:
    .THIS .multiSelect .slds-form-element__control
{
    display: grid !important;
    grid-template-columns: 1fr 1fr !important;
}


text:
Q: Creating a parasitic Windows installation Okay, I have recently revived an old computer of mine, and had an idea I wanted to explore.
It's an old Gigabyte board with Intel Pentium 4 @3.0 GHz Prescott processor.
I also have two IDE hard drives.
So here is the idea:
I want to put Win XP on both of the drives to create a dual boot. Simple enough. The catch? One of them (let's call him the victim) mustn't know the other one (the parasite) exists. Let me explain further.
What are the conditions that have to be met?
First off, when booting up the computer, it must boot to the victim if nothing is done. If a condition is met, it gives you a choice or boots the parasite directly. The condition can be anything - an USB stick plugged in with some data, a CD-drive in the DVD-ROM, a specific button being pressed, anything really. The another problem that comes into play here is the IDE configuration. Due to the cable length, I can have one of two setups:
IDE1Master: HDD1
IDE1Slave: HDD2
IDE2Master: DVDROM
IDE2Slave: None
or
IDE1Master: DVDROM
IDE1Slave: HDD1
IDE2Master: HDD2
IDE2Slave: None
Be as it may, one of the HDD will always be a slave. I know there is a utility called GNU GRUB, a bootloader. I haven't had time to mess with it yet, but if I can make it to show the selection screen for a second (long enough for me to hit down arrow and enter) and then go to default boot if nothing selected, that would solve the first issue. Is it possible?
I think that is it. The point is that unaware user of the computer should happily use the victim without having the slightest idea of existance of another Windows installation. The more advanced the user I can fool, the better.
I think if I can hide parasitic installation when booting I can call it a successful project.
What do you think?

A: I think you should re-evaluate what it is your trying to achieve. Because I can assure you, that the solution does not involve a second "hidden" hard drive.
If your determined to go this route, and I don't see why you would be... I'd look into IDE ribbon cable switches. Make it a physical switch in the back of the desktop case.  Look up IDE cable select, certain ribbons had a dedicated line for this.


text:
Q: Firebase Cloud functions: manipulate image before sending to the user I would like to write a cloud firebase function capable of triggering when a user requests a specific image and before sending it to him modify it by applying a graphic filter. I don't want that filter is applied on the client side.

A: You would have to write a cloud function for that and call that instead of accessing the bucket directly. There is no way to interfere with the request directly to a bucket.
I have found a basic tutorial to send an image from a cloud function here, but I don't know if that completely fits your needs, so you might have to look for more elaborate tutorials.
To modify the image there are some JS libraries out there, I suggest you look into one of them. One of them is already included into cloud functions as it seems

A: I would strongly suggest you have a trigger that fires when the raw/original image is first saved, and use a Cloud Function to make your modifications and then store that result for the user to call directly.  Cold starts are always a possible issue with Cloud Functions, and even without that you would be adding another layer of latency into the user experience.
Note this works even with "live" isochronous code - when the user uploads the "original", trigger/call the cloud function to generate the filtered version.  This will overlap at least somewhat with the user interactions (especially if they have a few choices to make), possibly making the app feel more responsive.


text:
Q: Difference between dates returns weird results I'm calculating the difference in minutes between two date-time in that way:
long diff = time2.getTime() - time1.getTime();

return diff / (60 * 1000);

For a strange reason it returns a lower number of minutes than expected.
For example the difference between 2014-01-22 18:45:00 and 2014-01-22 18:03:00 is 41 minutes when it should be 42 minutes
What's the reason? How to fix it?
EDIT
The debugger show "2014-01-22 18:45:00.0" for date1 and "Wed Jan 22 18:03:31 GMT 2014" for date2. I don't know why it's showing different syntaxes.

A: If you try to divide by 60f * 1000, you will see a result of 41.something because getTime() takes into consideration the milliseconds as well, and as you can see these are not zeros in your date values.

A: Its rounding problem. Long truncates the decimal, you should use Double in this case if u want the exact number.

A: Like Oracle explains...
public long getTime()

Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date
It's a rounding problem. If you round the two 'times' (both upper or lower) you won't have any problem, but if not both will take in account the ms and your result can vary 1 minute (your minimum grain of detail). I would use the class double instead of long as @Nguyten Le has said.


text:
Q: chef logging of wget I have a chef recipe that looks something like:
Chef::Log.info('step1')
# do stuff

Chef::Log.info('step2')
bash "do_wget" do
  code <<-EOF
  wget somefile
  EOF
end

Chef::Log.info('step3')
# do stuff

The wget takes a while but the logging ends up looking like
step1
step2
step3
bash script runs #indicates that the bash script from step 2 is running

Is there a way to prevent the logging from step3 until the bash script is done executing?

A: You should get acquainted with Anatomy of Chef Run. It has 2 stages: compiling and executing.
No action is taken on the resources in the recipes at compiling stage - each evaluated resource is just taken and put into the Resource Collection. Plain Ruby code outside of resources is evaluated, however.
In execution stage it actually evaluates Resource Collection. But by this moment all your logging messages are already printed out.
If you need to run ruby code (including Chef logging) on execution stage, there is a special resource for that Ruby Block
ruby_block "Add logging step3" do
  block do
    Chef::Log.info('step3')
  end
  action :create
end

Another way may be, is to actually execute resource in compiling stage:
bash "do_wget" do
  code "wget somefile"
  action :nothing
end.run_action :run

Action :nothing is set to avoid running this resource twice (once in every stage).

A: You can use the log resource instead, which I understand runs at the execution stage as you require
log "step2" do
    :info
end

or simply
log "step 3"

http://docs.opscode.com/resource_log.html


text:
Q: How to see what Kerberos Encryption is being used? I need to show what encryption is being used for kerberos on Windows Server 2008 R2. Is there a command I can run?
Is kerberos also used for local Windows Server account authentication or is it only for Active Directory?

A: You control which encryption types are used by Kerberos in an Active Directory environment. This article details the various places that it can be set.
Kerberos is not used to authenticate access by local accounts. The SAM database on each local machine does. SAM controls local authentication and authorization.


text:
Q: How do I make certain actions to occur when a player choose a specific dialog choice while intereacting with an NPC? A player is having conversation with an npc .Now , the player selects a Dialog Choice.Then, some actions happen.How do i do that?I'm learning lua.I'm Novice.I'm tryingg my best.And another thing I need to know that to make it happen where I should put the script and Which type of script I should put.Thnx for your patience! :)

A: This should work for making the selected dialog box trigger an action:
game.Workspace.YourDialogBox.DialogChoiceSelected:connect(function(player,choice)
    if choice.Name == "Selection 1" then
        --Your Selection 1 Code Here
    elseif choice.Name == "Selection 2" then
        --Your Selection 2 Code here
    end
end)

Adjust your code according to where your dialog box is and what will happen to perform the action.
You can find more about it here: https://developer.roblox.com/en-us/articles/Usage-of-dialogs


text:
Q: Angular mat menu position Hi i would like to have a mat-menu open to the left.
i got some scratch code in stackblitz, here is the link
https://stackblitz.com/edit/angular-material-menu-position-aside-6ab669?file=src/app/menu-overview-example.html
the structure should like this
Menu -> Item 1 Item 2 Item 3
or the oppposite direction
Item 1 Item 2 Item 3 <- Menu
any ideas? thanks

A: The matMenuTrigger exposes an openMenu() function that can be called to open the menu programmatically.
stackblitz demo
So to achieve the desired effect:

*

*listen to the menuOpened event of the main trigger,

*when main trigger opens, call openMenu() on the sub-trigger.

The only issue is, that since the sub-trigger will open before the parent has finished animating, it will not position properly. So:

*use the setTimeout function to delay the opening of the sub-trigger.


text:
Q: IntelliJ Shouldn't Import * when Importing Goal:
Say I have a line of code: payout.setPayoutStatusType(PayoutStatusType.REJECTED); but PayoutStatusType is not imported in the models which currently look like this:
import models.ApprovedLead;
import models.IdentityProviderType;
import models.ImportJob;
import models.ImportJobStatus;
import models.Offer;
import models.OfferSource;
import models.OfferViewedStatus;
import models.PaymentAccount;
import models.PaymentAccountType;
import models.PayoutStatusType;
import models.Payout;
import models.PendingPayout;
import models.RawOffer;
import models.User;
import models.UserDevice;
import models.UserDeviceType;
import models.UserOffer;

My issue is if I click on PayoutStatusType, and have it create the import for this it will remove all the static imports, and just do it in one line: import models.* which I don't want it to do.
My question is this: How do I set up my IDE which is Intellij to just make it import models.PayoutStatusType

A: You can configure the threshold above which IntelliJ starts to 'import *':
Preferences > Editor > Code Style > Java > Imports > Class count to use import with '*'
It looks like your latest import has exceeded this threshold thereby causing IntelliJ to collapse numerous imports under a *.


text:
Q: Why won't my rvm allow me to switch to an alternative Ruby? Ubuntu already has Ruby 1.8.7 installed. Then I installed rvm and used it to install Ruby 1.9.2, which is the version I want to use. However, ruby -v always returns 1.8.7.
How do I get rvm to use Ruby 1.9.2?
bxu@vm-bxu:~$ rvm use 1.9.2
Using /usr/share/ruby-rvm/gems/ruby-1.9.2-p320
bxu@vm-bxu:~$ ruby -v
ruby 1.8.7 (2011-06-30 patchlevel 352) [x86_64-linux]

A: The Problem
RVM does its own installation magic, but in Ubuntu's case it doesn't always install to the right Bash startup file. You probably don't actually have RVM running properly; even though it's sort of installed.
The Fix
You need to make sure the following two lines are at the BOTTOM of your ~/.bashrc file.
[[ -s "$HOME/.rvm/scripts/rvm" ]] && . "$HOME/.rvm/scripts/rvm"
export PATH=$PATH:$HOME/.rvm/bin

Then restart your terminal emulator or log back in. Note that sourcing ~/.bashrc has been known not to work in some cases, so this step will save your sanity.
RVM should now be working properly. The last step is to set your default Ruby.
rvm --default use 1.9.2

Important Edit
As I've just been reminded, RVM breaks Ubuntu login shells by installing ~/.bash_login, which overrides your Ubuntu ~/.profile in login shells. Move the code over to your ~/.bashrc if you haven't already done so, then remove or rename ~/.bash_login.

A: From the terminal:
rvm use 1.9.2

A: on Ubuntu you need to enable login shell in your terminal emulator, we have a quite good documentation for this at rvm site:
https://rvm.io/integration/gnome-terminal/


text:
Q: Textbook[ ] is undefined after setting it equal to subscribing to Observable Heres how I am calling the GET HTTP method:
getTextbooks() :Observable<Textbook[]> {
    return this.http.get<Textbook[]>('http://localhost:3000/catalogue');
}

Which parses the HTTP response to Textbook[] and returns an observable
I then subscribe to the observable and get the data like so:

this.textbookService.getTextbooks().subscribe(
    (data: Textbook[]) => this.textbooks = data,
    (err: any) => console.log(err),
);

The weird thing is, checking in the Network tab in the Chrome inspecting tool shows that it indeed received an array of objects, each with the correct parameters, as well as a 200OK status. If I printed out data in the callback of the .subscribe method it also shows the array of Textbooks just fine. It is just when I try to set this.textbooks = data when I get that this.textbook is undefined. this.textbooks is also of type Textbook[], same as data[].
Any advice would be amazing, thank you!

A: You might be trying to print this.textbook outside the subscribe block
As the calls are async so please check only after the calls(i.e. subscribe block is resolved)
Therefore user this.textbook inside subscribe block
this.textbookService.getTextbooks().subscribe(
    (data: Textbook[]) => {
           this.textbooks = data;
           console.log(this.textbook);
           },
    (err: any) => console.log(err),
);


text:
Q: How can I feature test for a valid duration using Laravel's validation helpers? I am trying to write a Feature test that checks that the provided end_time does not occur before the provided start_time. I've spent the last few days; I think I've seen about every SO post and still having trouble getting it through my head.
I have been able to successfully test/validate based on a condition:
MyTest.php
/** @test */
public function a_blackout_that_does_not_close_the_location_requires_an_end_time()
{
    $table = 'my_table';

    $blackout = factory(Blackout::class)->create([
        'closed' => 0,
    ]);

    $this->assertDatabaseHas($table, [
        'end_time' => $blackout->end_time,
    ]);
}

MyController.php
public function store(Request $request) {
    $attributes = $request->validate([
        ...
        'date' => ['required'],
        'closed' => ['nullable'],
        'start_time' => ['required_if:closed,0'],  // works great
        'end_time' => ['required_if:closed,0'],    // works great
    ]);

    $blackout = new Blackout($attributes);

    ...
}

Now I want to make sure that any provided end_time is not before a provided start_time.
MyTest.php
/** @test */
public function a_blackout_end_time_cannot_be_before_the_start_time()
{
    $blackout = factory(Blackout::class)->raw([
        'closed' => 0,
        'start_time' => '08:00:00',
        'end_time' => '07:00:00',
    ]);

    $response = $this->post('api/v1/blackouts', $blackout)
        ->assertSessionHasErrors('end_time');
}

This is what I'm trying to do:
MyController.php
    public function store(Request $request) {
    $attributes = $request->validate([
        ...
        'date' => ['required'],
        'closed' => ['nullable'],
        'start_time' => ['required_if:closed,0'],
        'end_time' => ['required_if:closed,0|after:start_time'],
    ]);

    $blackout = new Blackout($attributes);

    ...
}

I keep getting an error in my test:

1) Tests\Feature\BlackoutsTest::a_blackout_end_time_cannot_be_before_the_start_time
  Session is missing expected key [errors].
  Failed asserting that false is true.

That suggests that it isn't getting the correct error(s) set/returned from the validation. I've tried a bunch of ways to format the start_time and end_time to try to compare.
Further in my controller, I'm able to compare the times relatively easily:
MyController.php
...
$start_time = strtotime($blackout->start_time);
$end_time = strtotime($blackout->end_time);

if ($end_time <= $start_time) {
    // Invalid duration
} else {
    $blackout->save();
}

...

I am struggling how to validate through the validator so I can leverage the error message(s) better.
Thank you for any suggestions!
EDIT
Thank you @Thomas Van der Veen. Clearly, I'm learning so while looking through the json examples I believe I'm doing a number of things wrong (big surprise).
I've updated my test to now use postJson instead of post. I'm checking for a 422 response and that there should be an end_time error.
/** @test */
public function a_blackout_end_time_cannot_be_before_the_start_time()
{
    $blackout = factory(Blackout::class)->raw([
        'closed' => 0,
        'start_time' => '08:00:00',
        'end_time' => '07:00:00',
     ]);

     $response = $this->postJson('api/v1/blackouts', $blackout)
         ->assertStatus(422)
         ->assertJsonValidationErrors('end_time');
 }

MyController.php
$attributes = $request->validate([
   ...
   'date' => ['required'],
   'closed' => ['nullable'],
   'start_time' => ['required_if:closed,0|date|'],
   'end_time' => ['required_if:closed,0|date|after:start_time'],
]);

...

$blackout->save();

return response()->json(['data' => $blackout], 201);

The test response is:

1) Tests\Feature\BlackoutsTest::a_blackout_end_time_cannot_be_before_the_start_time
  Expected status code 422 but received 201.
  Failed asserting that false is true.

Which tells me my validation is bad since it's getting through to a 201.
Thank you both for your help. I feel like I'm starting to talk myself in circles & I'm making this way harder than it is.

A: Thank you both for your suggestions! They both helped get me to this answer. Although I believe I am still writing/executing tests incorrectly
Here is the solution I ended up with, If there is a better way please let me know so I can update my answer.
I ended up writing a custom validation rule and passing in my time_start to compare the two times.
MyTest.php
/** @test */
public function a_blackout_end_time_cannot_be_before_the_start_time()
{
    $blackout = factory(Blackout::class)->raw([
        'closed' => 0,
        'time_start' => '08:00',
        'time_end' => '07:00',
    ]);

    $response = $this->postJson('api/v1/blackouts', $blackout)
        ->assertStatus(422)
        ->assertJsonValidationErrors('time_end');
}

MyController.php
public function store(Request $request)
{
    $attributes = $request->validate([
        ...
        'date' => ['required', new DateFormatRule], // Custom rule
        'closed' => 'nullable',
        'time_start' => 'required_if:closed,0',
        'time_end' => ['required_if:closed,0', new TimeDurationRule($request->time_start)],
    ]);

    $blackout = new Blackout($attributes);
    ...
}

TimeDurationRule.php
**
 * Create a new rule instance.
 *
 * @return void
 */
public function __construct($time_start)
{
    $this->time_start = $time_start;
}

/**
 * Determine if the validation rule passes.
 *
 * @param string $attribute
 * @param mixed $value
 * @return bool
 */
public function passes($attribute, $value)
{
    return strtotime($value) > strtotime($this->time_start);
}

/**
 * Get the validation error message.
 *
 * @return string
 */
public function message()
{
    return 'Time duration is invalid.';
}

In my test I am getting a 422 response as expected. I can verify things are working by changing the name of the expected error from time_end to time_end123 and I'll get an error -- saying It was expecting time_end not `time_end123.


text:
Q: How would you sample and store ultrasonic signals at 132 kHz using a microcontroller, Raspberry Pi, etc.? I am attempting to sample and store analog ultrasonic microphone data. I am sampling at 12-bits. My ADC can sample fast enough, but storing to QSPI NOR Flash IC proved too slow, as did transferring data out via 2.8 Mb/s UART to USB IC to a terminal program. I am attempting to sample and store data at a sample rate of about 132 kHz, so my sample and store time period should be no longer than 7.3 microseconds equates to a sampling frequency of about 137kHz.(The shortest period I achieved was 23.25 μs,) My goal for now is to be able to sample and store one second's worth of data sampled at 132 kHz or higher.
I am working with an STM32F446RET6 microcontroller. Any suggestions/tips are greatly appreciated. I am currently looking into trying QSPI flash again.
Thank You

A: Break up your storage problem into several parts, from fastest and slowest. The fastest storage is SRAM, followed by Flash, then off-board UART transfer. With a sample rate of 132 kHz, this will produce a total of 264,000 bytes (kHz = 1,000) in the 1 second capture time, but the STM32F446RET6 only has 128KB of SRAM, so it won't all fit. But it will fit into the slower internal Flash memory.
Fine, just create the largest circular buffer in SRAM that you can afford. Be sure to dial down heap and stack to get the maximum memory available for this circular buffer. Next, create linear buffer in internal Flash memory, then use the DMA feature of the chip to transfer from the SRAM buffer to the Flash buffer. The idea is that although the Flash memory is too slow, it will offload the SRAM buffer enough so that near the end of the 1 second capture window it will be clear enough to hold the remaining data.
Only after all the data is transferred to Flash memory, do you want to start the UART transfer so that none of the cycles are interrupted (wasted) in the Flash transfer which is most critical.
Also, take note that Flash memory likes to be updated (written to) in chunks, not bytes, for the most efficient transfer speed. So setup the DMA to transfer in these chunk sizes only. See here for writing to internal Flash memory.
Since the SRAM buffer is circular design, it may not be easy to use a DMA channel for the ADC to SRAM transfer, so just let the CPU do these transfers inside a tight loop or an interrupt service routine. The CPU is fast enough anyway that this is no longer critical.

A: Why do you want to store so much data?  Are you trying to store each waveform echo?  Why?  Typically an ultrasonic sensor sends chirps and waits for the echo of the spchirp 8 to 20 full wavelengths, then sends another string of chirps and processes the previous string.  Each burst of chirps is typically spaced just a bit longer in time than the time it would take for an echo to return from the maximum expected distance the microphone can sense.
Only the processed data is typically saved - not each waveform.


text:
Q: Comparing to Images (shape of the sihlohette image) I'm looking for a way to compare a number of silhouettes and determine which two are most alike, obviously I would like to do this in the most efficient way possible. I thought perhaps this could be done using the image magic morphology functionality, but perhaps I'm misunderstanding the function. http://www.imagemagick.org/Usage/morphology/#intro
Any thoughts?

A: Mathematical morphology is a technique used in digital image processing mostly for performing image shape analysis. Therefore it can be used for comparing two images to discover whether their shape is similar.
Various methods can be used to achieve this. Basic methods are Erosion and Dilatation and the others are more or less based on them. You can use iterations of Erosion with appropriately chosen structuring element (regarding the nature of the images) and obtain basic shape of the image and then compare it pixel-wise. Alternatively you can detect if something remains of the images or there is nothing left each iteration and based on that determine their similarity. This of course works only for some simple cases and more complex methods with some special treatments have to be implemented for common usage.
If you would like to use mathematical morphology for comparing images I recommend to familiarize yourself more with this concept by reading some related materials, e.g. Mathematical Morphology. There are also other ways you may find more suitable for resolving your task but the problem of comparing images is in general a very complicated issue and not straightforward at all.

A: A silhouette is a view of an object or scene as a solid shape of a single color, usually black. The shape therefore depicts the outline of the object, while the interior is featureless. It would have useful if you could have given examples of your test images. Thus when we have such simplified case of an image it would good to observe the spatial distribution of grayscale components of different sizes. This is efficiently obtained from the granulometry operation in mathematical morphology. This basically provides different scales of connected components in the image. You could look at this paper which uses the granulometry to characterize Human silhouettes using a dictionary learnt postive and negative human shapes.


text:
Q: call server function from jquery dialog Currently I'm using jQuery on my asp.net content page (using master).  I am creating a modal dialog using jquery.  The div that is defined with the following code

        <asp:Panel ID="Panel" runat="server">
            Is the information you have entered correct?

            <asp:Label>Some labels filled when the modal appears</asp:Label>
            <asp:button runat="server" OnClick="someServerSide_Function" Text="Submit" />
        </asp:Panel>

There is a HTML button that gets pressed, and when the button is pressed, it calls the following code
$("#example").dialog("open");

And the modal is defined with the following code:
$("#example").dialog({
                autoOpen: false,
                modal: true,
                height: 400,
                overlay: overlayCss,
                bgiframe: true
            });

The Modal gets filled when the HTML button is clicked, and the ASP.NET button does not call its server side function when it is clicked.  The Example div resides inside of the  tags, so it should be calling the server side function.  What could be wrong?

A: Not nearly enough info to help you probably... but try this link.
http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/
Edit:
It appears this question has been edited so I will edit my answer...
Use the above if you are wanting your button to call the serverside method from jquery without posting the page.
It now appears that you would be correctly calling a server-side method. (the whole page would submit.)
Have you set a break point in your serverside method and make sure that its being called (debugging)?
There really could be a lot wrong without seeing more of your code-behind.
You could also wire up the page with the Onit event with something like
this.Button1+=new EventHandler(Button1_Click);

(After giving your button an ID of "Button1")


text:
Q: How to create one node in py2neo correctly? I just test py2neo demo,but failed,code is :
from py2neo.data import Node, Relationship
import py2neo
g = py2neo.Graph('http:/172.18.0.52:7474', user='neo4j',password='123')
a = Node("Person", name="Alice")
b = Node("Person", name="Bob")
ab = Relationship(a, "KNOWS", b)
print(a)
g.create(a)

output is : (:Person {name: 'Alice'})
traceback is :

TypeError                                 Traceback (most recent call
  last)
  ~/miniconda2/envs/py35/lib/python3.5/site-packages/py2neo/internal/http.py
  in fix_parameters(parameters)
       70     try:
  ---> 71         dehydrated, = dehydrator.dehydrate([parameters])
       72     except TypeError as error:
~/miniconda2/envs/py35/lib/python3.5/site-packages/py2neo/internal/json.py
  in dehydrate(self, values)
      121
  --> 122         return tuple(map(dehydrate_, values))
~/miniconda2/envs/py35/lib/python3.5/site-packages/py2neo/internal/json.py
  in dehydrate_(obj)
      117             elif isinstance(obj, dict):
  --> 118                 return {key: dehydrate_(value) for key, value in obj.items()}
      119             else:
~/miniconda2/envs/py35/lib/python3.5/site-packages/py2neo/internal/json.py
  in (.0)
      117             elif isinstance(obj, dict):
  --> 118                 return {key: dehydrate_(value) for key, value in obj.items()}
      119             else:
~/miniconda2/envs/py35/lib/python3.5/site-packages/py2neo/internal/json.py
  in dehydrate_(obj)
      119             else:
  --> 120                 raise TypeError(obj)
      121
TypeError:
During handling of the above exception, another exception occurred:
TypeError                                 Traceback (most recent call
  last)  in ()
       10
       11 print(a)
  ---> 12 g.create(a)
~/miniconda2/envs/py35/lib/python3.5/site-packages/py2neo/database.py
  in create(self, subgraph)
      343         """
      344         with self.begin() as tx:
  --> 345             tx.create(subgraph)
      346
      347     def delete(self, subgraph):
~/miniconda2/envs/py35/lib/python3.5/site-packages/py2neo/database.py
  in create(self, subgraph)
      919             raise TypeError("No method defined to create object %r" % subgraph)
      920         else:
  --> 921             create(self)
      922
      923     def delete(self, subgraph):
~/miniconda2/envs/py35/lib/python3.5/site-packages/py2neo/data.py in
  db_create(self, tx)
      612
      613     def db_create(self, tx):
  --> 614         create_subgraph(tx, self)
      615
      616     def db_delete(self, tx):
~/miniconda2/envs/py35/lib/python3.5/site-packages/py2neo/internal/operations.py
  in create_subgraph(tx, subgraph)
      133     for labels, nodes in _node_create_dict(n for n in subgraph.nodes if n.graph is None).items():
      134         identities = _create_nodes(tx, labels, map(dict, nodes))
  --> 135         for i, identity in enumerate(identities):
      136             node = nodes[i]
      137             node.graph = graph
~/miniconda2/envs/py35/lib/python3.5/site-packages/py2neo/internal/operations.py
  in _create_nodes(tx, labels, data)
       84     label_string = "".join(":" + cypher_escape(label) for label in sorted(labels))
       85     cypher = "UNWIND $x AS data CREATE (_%s) SET _ = data RETURN id(_)" % label_string
  ---> 86     for record in tx.run(cypher, x=data):
       87         yield record[0]
       88
~/miniconda2/envs/py35/lib/python3.5/site-packages/py2neo/database.py
  in run(self, cypher, parameters, **kwparameters)
      838         try:
      839             if self.transaction:
  --> 840                 result = self.transaction.run(cypher, parameters, **kwparameters)
      841             else:
      842                 result = self.session.run(cypher, parameters, **kwparameters)
~/miniconda2/envs/py35/lib/python3.5/site-packages/neo4j/v1/api.py in
  run(self, statement, parameters, **kwparameters)
      603         if self.closed():
      604             raise TransactionError("Transaction closed")
  --> 605         return self.session.run(statement, parameters, **kwparameters)
      606
      607     def sync(self):
~/miniconda2/envs/py35/lib/python3.5/site-packages/py2neo/internal/http.py
  in run(self, statement, parameters, **kwparameters)
      288         self._statements.append(OrderedDict([
      289             ("statement", ustr(statement)),
  --> 290             ("parameters", fix_parameters(dict(parameters or {}, **kwparameters))),
      291             ("resultDataContents", ["REST"]),
      292             ("includeStats", True),
~/miniconda2/envs/py35/lib/python3.5/site-packages/py2neo/internal/http.py
  in fix_parameters(parameters)
       72     except TypeError as error:
       73         value = error.args[0]
  ---> 74         raise TypeError("Parameters of type {} are not supported".format(type(value).name))
       75     else:
       76         return dehydrated
TypeError: Parameters of type map are not supported

the output is not correspond with the demo:'(alice:Person {name:"Alice"})'

A: You maybe install the latest version (4.0.0) of py2neo. Some people met the same issue as you, his solution that you can follow py2neo issue 678.
Another solution is that you can install previous version, for example, pip install py2neo==3.1.2, it works for me.


text:
Q: How to increase resolution in ubuntu 15.10? using xrandr and updating nvidia drivers didn't work Friends,
I have spent 2 days already trying to get ubuntu work on my laptop. I am getting various problems with graphics. Upon installing from USB I cannot immediately enter due to "low-graphics mode" problem. I can sidestep it by adding nomodeset to the booting options, but the problems don't end there.
Now I am able to login, but the resolution is terrible. Typing xrandr in the console yields:
xrandr: Failed to get size of gamma for output default
Screen 0: minimum 1024 x 768, current 1024 x 768, maximum 1024 x 768
I tried to follow this thread in order to use xrandr to add a new resolution mode. In vain.
xrandr --newmode VGA1 "1920x1080_60.00" 173.00 1920 2048 2248 2576 1080 1083 1088 1120 -hsync +vsync
xrandr: unrecognized option '-hsync'
In another topic it has been suggested that I should get proper graphic card divers. When I installed nvidia drivers, I wasn't
able to even enter the login screen, it just went black immediately. I tried to purge and reinstall nvidia drivers but it did not help. Welp, I reinstalled ubuntu from my USB. Then I tried bumblebee, which I read were good nvidia drivers. After rebooting nothing happened, still low resolution with xrandr manipulations yielding nothing.
At this point I am very confused and feel rather deflated. The solution probably is somewhere there, I went through countless threads but just can't quite get it. If there is any information that you might find useful to solve it, I will be happy to provide it.
Computer Specs:
Model: Asus N551JM
Processor: Intel® Core™ i7-4710HQ CPU @ 2.50GHz × 8
VGA compatible controller: Intel Corporation 4th Gen Core Processor Integrated Graphics Controller (rev 06)
3D controller: NVIDIA Corporation GM107M [GeForce GTX 860M] (rev ff)

A: I just solved the problem accidentally...
For future generations, here is the solution:
After installing the bumblebee pack as explained here I rebooted ubuntu and forgot to boot it with "nomodeset". Somehow, now it works without it and everything is good ;)


text:
Q: Custom main nib file can't connect actions to targets On application launch, I receive the output: "Could not connect the action to target of class NSApplication" for each of the buttons I have created.
In my Info.plist file, I changed the Main nib file base name to MyWindowController.
In the corresponding MyWindowController.xib, my Application placeholder's class is NSApplication, and its delegate outlet is set to my main application delegate.
My File Owner placeholder's class is set to MyWindowController, and I have buttons set up to perform actions.
MyWindowController.xib is the only xib file in my project.
I'm not all that familiar with connections in xib files, and I'm not sure I understand the difference between an Application and a File Owner when there is only 1 xib file.
Basically, I just want the window I have created in MyWindowController.xib to appear upon app launch and for the outlets I have made with the File Owner to be connected to this window.
Any suggestions or ideas on how I should proceed?


text:
Q: Can't log any data from API call I'm pretty new to kotlin, and I feel pretty much overwhelmed by it. I'd like to ask - how I can display any data from MutableLiveData? I've tried to Log it, but it doesn't seem to work. I've already added the internet permission to the manifest. Here's the code:
ApiServices
interface ApiServices {
@GET("/fixer/latest/")
fun getRatesData(
    @Query("base") base: String,
    @Query("apikey") apikey: String
): Call<CurrencyModel>

companion object {
    private const val url = "https://api.apilayer.com/"
    var apiServices: ApiServices? = null

    fun getInstance(): ApiServices {
        if (apiServices == null) {
            val retrofit = Retrofit.Builder()
                .baseUrl(url)
                .addConverterFactory(GsonConverterFactory.create())
                .build()
            apiServices = retrofit.create(ApiServices::class.java)
        }
        return apiServices!!
    }
 }
}

Repository
class CurrencyRepository constructor(private val apiServices: ApiServices) {
    fun getLatestRates() = apiServices.getRatesData("EUR", "API_KEY");
}

ViewModel
  class CurrencyViewModel constructor(private val currencyRepository: CurrencyRepository) :
    ViewModel() {
    val currencyRatesList = MutableLiveData<CurrencyModel>()
    val errorMessage = MutableLiveData<String>()

    fun getLatestRates() {
        val response = currencyRepository.getLatestRates();
        response.enqueue(object : retrofit2.Callback<CurrencyModel> {
            override fun onResponse(
                call: retrofit2.Call<CurrencyModel>,
                response: Response<CurrencyModel>
            ) {
                currencyRatesList.postValue(response.body())
            }

            override fun onFailure(call: retrofit2.Call<CurrencyModel>, t: Throwable) {
                errorMessage.postValue(t.message)
            }
        })
    }
}

FactoryViewModel
class CurrencyViewModelFactory constructor(private val repository: CurrencyRepository) :
ViewModelProvider.Factory {

override fun <T : ViewModel?> create(modelClass: Class<T>): T {
    return if (modelClass.isAssignableFrom(CurrencyViewModel::class.java)) {
        CurrencyViewModel(this.repository) as T
    }else{
        throw IllegalArgumentException("Couldn't found ViewModel")
    }
 }
}

MainActivity
class MainActivity : AppCompatActivity() {

private val retrofitService = ApiServices.getInstance()
lateinit var viewModel: CurrencyViewModel

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    viewModel = ViewModelProvider(this, CurrencyViewModelFactory(CurrencyRepository(retrofitService)))
        .get(CurrencyViewModel::class.java)
    viewModel.currencyRatesList.observe(this, Observer {
        Log.d(TAG, "onCreate: $it")
    })
    viewModel.errorMessage.observe(this, Observer {
        viewModel.getLatestRates()
    })
 }
}

A: You never call viewModel.getLatestRates() in your onCreate() to fetch an initial value for your LiveData, so it never emits anything to observe. The only place you have called it is inside your error listener, which won't be called until a fetch returns an error.
Side note, I recommend naming the function "fetchLatestRates()". By convention, "get" implies that the function returns what it's getting immediately rather than passing it to a LiveData later when its ready.
And a tip. Instead of this:
class MainActivity : AppCompatActivity() {

  lateinit var viewModel: CurrencyViewModel

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    // ...
    viewModel = ViewModelProvider(this, CurrencyViewModelFactory(CurrencyRepository(retrofitService)))
        .get(CurrencyViewModel::class.java)
    //...
  }
}

You can do this for the same result:
class MainActivity : AppCompatActivity() {

  val viewModel: CurrencyViewModel by viewModels(CurrencyViewModelFactory(CurrencyRepository(retrofitService)))

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    // ...
  }
}


text:
Q: Heroku deployment of Fastapi (Python) running on uvicorn: Web process failed to bind to $PORT We have a python 3.9 fastapi server that we are trying to get running on uvicorn on heroku.
It comes up fine when we start it on a heroku run bash instance but when it launches normally on the dyno manifold the port doesn't bind.
heroku/web.1 Starting process with command `uvicorn app.main:app --workers 4 --port 42374`
app/web.1 INFO:     Uvicorn running on http://127.0.0.1:42374 (Press CTRL+C to quit)
app/web.1 INFO:     Started parent process [4]
app/web.1 INFO:     Started server process [13]
app/web.1 INFO:     Waiting for application startup.
app/web.1 INFO:     Started server process [10]
app/web.1 INFO:     Waiting for application startup.
app/web.1 INFO:     Started server process [12]
app/web.1 INFO:     Waiting for application startup.
app/web.1 INFO:     Started server process [11]
app/web.1 INFO:     Waiting for application startup.
app/web.1 INFO:     Application startup complete.
app/web.1 INFO:     Application startup complete.
app/web.1 INFO:     Application startup complete.
app/web.1 INFO:     Application startup complete.
heroku/web.1 Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch
heroku/web.1 Stopping process with SIGKILL
heroku/web.1 Process exited with status 137
heroku/web.1 State changed from starting to crashed

If I run it locally using Heroku CLI:
root@d2258955b223:/workspaces/app-service-cross-sell# heroku run bash
Running bash on ⬢ aci-sell-service... up, run.4472 (Hobby)
~ $ uvicorn app.main:app --workers 4 --port $PORT
INFO:     Uvicorn running on http://127.0.0.1:26281 (Press CTRL+C to quit)
INFO:     Started parent process [141]
INFO:     Started server process [144]
INFO:     Waiting for application startup.
INFO:     Started server process [145]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     Application startup complete.
INFO:     Started server process [143]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     Started server process [146]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
^Z
[1]+  Stopped                 uvicorn app.main:app --workers 4 --port $PORT
~ $ bg
[1]+ uvicorn app.main:app --workers 4 --port $PORT &
~ $ curl http://localhost:26281
INFO:     127.0.0.1:55674 - "GET / HTTP/1.1" 200 OK

App loads from:
if __name__ == "__main__":
    uvicorn.run(
        "main:app",
        host="0.0.0.0",
        port=config.PORT,
        reload=not config.DEBUG,
        debug=config.DEBUG,
        log_level=VLabLogger.get_log_level_based_on_env().lower(),
    )

A: I would suggest creating a Procfile having:
web: uvicorn main:app --host=0.0.0.0 --port=${PORT}

and let heroku handle the PORT.


text:
Q: Undefined Offset 1 error $div_odds = $div - > getElementsByTagName('div');
foreach($div_odds as $od) {
    $class_od = $od - > getAttribute('class');
    if ($class_od == 'CSegno') {
      $expolde = preg_split('/\n|\r\n?/', $div - > textContent);
      $part - > type = explode('Segno:', $expolde[3])[1];
      $part - > cote = str_replace(',', '.', preg_replace('/\s+/', '', $expolde[2]));
    }

It shows below error message:

'Undefined Offset 1'


text:
Q: how post and get specialchars in url? how post and get "&" symbol in url? in php. please help me ........

A: Encode data with urlencode. It will be decoded automatically when parsed into $_POST.

A: use urldecode
http://www.php.net/manual/en/function.urldecode.php
$searchword = urldecode($_GET['searchword']);

A: encoded as "%26".
u can use function urlencode()

A: Have you tried:
index.php?searchword=G%20%26%20G%20Tours


text:
Q: Closure of the complement, iteration, set identity
Let $A$ be a closed subset of a topological space $X$ and $A'=\overline{X\setminus A}$. Then holds $A'''=A'$

I want to proof this equality.
I might have $\subseteq$.
First of all $A'''=\overline{X\setminus (\overline{X\setminus (\overline{X\setminus A})})}$.
I want to show $A'''=A'$
Let $x\in A'''$.
Then $x\in\bigcap_{U\supseteq X\setminus (\overline{X\setminus (\overline{X\setminus A})})\\ U\, \text{closed}} U$
And similar:
$U\supseteq X\setminus \bigcap_{V\supseteq X\setminus (\overline{X\setminus A)}} V$
$V\supseteq X\setminus \bigcap_{W\supseteq X\setminus A} W$
Now suppose $x\notin \overline{X\setminus A}$.
[Basically it goes like this now. I spare you the whole argument here, it should be clear how it is done at this point, I hope.]
Then $x\notin\bigcap W\Rightarrow x\in V\Rightarrow x\notin U\Rightarrow x\notin\bigcap U$. Contradiction.
If this is wrong, let me know and I provide a rigorouse proof, if this is not understandable.
Now I want to proof $A'''\supseteq A'$.
But here I am kinda stuck...
Espacially I do not see where to involve that $A$ is closed.
Hints are appreciated.
Thanks in advance.

A: int A, interior of A;  cl A, closure of A;  S topological space.

int cl A = int cl int A.  Algebraic (set algebra) proof:
. . int cl A = int int cl A subset int cl int cl A
. . subset int cl cl A = int cl A

cl S\A = S - int A
A point by point proof can be done with a
series of a half dozen equivalent statements:
x in cl S\A iff ... iff x in S - int A.

Algebraic proof of A' = A"':
A' = cl S\A = S - int A
A" = cl int A
A"' = cl (S - cl int A) = S - int cl int A
. . = S - int cl int cl A
. . = S - int cl A = S - int A = A'.

Where is the fact that A is closed, used?

A: Let $C(s)=\overline s$ and $I(s)=int(s).$
Theorem: $CICI(s)=CI(s).$
Proof: (i). $CICI(s)=C(I(CI(s))\subset C(CI(s)) =CI(s).$
(ii). $CICI(s)=CI(C(I(s))\supset CI(I(s))=CI(s).$
Let $s^-=\overline s$ and $s^c=X$ \ $s.$  With the superscripts acting from left to right we have  $CI(s)=s^{c-c-}$ and $s'=s^{c-}=C(s^c).$
So $A'''=A^{c-c-c-}.$ Now since $A=A^-$ we have   $A^c=I(A^c).$ Therefore  $$ A' =C(A^c)=$$ $$=CI(A^c)= CICI(A^c)=$$ $$=CIC(I(A^c))=CIC(A^c)=$$ $$=CI(A^{c-})=$$ $$= (A^{c-})^{c-c-}=A^{c-c-c-}=A'''.$$
Sleight of hand: Change $A^c$ to $I(A^c)$ from the 1st to 2nd line  in order to apply the Theorem , and then change $I(A^c)$ back to $A^c$ in the third line.