text:
Q: Querying nested lists with LINQ instead of loops Lets say I have the following setup
Continent
--Countries
----Provinces
------Cities
A continent contains a list of many countries which contains a list of many provinces which contains a list of many cities.
For each nested list lets say I want to do a check (name length is greater than 5)
Instead of using this loop structure
var countries = dbSet.Countries.Where(c => c.Name.Length > 5);
foreach (var country in countries)
{
   country.Provinces = country.Provinces.Where(p => p.Name.Length > 5);
   foreach (var province in country.Provinces)
   {
      province.Cities = province.Cities.Where(ci => ci.Name.Length() > 5);
   }
}

How could I accomplish the same efficiently with LINQ?

A: Efficiently?  In terms of written code, sure, but we'll call that "cleanly".  In terms of execution, that's not a question you should be asking at this point.  Focus on getting the job done in code that's understandable and then "race your horses" to see if you really need to improve on it.
One thing I should caution is that LINQ is about querying, which doesn't mutate the source sequences.  You're assigning the filtered sequences back to the properties and that's contrary to LINQ principles.  The tag shows you're using Entity Framework so it's definitely not a good idea to do that because it uses its own collection types under the hood.
To answer your question, the SelectMany extension method loops on the projected sequence.  When it's translated to a database query, it translates to a join.
dbSet.Countries
    .Where(c => c.Names.Length > 5)
    .SelectMany(c => c.Provinces)
    .Where(p => p.Name.Length > 5)
    .SelectMany(p => p.Cities)
    .Where(ci => ci.Name.Length > 5)
    .Select(ci => ci.Name);

That'll give you the names of all cities where the country, province, and city names are all longer than 5 characters.
But that only gives you the names of the cities.  If you want to know each level of information, extension methods are difficult to use because you have to project "transparent identifiers" at each step along the way and it can get pretty cluttered.  Let the compiler do that for you by using LINQ syntax.
from c in dbSet.Countries
where c.Name.Length > 5
from p in c.Provinces
where p.Name.Length > 5
from ci in p.Cities
where ci.Name.Length > 5

That will do the same thing as above, except now, all your range variables are carried through the expression so you can do this:
select new
{
    CountryName = c.Name,
    ProvinceName = p.Name,
    CityName = ci.Name
};

...or whatever you want to do with c, p, and ci.

EDIT: Merged the second answer, which addressed questions in the comments, into this one.
In order to preserve the parent levels through the query, you need to project a container for the parent and the child each time you loop through a collection of child objects.  When you use LINQ syntax, the compiler does this for you in the form of a "transparent identifier".  It's transparent because your references to range variables "go right through" it and you never see it.  Jon Skeet touches on them near the end of Reimplementing LINQ to Objects: Part 19 – Join.
To accomplish this, you want to use a different overload of SelectMany this time, one that also takes a lambda to project the container you need.  Each iteration through the child items, that lambda is called  and passed two parameters, the parent and the current iteration's child item.
var result = dbSet.Countries
    .Where(c => c.Names.Length > 5)
    .SelectMany(c => c.Provinces, (c, p) => new { c, p })
    .Where(x1 => x1.p.Name.Length > 5)
    .SelectMany(x1 => x1.p.Cities, (x1, ci) => new { x1.c, x1.p, ci })
    .Where(x2 => x2.ci.Name.Length > 5)
    .Select(x2 => new
    {
        Country = x2.c,
        Province = x2.p,
        City = x2.ci
    })
    .ToList();

The x1 and x2 lambda arguments are the containers projected from the preceding SelectMany call.  I like to call them "opaque identifiers".  They're no longer transparent if you have refer to them explicitly.
The c, p, and ci range variables are now properties of those containers.
As a bonus note, when you use a let clause, the compiler's doing the exact same thing, creating a container that has all of the available range variables and the new variable that's being introduced.
I want to end this with a word of advice: Use LINQ syntax as much as possible.  It's easier to write and get right, and it's easier to read because you don't have all those projections that the compiler can do for you.  If you have to resort to extension methods, do so in parts.  The two techniques can be mixed.  There's art in keeping it from looking like a mess.


text:
Q: Routing issues in my AngularJs application I have given the route as '/second' to navigate into my second.html page, but when I'm clicking on the button, it's not navigating into the other page. I'm having this issue because of the URL, I think.
I want the URL to be http://127.0.0.1:5500/index.html#/second when I click on the button, but it's displaying the URL something like this: http://127.0.0.1:5500/index.html#!/#%2Fsecond. What could be the cause of the URL becoming something like this?

A: Try removing the / and make it only second. update the question with your router code for further assit.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Converting array with Different data type How to convert this in Javascript from:
[
   {
      "label": "Purok I",
      "y": "1"
   },
   {
      "label": "Purok II",
      "y": "1"
   },
   {
      "label": "Purok III",
      "y": "2"
   }
]

to:
[
   {
      label: "Purok I",
      y: 1
   },
   {
      label: "Purok II",
      y: 1
   },
   {
      label: "Purok III",
      y: 2
   }
]

Any help?

A: This method will update all numeric types in your objects automatically.

let arr = [{
    "label": "Purok I",
    "y": "1"
  },
  {
    "label": "Purok II",
    "y": "1"
  },
  {
    "label": "Purok III",
    "y": "2",
    "example": "432.23"
  }
];

// Map over your array of objects
arr = arr.map(obj => {
  // Map over all the keys in your object
  Object.keys(obj).map(key => {
    // Check if the key is numeric
    if (!isNaN(obj[key])) {
      obj[key] = +obj[key];
    }
  })
  return obj;
});
console.log(arr);

A: Make all stringified numbers into non-stringified numbers using map and destructuring like so:

const data = [
   {
      "label": "Purok I",
      "y": "1"
   },
   {
      "label": "Purok II",
      "y": "1"
   },
   {
      "label": "Purok III",
      "y": "2"
   }
];

const numbered = data.map(({ label, y }) => { return {label, y: parseInt(y)}});

console.log(numbered);
.as-console-wrapper { max-height: 100% !important; top: auto; }

EDIT
Turns out making string-less property names is impossible:

var obj = {
  foo: "bar",
  one: 1
};

console.log(obj);

A:

let  p = [
   {
      "label": "Purok I",
      "y": "1"
   },
   {
      "label": "Purok II",
      "y": "1"
   },
   {
      "label": "Purok III",
      "y": "2"
   }
]

let result = p.map(function(x) {
    x.y = Number(x.y);
    return x;
});

console.log(result);


text:
Q: Unity: Cannot Load/Save Player Pos So, in Unity I am trying to load the player's position from PlayerPrefs.
LOAD FUNCTION
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using System.IO;
using UnityEngine.UI;
using CI.QuickSave;

public class RELoadSave : MonoBehaviour
{

    public GameObject Player;

    public float x, y, z;
    private bool saving = false;

    private int Mode = 0;
    private Vector3 coordsem;
    private int count;

    protected FileInfo theSourceFile = null;
    protected StreamReader reader = null;
    protected string text = " "; // assigned to allow first line to be read below

    public Button btn;
    void Start()
    {
        x = PlayerPrefs.GetFloat("x");
        y = PlayerPrefs.GetFloat("y");
        z = PlayerPrefs.GetFloat("z");

        Vector3 LoadPosition = new Vector3(x, y, z);
        Player.transform.position = LoadPosition;
    }
    private void Awake()
    {

    }

    void Update()
    {

    }
    public void ResetScene()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().name);

    }

}

SAVE FUNCTION
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.IO;
using TMPro;
using UnityEngine.UI;
using CI.QuickSave;

public class SaveGame : MonoBehaviour
{
public float coordse;

public float x, y, z;

public GameObject Player;

// Start is called bsefore the first frame update
void Start()
{

}

// Update is called once per frame
void Update()
{

}

public void SaveGameCore()
{
    x = Player.transform.position.x;
    y = Player.transform.position.y;
    z = Player.transform.position.z;

    PlayerPrefs.SetFloat("x", x);
    PlayerPrefs.SetFloat("y", y);
    PlayerPrefs.SetFloat("z", z);

}

}
Things to note:

*

*these functions are NOT called inside the player

*running Unity 2019
This is meant to be applicable to a 3d FPS game, taht is what the code is for not a 2d game. BUT I am confused, but I probally made a simple mistake. If it is not replacatable, I can upload small assets from the game. It should be working but it isn't. The player also can only collide with 2d box coliders if that helps.

A: I checked your code and everything works fine
public float x,y,z;
public GameObject Player;
public Vector3 LoadPosition;
public void Save()
{
    x = Player.transform.position.x;
    y = Player.transform.position.y;
    z = Player.transform.position.z;

    PlayerPrefs.SetFloat("x_", x);
    PlayerPrefs.SetFloat("y_", y);
    PlayerPrefs.SetFloat("z_", z);

}
public void Load()
{
    x = PlayerPrefs.GetFloat("x_");
    y = PlayerPrefs.GetFloat("y_");
    z = PlayerPrefs.GetFloat("z_");

    LoadPosition = new Vector3(x, y, z);
    Player.transform.position = LoadPosition;
}

The problem may be related to the method of calling save or laod
Perhaps the problem is with the version of the unity you have, this is an unlikely possibility
Anyway, you can do without PlayerPrefs by saving the player data (Positino) in a text file inside the folder
Take a look at this reference for saving and Load


text:
Q: How to get Symbolic crash repost ios xcode 8 I am going to check my device crash log of iPhone 5s. But the crash logs are written in unsymbolic format, which is not able to understand.
i have already done the symbolic method using terminal as below

if you have any info related to this issue then please share with me..... :)

A: Try the following:
DEVELOPER_DIR=xcode-select -print-path ./symbolicatecrash -v igolive.crash igoliverel.app.dSYM


text:
Q: Windows Authentication SSO in ASP.NET Remote Web Application There is a requirement to implement Single Sign On (SSO) in our website so that users accessing it from the intranet won't have to type in their credentials.
The problem here is that the website is going to be hosted on the internet, on a remote server.
Is there some way this can be done?
--EDIT--
I looked at following link:
http://en.wikipedia.org/wiki/Active_Directory_Federation_Services
And the example scenario that is mentioned in there is exactly what we require.
Here is the detailed explanation on the situation:
There is an Active Directory Domain Controller that is used to authenticate users in the intranet.
Once the user logs into the machine, and opens up the remote website, the website should somehow verify that the user is already logged into the intranet using AD credentials and automatically allow access to the website.
Also, the website is supposed to be getting a Security Token that can be used to authenticate the user.

A: Of course, for example, Microsoft's way of doing that for connecting Office365 to your Intranet is called Active Directory Federation Services.
It is (as most single sign on solutions) not entirely straight forward, and it assumes a domain on your intranet, but since Office365 uses it, it is and will most likely continue to be well supported in the future.

A: It's just a matter of integrating your web app with the authentication provider that you are using for SSO.  The details are going to vary dramatically if your using OAuth vs. Shibboleth vs. ADFS vs. etc, so there really isn't enough information in your question to give a helpful answer.


text:
Q: Custom Site Creation with CSOM I have the need to customize the site creation process in SharePoint Online. Is this possible via an app using JavaScript CSOM? If so can anyone point me in the right direction.

A: Yes it's possible. If you're new to JavaScript, I recommend learning deferred's (promises) as they hold the trick to controlling the async firing order.   Here is a sample to get you started:
Here is a namespaced function that gets the id of a custom site template based on the template's name and then spins up a new site under the root based on that template (I omitted the errorHandler function for brevity, although this response is far from brief).
"Use strict";

var NAPP = window.NAPP || {};
NAPP.Automation = NAPP.Automation || {};

NAPP.Automation.Site = function () {
var createSite = function () {
    return $.Deferred(function (def) {
        var templateName = "My Custom Template Name";
        var templateID = "";

        getWebTemplateID(templateName);
        function getWebTemplateID(templateName) {
            var hostweburl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
            this.context = SP.ClientContext.get_current();
            var appContextSite = new SP.AppContextSite(this.context, hostweburl);
            this.web = appContextSite.get_web();
            var webTemp = this.web.getAvailableWebTemplates(1033, false);
            this.context.load(webTemp);
            this.context.executeQueryAsync(Function.createDelegate(this, gotWebTemplate), Function.createDelegate(this, errorHandler));
            function gotWebTemplate() {
                var enumerator = webTemp.getEnumerator();
                while (enumerator.moveNext()) {
                    var currentItem = enumerator.get_current();
                    var currID = currentItem.get_name();
                    var currTitle = currentItem.get_title();
                    if (currTitle === templateName) {
                        templateID = currID;
                        finishSiteCreation();
                    }
                }
            }
        }

        function finishSiteCreation() {
            siteName = $("#companyName").val(); // these come from a custom form I have on the default.aspx page of the app
            siteTitle = $("#siteName").val();

            $("#progressWrap").empty().append("
Creating subsite...
");
            var hostweburl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
            this.context = SP.ClientContext.get_current();
            var appContextSite = new SP.AppContextSite(this.context, hostweburl);
            this.web = appContextSite.get_web();

            var WCI = new SP.WebCreationInformation();
            WCI.set_webTemplate(templateID);
            WCI.set_description($("#companyDesc").val());
            WCI.set_title(siteName);
            WCI.set_url(siteTitle);
            WCI.set_language(1033);
            WCI.set_useSamePermissionsAsParentSite("false");
            this.newSite = this.web.get_webs().add(WCI);

            this.context.load(this.newSite);
            this.context.executeQueryAsync(
                Function.createDelegate(this, function () {
                    $("#progressWrap").append("
" + siteName+ " Site Created
");
                    def.resolve(this.newSite);
                }),
                Function.createDelegate(this, function (sender, args) { def.reject(sender, args); })
            );
        }
    });
};
return { createSite: createSite };
}();

It's important to note that the function returns a deferred object which signals that it's done and is ready for another. (Thank you sir; may I have another?)
And here is a function to create a group in that new site (spWeb object is passed down through the promise chaining in the initialization which I'll show later)
"use strict";

var NAPP = window.NAPP || {};
NAPP.Automation = NAPP.Automation || {};

NAPP.Automation.Groups = function () {
var createGroups = function (spWeb, groupName, permissionLevel) {
    return $.Deferred(function (def) {
        this.context = SP.ClientContext.get_current();
        this.groupCollection = spWeb.get_siteGroups();

        var permissionGroup = new SP.GroupCreationInformation();
        permissionGroup.set_title(groupName);
        permissionGroup.set_description("description");
        var oPermissionsGroup = this.groupCollection.add(permissionGroup);

        var rollDef = spWeb.get_roleDefinitions().getByName(permissionLevel);
        var collBind = SP.RoleDefinitionBindingCollection.newObject(this.context);
        collBind.add(rollDef);

        var assignments = spWeb.get_roleAssignments();
        var roleAssignment = assignments.add(oPermissionsGroup, collBind);

        this.context.load(oPermissionsGroup);
        this.context.executeQueryAsync(
            Function.createDelegate(this, function () {
                $("#progressWrap").append("
" + groupName + " Group Created
");
                def.resolve(oPermissionsGroup);
            }),
            Function.createDelegate(this, function (sender, args) {def.reject(sender, args);})
        );
    })
};
return { createGroups: createGroups };
}();

and here is how I call them to fire in the right order using promises on button click
    $("#someButton").click(function () {
    var spWebPromise = NAPP.Automation.Site.createSite();
    $.when(spWebPromise)// begin promise chaining
        .then(function (spWeb) { return createSiteGroups(spWeb);})
        .done(function (spWeb) {$("#progressWrap").append("
All done!
"); })
        .fail(function (sender, args) { $("#progressWrap").append("
Error: " + args.get_message() + "
"); });
});

Since I needed to create multiple groups for each site, I stuck the actual call to the namespace for the create groups inside it's own promise returning function so that multiple groups would be created asynchronously (when block notates all functions contained therein need to finish before the promise is fulfilled).
// promise firing order helpers
function createSiteGroups(spWeb) {
return $.Deferred(function (def) {
    $.when(
        NAPP.Automation.Groups.createGroups(spWeb, "Approver", "Read"),
        NAPP.Automation.Groups.createGroups(spWeb, "External Members", "Read"),
        NAPP.Automation.Groups.createGroups(spWeb, "Internal Members", "Edit"),
        NAPP.Automation.Groups.createGroups(spWeb, "Owners", "Full Control"),
        NAPP.Automation.Groups.createGroups(spWeb, "Read Only", "Read")
    )
    .done(function () {
        $("#progressWrap").append("
--- Groups Creation Complete ---
");
        def.resolve(spWeb);
    })
    .fail(function (sender, args) { def.reject(sender, args); });
});
}


text:
Q: I cannot add any function for my fragment's java files UPDATES
I added more java files just in case you find them helpful. I figured that I may need to write codes to connect between MainActivity.java and my fragments, but the codes I followed from several YouTube videos do not work. I would be greatly appreciated if you can write me a line of code to connect the fragment.
END OF UPDATES
Whenever I try to add functions in my fragment file, it does not work. I think I may miss some codes in MainActivity.java, but I have no idea what to add to make my fragment's java files work.
Here is my fragment's java file (I did not touch anything but added a simple function to show a check mark when a button is clicked):
package com.example.dailybible3;

import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link FragmentBible#newInstance} factory method to
 * create an instance of this fragment.
 */
public class FragmentBible extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public FragmentBible() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment fragment_bible.
     */
    // TODO: Rename and change types and number of parameters
    public static FragmentBible newInstance(String param1, String param2) {
        FragmentBible fragment = new FragmentBible();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_bible, container, false);
        Button btn_complete = (Button) view.findViewById(R.id.complete_button);
        btn_complete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                ImageView check_mark = (ImageView) view.findViewById(R.id.check_mark);
                int visibility = check_mark.getVisibility();
                if(visibility == View.VISIBLE)
                {
                    check_mark.setVisibility(View.INVISIBLE);
                }
                else
                {
                    check_mark.setVisibility(View.VISIBLE);
                }
            }
        });
        return view;
    }
}

Just in case, here is my xml file as well:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".FragmentBible"
    android:theme="@style/FontStyle">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/colorPrimary"
        android:orientation="vertical">

        <TextView
            android:id="@+id/white_background_round"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_centerInParent="true"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="10dp"
            android:layout_marginRight="10dp"
            android:layout_marginBottom="10dp"
            android:background="@drawable/white_background_round" />

        <RelativeLayout
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignTop="@+id/white_background_round"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="15dp">

            <TextView
                android:id="@+id/title_string"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/tab_text_2"
                android:textColor="@color/colorPrimary"
                android:textSize="45sp"
                android:textStyle="bold"/>

            <ImageView
                android:id="@+id/title_image"
                android:layout_width="70dp"
                android:layout_height="70dp"
                android:layout_alignTop="@+id/title_string"
                android:layout_alignBottom="@+id/title_string"
                android:layout_marginLeft="20dp"
                android:layout_toEndOf="@+id/title_string"
                android:background="@drawable/ic_bible_english" />

        </RelativeLayout>

        <ImageView
            android:id="@+id/button_background"
            android:layout_width="wrap_content"
            android:layout_marginTop="10dp"
            android:layout_height="30dp"
            android:layout_alignStart="@+id/white_background_round"
            android:layout_alignEnd="@+id/white_background_round"
            android:layout_marginRight="60dp"
            android:layout_marginLeft="60dp"
            android:layout_below="@+id/title"
            android:background="@drawable/light_background_round_english" />

        <Button
            android:id="@+id/niv"
            android:layout_width="wrap_content"
            android:layout_height="30dp"
            android:layout_alignTop="@+id/button_background"
            android:layout_alignStart="@+id/button_background"
            android:layout_alignBottom="@+id/button_background"
            android:layout_toStartOf="@+id/centerline"
            android:text="NIV"
            android:textColor="@color/colorPrimary"
            android:textStyle="bold"
            android:background="@android:color/transparent"/>

        <Button
            android:id="@+id/kjv"
            android:layout_width="wrap_content"
            android:layout_height="30dp"
            android:layout_alignTop="@+id/button_background"
            android:layout_alignEnd="@+id/button_background"
            android:layout_alignBottom="@+id/button_background"
            android:layout_toEndOf="@+id/centerline"
            android:text="KJV"
            android:textColor="@color/colorPrimary"
            android:textStyle="bold"
            android:background="@android:color/transparent"/>

        <TextView
            android:id="@+id/centerline"
            android:layout_width="1dp"
            android:layout_height="10dp"
            android:layout_alignBottom="@+id/button_background"
            android:layout_centerHorizontal="true"
            android:layout_below="@+id/title"
            android:background="@color/colorPrimary"
            android:layout_margin="5dp"
            android:layout_alignTop="@+id/button_background"
            android:elevation="10dp"/>

        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_above="@+id/complete_button"
            android:layout_below="@+id/button_background"
            android:layout_alignStart="@+id/white_background_round"
            android:layout_alignEnd="@+id/white_background_round"
            android:layout_marginStart="20dp"
            android:layout_marginTop="20dp"
            android:layout_marginBottom="20dp">

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent">

                <TextView
                    android:id="@+id/subtitle1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Leviticus 2"
                    android:textColor="@color/colorPrimaryLight"
                    android:textSize="25sp"
                    android:textStyle="bold"/>

                <TextView
                    android:id="@+id/subtitle_text1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/subtitle1"
                    android:layout_alignStart="@+id/subtitle1"
                    android:layout_marginEnd="20dp"
                    android:text="1) When anyone brings a grain offering to the Lord, their offering is to be of the finest flour. They are to pour olive oil on it, put incense on it 2) and take it to Aaron's sons the priests. The priest shall take a handful of the flour and oil, together with all the incense, and burn this as a memorial portion on the altar, a food offering, an aroma pleasing to the Lord."
                    android:textColor="@color/colorPrimary"
                    android:textSize="15sp"
                    android:textStyle="bold" />

                <TextView
                    android:id="@+id/subtitle2"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/subtitle_text1"
                    android:text="Leviticus 2"
                    android:textColor="@color/colorPrimaryLight"
                    android:textSize="25sp"
                    android:textStyle="bold"/>

                <TextView
                    android:id="@+id/subtitle_text2"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/subtitle2"
                    android:layout_alignStart="@+id/subtitle2"
                    android:layout_marginEnd="20dp"
                    android:text="1) When anyone brings a grain offering to the Lord, their offering is to be of the finest flour. They are to pour olive oil on it, put incense on it 2) and take it to Aaron's sons the priests. The priest shall take a handful of the flour and oil, together with all the incense, and burn this as a memorial portion on the altar, a food offering, an aroma pleasing to the Lord."
                    android:textColor="@color/colorPrimary"
                    android:textSize="15sp"
                    android:textStyle="bold"/>

                <TextView
                    android:id="@+id/subtitle3"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/subtitle_text2"
                    android:text="Leviticus 2"
                    android:textColor="@color/colorPrimaryLight"
                    android:textSize="25sp"
                    android:textStyle="bold" />

                <TextView
                    android:id="@+id/subtitle_text3"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/subtitle3"
                    android:layout_alignStart="@+id/subtitle3"
                    android:layout_marginEnd="20dp"
                    android:text="1) When anyone brings a grain offering to the Lord, their offering is to be of the finest flour. They are to pour olive oil on it, put incense on it 2) and take it to Aaron's sons the priests. The priest shall take a handful of the flour and oil, together with all the incense, and burn this as a memorial portion on the altar, a food offering, an aroma pleasing to the Lord."
                    android:textColor="@color/colorPrimary"
                    android:textSize="15sp"
                    android:textStyle="bold"/>

            </RelativeLayout>

        </ScrollView>

        <TextView
            android:id="@+id/complete_button_background"
            android:layout_width="wrap_content"
            android:layout_height="60sp"
            android:layout_alignBottom="@+id/white_background_round"
            android:layout_alignRight="@+id/white_background_round"
            android:layout_alignLeft="@+id/white_background_round"
            android:layout_marginRight="75dp"
            android:layout_marginLeft="75sp"
            android:layout_marginBottom="20sp"
            android:background="@drawable/light_background_round_english" />

        <ImageView
            android:id="@+id/check_mark"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBottom="@+id/complete_button"
            android:layout_alignLeft="@+id/complete_button"
            android:layout_alignRight="@+id/complete_button"
            android:layout_alignTop="@+id/complete_button"
            android:elevation="10dp"
            android:visibility="invisible"
            android:src="@drawable/ic_check_english"/>

        <TextView
            android:id="@+id/complete_button_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Complete"
            android:layout_alignTop="@+id/complete_button_background"
            android:layout_alignLeft="@+id/complete_button_background"
            android:layout_alignBottom="@+id/complete_button_background"
            android:layout_marginLeft="10sp"
            android:layout_marginTop="10sp"
            android:layout_marginBottom="10sp"
            android:gravity="center"
            android:textSize="30sp"
            android:textColor="@color/colorPrimary"
            android:textStyle="bold"/>

        <Button
            android:id="@+id/complete_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignRight="@+id/complete_button_background"
            android:layout_alignBottom="@+id/complete_button_background"
            android:layout_alignTop="@+id/complete_button_background"
            android:layout_marginTop="7sp"
            android:layout_marginBottom="7sp"
            android:layout_marginRight="10sp"
            android:layout_marginLeft="10sp"
            android:layout_toEndOf="@+id/complete_button_text"
            android:background="@drawable/white_button_round" />

    </RelativeLayout>

</FrameLayout>

And here is MainActivity.java:
package com.example.dailybible3;

import android.os.Bundle;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.tabs.TabLayout;

import androidx.viewpager.widget.ViewPager;
import androidx.appcompat.app.AppCompatActivity;

import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import com.example.dailybible3.ui.main.SectionsPagerAdapter;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());
        ViewPager viewPager = findViewById(R.id.view_pager);
        viewPager.setAdapter(sectionsPagerAdapter);

        TabLayout tabs = findViewById(R.id.tabs);
        tabs.setupWithViewPager(viewPager);

    }
}

Also, here is the adapter:
package com.example.dailybible3.ui.main;

import android.content.Context;

import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;

import com.example.dailybible3.R;

/**
 * A [FragmentPagerAdapter] that returns a fragment corresponding to
 * one of the sections/tabs/pages.
 */
public class SectionsPagerAdapter extends FragmentPagerAdapter {

    @StringRes
    private static final int[] TAB_TITLES = new int[]{R.string.tab_text_1, R.string.tab_text_2, R.string.tab_text_3, R.string.tab_text_4, R.string.tab_text_5};
    private final Context mContext;

    public SectionsPagerAdapter(Context context, FragmentManager fm) {
        super(fm);
        mContext = context;
    }

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a PlaceholderFragment (defined as a static inner class below).
        return PlaceholderFragment.newInstance(position + 1);
    }

    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        return mContext.getResources().getString(TAB_TITLES[position]);
    }

    @Override
    public int getCount() {
        // Show 5 total pages.
        return 5;
    }
}

And here is PlaceHolderFragment.java:
package com.example.dailybible3.ui.main;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.example.dailybible3.R;

/**
 * A placeholder fragment containing a simple view.
 */
public class PlaceholderFragment extends Fragment {

    private static final String ARG_SECTION_NUMBER = "section_number";

    private PageViewModel pageViewModel;

    public static PlaceholderFragment newInstance(int index) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(ARG_SECTION_NUMBER, index);
        fragment.setArguments(bundle);

        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        pageViewModel = ViewModelProviders.of(this).get(PageViewModel.class);
        int index = 1;
        if (getArguments() != null) {
            index = getArguments().getInt(ARG_SECTION_NUMBER);
        }
        pageViewModel.setIndex(index);
    }

    @Override
    public View onCreateView(
            @NonNull LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View root = null;

        switch(getArguments().getInt(ARG_SECTION_NUMBER))
        {
            case 1:
                root = inflater.inflate(R.layout.fragment_main, container, false);
                break;
            case 2:
                root = inflater.inflate(R.layout.fragment_bible, container, false);
                break;
            case 3:
                root = inflater.inflate(R.layout.fragment_notes, container, false);
                break;
            case 4:
                root = inflater.inflate(R.layout.fragment_alarm, container, false);
                break;
            case 5:
                root = inflater.inflate(R.layout.fragment_records, container, false);
                break;
        }
        return root;
    }
}

And here is the PageViewModel.java (which I am not quite sure why it is needed):
package com.example.dailybible3.ui.main;

import androidx.arch.core.util.Function;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Transformations;
import androidx.lifecycle.ViewModel;

public class PageViewModel extends ViewModel {

    private MutableLiveData<Integer> mIndex = new MutableLiveData<>();
    private LiveData<String> mText = Transformations.map(mIndex, new Function<Integer, String>() {
        @Override
        public String apply(Integer input) {
            return "Hello world from section: " + input;
        }
    });

    public void setIndex(int index) {
        mIndex.setValue(index);
    }

    public LiveData<String> getText() {
        return mText;
    }
}

Any help is greatly appreciated!


text:
Q: Send a queryset from Django views to JQuery I want to send a JsonResponse of a queryset from Django views to JQuery but I am not getting any data from the JQuery side.
This is my views file add_field_views.py :
from django.http import  JsonResponse
def drop_down_requests(request):
    text = request.POST['text']
    print("---->", text)
    from captiq.financing_settings.models import ChoiceGroup
    response = ChoiceGroup.objects.get(slug="Ja/Nein")
    output = JsonResponse(response,safe=False)
    print("output -", output)
    return output

this is where I declared the URL in urls.py inorder for the Jquery to GET the data from the views :
urlpatterns = [

    path('my-ajax-test/', add_field_views.drop_down_requests, name='ajax-test-view'),
]

project urls.py:
frontend_urls = []
for module_name, module_data in FRONTEND_MODULES.items():
    frontend_urls.append(re_path(
        module_data['url'],
        XFrameSameOriginView.as_view(template_name=module_data['view']),
        name=module_name))

urlpatterns = i18n_patterns(
    path('admin/', admin_site.urls),
    path('admin/log_viewer/', include(
        ('log_viewer.urls', 'log-viewer'), namespace='log-viewer')),
    path('admin/docs/', include('docs.urls')),
    path('_nested_admin/', include('nested_admin.urls')),
    path('accounts/', include(
        ('accounts.urls', 'accounts'), namespace='accounts')),
    path('api-auth/',
         include('rest_framework.urls', namespace='rest_framework')),

)

api_v1_patterns = [
    path('financing/', include(
        ('financing.urls', 'financing'), namespace='financing')),
    path('financing-settings/', include(
        ('financing_settings.urls', 'financing_settings'),
        namespace='financing_settings')),
    path('partners/', include(
        ('partners.urls', 'partners'), namespace='partners')),
    path('accounts/', include(
        ('accounts.urls', 'accounts'), namespace='accounts')),
    path('customers/', include(
        ('customers.urls', 'customers'), namespace='customers')),
]

urlpatterns += [
    path('api/v1/', include((api_v1_patterns, 'api'), namespace='api')),
    path('', RedirectView.as_view(url='loan-application/auth')),
    path('notifications/', include(
        'notifications.urls', namespace='notifications')),
] + frontend_urls

if settings.ENABLE_ROSETTA:
    urlpatterns += i18n_patterns(
        path('admin/rosetta/', include('rosetta.urls')),
    )

if settings.DEBUG:
    urlpatterns += static(
        settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

then is my JQuery which is waiting for the queryset data or JSON data :
window.addEventListener('load', function () {
    (function ($) {
        "use strict";
        $(document).ready(function () {

            $("#id_depending_field").change(function (event) {
                console.log("am here man");
                const valueSelected = this.value;
                $.ajax({
                    type: "POST",
                    url: 'my-ajax-test/',
                    data: {
                        csrfmiddlewaretoken:
                        document.getElementsByName('csrfmiddlewaretoken')[0].value,
                        text: valueSelected
                    },
                    success: function callback(response) {
                        console.log("____________", response)
                    }
                });
            })

        });
    })(django.jQuery);
});

With the code above am not able to get JSON data in JQuery, Instead I get a weird HTML output below :
<link rel="stylesheet" type="text/css" href="/static/css/notifications.css">

.

What am I doing wrong here ?

A: when you use relative path it is easy to lead your urls to wrong place. at your page your ajax will call for /en/admin/financing_settings/field/add/my-ajax-test/.
you can save exact url on your html page with data-* attribute.
In your example add data-ajax_url attribute to your #id_depending_field (or any other element)
data-ajax_url="{% url "api:financing_settings:ajax-test-view" %}" - url must be like this as i understand your routing
and then in your ajax code instead of url: 'my-ajax-test/', use url: $(#id_depending_field).data('ajax_url')
this will always give you exact url from any page where you load your .js file. And later if you decide to refactor your project and change url path it will keep all changes for you without changing html or js code

A: Use absolute URL when sending AJAX request:
$.ajax({
  type: "POST",
  url: '/my-ajax-test/',
  data: {
  ...
})

Apparently, you were sending it to /en/admin/financing_settings/field/add/my-ajax-test/ cause it was relative


text:
Q: Center only specific text/button on bootstrap " navbar menu I have a functionnal narbar menu using Boostrap 3.
I want to change the location of the 'sign in' and 'sign up button' here that are now on the right to the center of the menu (horizontally speaking).
I have been reading many SO posts but they usually only explain how to globally center ALL the elements of the header or I don't manage to apply what they say to my SPECIFIC CASE.
could you tell me what to change in the code below to have this working?
Here is the code:
html

        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">

        </button>

            My App

                          login

                            Sign up Free

Cool, you need explanations?

test

About Us

Team

Press

The CSS:
.navbar {
  margin-bottom: 0px;
 }

.navbar-brand {
    font-size     : 2.4em;
    letter-spacing: -4px;
    padding             :   15px 45px;
    @media (max-width: 768px) {
        padding: 15px 25px;
    }
}

.navbar-nav {
  margin: 0px;
}

.navbar-default {
    background   : none repeat scroll 0 0 black;
    border-bottom: 0 none;
    filter       : none;
    padding-right: 5px;
}

.navbar-default .navbar-brand {
    color         : white;
    &:hover             { color: white;}
}

Here is the code : http://www.bootply.com/3yzojgyQdj#
Thanks!

A: Remove

    login

    Sign up Free

from

and place them in a justified navbar, before that:

        login

        Sign up Free

LE: I added this to your css:
.navbar-collapse {
    float: right;
}
.navbar-default .container {
    text-align: center;
}
.navbar-justified {
    float: none;
    display: inline-block;
}

Bootply.


text:
Q: Making/forcing the Validation to fail by adding custom error Not Working in Laravel I am trying to make the Validation fail. I have tried the following:
UserController.php
public function add_user(Request $request)
{
$messsages = array(
    'email.unique' => 'Email already exists',
    'email.required' => 'Email is missing',
    'valid_from.date_format' => 'Valid from date invalid. mm/dd/yyyy e.g. 12/13/2014',
    'valid_to.date_format' => 'Valid to date invalid. mm/dd/yyyy e.g. 12/13/2014',
    'valid_to.required' => 'Valid to date is missing',
    'cnic.min' => 'CNIC is 15 characters long. Do not forget hyphens 35212-XXXXXXX-X',
    'cnic.max' => 'CNIC is 15 characters long. Do not forget hyphens 35212-XXXXXXX-X',
    'cnic.regex' => 'CNIC include hyphens 35212-XXXXXXX-X'
);

$rules = array(
    'name' => 'required',
    'email' => 'required|email|unique:users',
    'valid_from' => 'required|date_format:m/d/Y',
    'valid_to' => 'required|date_format:m/d/Y',
    'phone' => 'numeric',
    'cnic' => [
    'min:15',
    'max:15',
    'regex:/\d{5}-\d{7}-\d{1}/'
    ]
);

$validator = Validator::make($request->all(), $rules, $messsages);

//Check year
$y_from = substr($request->valid_from, -4); $y_from = (int)$y_from;
$y_to = substr($request->valid_to, -4); $y_to = (int)$y_to;
if($y_from >= 2038 || $y_to >= 2038) //HERE I ADD CUSTOM ERROR
{
    $validator->getMessageBag()->add('maxyear', 'Invalid date. Maximum value of Year = 2038');
    //$validator->errors()->add('maxyear', 'Invalid date. Maximum value of Year = 2038'); //Doesnt work as above
}

if ($validator->fails()) { //DOESNT WORK
    $messages = $validator->messages();
    return Redirect::route('userAdd')->withErrors($messages);
}

$user = new User;
$user->name = $request->name;
/* Save other model data */

$user->save();
Session::flash('userCreated', 'User Created Successfully');

return redirect('/pending_users');
}

The $validator->fails() goes true somehow and validation does not fail..
I have tried a solution like:
if($y_from >= 2038 || $y_to >= 2038)
{
    //$validator->getMessageBag()->add('maxyear', 'Invalid value for Year in date. Max year = 2038');
    //$validator->errors()->add('maxyear', 'Invalid date. Maximum value of Year = 2038');
    $rules['unreal_input'] = 'required';
    $messages['unreal_input.required'] = 'Invalid date. Maximum value of Year = 2038';
}

$validator = Validator::make($request->all(), $rules, $messsages);

It is Ugly as in View it always gives default error "unreal_input is required field". HELP!!
UPDATE
It was typo I used $messsages with 3 s

A: You changes are good so that you add $rules['unreal_input'] and $messages['unreal_input.required']
However you are having a typo, See $messsages vs $messages. In one case there are 3x "s" other case there are only 2x so it is different array.


text:
Q: Open sets in topology and metric spaces Let $\tau$ = { $\emptyset,[0,1],\mathbb{R}$}
($\mathbb{R},\tau$) is a topological space, right? Since the intersection of any of the sets in $\tau$ is itself in $\tau$, and same for the union.  But doesn't this make [0,1] an open set w.r.t. $\tau$, conflicting with [0,1] being closed in $\mathbb{R}$?
Thanks!

A: Which set is "open" or "closed" depends on the topology of the space and in fact is the topology of the space. In your topology $\tau$ the set $[0,1]$ is open, but in the standard topology on $\mathbb R$, it is in fact closed.
The standard topology on $\mathbb R$ is induced by the metric $d: (x,y) \mapsto |x-y|$. Here induced means that we use this metric to define a collection of open sets (called a basis) which generate a topology. In particular these open balls are defined as $$B_r(x) = \{p \in \mathbb R \mid d(x,p) < r\}.$$ This definition works for any metric over any space. The open balls of $\mathbb R$ under the Euclidean metric are just the open intervals.


text:
Q: Simple barplot of variables in DF using a loop Not having much experience at all writing loops, I'm looking to automate (with a loop) something I do frequently with all new datasets: create boxplots and histograms of each variable, as well as calculate descriptive statistics, for the latter, I tend to use both describe (Hmisc) and/or stats (fileds).
Ideally, I'd like to have the loop produce one boxplot for each appropriate variable.  My loop below produces only one boxplot and returns the error:
Error: no function to return from, jumping to top level
What am I getting wrong?  Also, if anyone could point me to a reference/website that may straighten out my insufficient loop-writing ways, I'd love the help.
Thanks!
Chris
y <- LETTERS[as.integer(rnorm(100, mean=5, sd=1))]
z <- LETTERS[as.integer(rnorm(100, mean=10, sd=1))]
x <- round(rnorm(100, mean=5, sd=2.5),2)
data <- as.data.frame(cbind(x,y,z))

A<- do.call("cbind", lapply(data, class))
B<- as.vector( A[1,])
C <- grep("character|factor", B)

for (i in 1:length(C)) {
  x <- C[i]
  counti <- table(data[,x])
  y <- barplot(counti, main=paste("Barplot for var", x))
  return(y)}

A: You can not use "return" in the loop, it is used in functions. Also you might want to make pauses between plots:
par(ask=T)
for (i in 1:length(C)) {
  x <- C[i]
  counti <- table(data[,x])
  y <- barplot(counti, main=paste("Barplot for var", x))
  y
}

A: The first thing you should unlearn is the as.data.frame(cbind()) mistake. It forces all the columns to be of the same class, thereby defeating any benefits of the dataframe structure.
sapply(data, class)
       x        y        z
"factor" "factor" "factor"

It's also going to be simpler to just use A<- sapply(data, class) as above and get a vector instead of that tortured pass through cbind. And as others have mentioned return works for regular functions but not inside a for-loop. If you were going to do it with a for-loop, you need to have a structure to gather the results of the barplot calls and a list is the natural one because you cannot be sure they will all be the same length. This might be an alternate route:
y <- LETTERS[as.integer(rnorm(100, mean=5, sd=1))]
z <- LETTERS[as.integer(rnorm(100, mean=10, sd=1))]
x <- round(rnorm(100, mean=5, sd=2.5),2)
data <- data.frame(x=x,y=y,z=z)
CC <- grep("character|factor", sapply(data, class))
y <- list()
 for (i in seq_along(CC) ) {
   x <- CC[i]
   counti <- table(data[,x])
   y <- c(y, list(barplot( counti, main=paste("Barplot for var", x))))
   }
 y
#------------
[[1]]
     [,1]
[1,]  0.7
[2,]  1.9
[3,]  3.1
[4,]  4.3
[5,]  5.5
[6,]  6.7

[[2]]
     [,1]
[1,]  0.7
[2,]  1.9
[3,]  3.1
[4,]  4.3
[5,]  5.5
[6,]  6.7

A: I think something with lapply may be nicer:
C <- grep("character|factor", B)

FUN <- function(vec, num){
  if (dev.interactive()) dev.new()
  counti <- table(vec)
  y <- barplot(counti, main=paste("Barplot for var", num))
  return(y)
}

lapply(C, function(i) FUN(data[, i], i))


text:
Q: Adjusting the vertical position of the limits of a sum Is there a way to vertically adjust the lower limits of the two sums below, such that 'p' and 'q' are vertically aligned?
\sum_{p=1}^{\mathcal{M}}\sum_{q\in\mathfrak{N}_p^+}

EDIT: As per egreg's comment below, I tried
\sum_{p=1\vphantom{\mathfrak{N}_p^+}}^{\mathcal{M}}\sum_{q\in \mathfrak{N}_{p}^+}
This results in

However, I would prefer to shift the second lower limit up to the first, than the other way round. I tried
\sum_{p=1}^{\mathcal{M}}\sum_{q\in\mathfrak{N}_{p}^+\vphantom{p=1}},
but this does nothing.

A: You can equalize the two subscripts by using a phantom.
I like more the (more complex) second suggestion where the + is smashed at the top, so the two subscripts are a bit nearer the summation sign.
\documentclass{article}
\usepackage{amsmath,amssymb}

\begin{document}

Original
\[
\sum_{p=1}^{\mathcal{M}}\sum_{q\in\mathfrak{N}_p^+}
\]

First suggestion
\[
\sum_{p=1\vphantom{q\in\mathfrak{N}_p^+}}^{\mathcal{M}}\sum_{q\in\mathfrak{N}_p^+}
\]

Second suggestion
\[
\sum_{p=1\vphantom{q\in\mathfrak{N}_p^{\smash[t]{+}}}}^{\mathcal{M}}\sum_{q\in\mathfrak{N}_p^{\smash[t]{+}}}
\]

\end{document}

For producing the rule on the baseline I used a trick not shown in the code above.


text:
Q: Android: No application can perform this action (ACTION_SEND) first of all I saw the same problem I have, solved here. But even with the answeres there, I didn't solve it. And I couldn't find a place to add comment. Only answer, and being an answer I'm not sure people will be notified with it. that's why I'm creating a new Question. Sorry for that :S
I'm new to Android world, and I'm trying basic stuff.
This may seem too childish I know, but I can't figure out what the problem is.
I'm trying to open one app to send an email. Wether the native app or not.
I'm using a real device (Sony Ericsson Xperia X10) and I have at least two apps capable or handling email.
I have the following code:
    Intent intent = new Intent(android.content.Intent.ACTION_SEND);
    intent.setType("message/rfc822"); //same with "setType("text/plain")
    intent.setData(Uri.parse(((EditText)findViewById(R.id.emailAddress)).getText().toString()));
    thisActivity.startActivity(Intent.createChooser(intent, "Choose program"));

I'm stuck on this and it's making me crazy! I've been searching for a solution, but everybody seems to resolve this matter with the "setType" method. This is frustrating because it's such a "small task"... :/
Thank you very much and I'm sorry for "double question".

A: You do not use setData() here. Use EXTRA_EMAIL. Or, use ACTION_SENDTO instead of ACTION_SEND, though then you will need to ensure that you have the mailto: scheme in your Uri.


text:
Q: Wiring multiple beans with the same dependency via Spring Boot @Configuration In older Spring MVC apps, where you'd specify application.xml and declare your app's beans so that Spring DI could instantiate them and wire them together, you might have something like this:
<bean id="chargeFactory" class="com.example.myapp.ChargeFactory" />

<bean id="paymentService" class="com.example.myapp.DefaultPaymentService">
  <ref id="chargeFactory"/>
</bean>

<bean id="chargeAuditor" class="com.example.myapp.ChargeAuditor">
  <ref id="chargeFactory"/>
</bean>

Which might help wire up the following code:
public interface PaymentService {
    public void makePayment(Payment payment);
}

public class DefaultPaymentService implements PaymentService {
    @Autowired
    private ChargeFactory chargeFactory;

    @Override
    public void makePayment(Payment payment, String key) {
        Charge charge = chargeFactory.createCharge(key);
        charge.doCharge(payment);
    }
}

public class ChargeAuditor {
    @Autowired
    private ChargeFactory chargeFactory;

    public void auditAllCharges(String key) {
        List<Charge> charges = chargeFactory.getAllCharges(key);
        // blah whatever
    }
}

How do you accomplish the same bean wiring in Spring Boot with the @Configuration class? For example:
@Configuration
public class MyAppInjector {
    @Bean
    public ChargeFactory chargeFactory() {
        return new ChargeFactory();
    }

    @Bean
    public PaymentService paymentService() {
        return new DefaultPaymentService(chargeFactory());
    }

    @Bean
    public ChargeAuditor chargeAuditor() {
        return new ChargeAuditor(chargeFactory());
    }
}

This might work but introduces some issues:

*

*It would force me to have to write value constructors for all my classes, which goes against everything I see in literally every tutorial/article I've come across. Plus, if I had to do that, then there's no real value to @Autowired anyways...

*At this point I'm essentially doing "DIY DI", which is OK, except I'm trying to deliberately use Spring DI :-)

*Every time I call chargeFactory() I'm getting a new (prototype-style) ChargeFactory instance. Maybe I want a singleton. Using this approach I have to hand-roll my own singleton implementation.

Sure, I can do all of this, but I feel like I'm flagrantly misusing/misunderstanding how @Configuration is supposed to be used, because it seems like I'm introducing a whole lot of DIY/homegrown code to solve something Spring DI should be able to do for me.
How would I reference the chargeFactory bean and wire it into both the "provider methods" for the paymentService and chargeAuditor beans? Again, looking for the Java-based @Configuration solution instead of writing an XML document to define the wirings.
I found this article which seems to be the only tutorial/documentation (surprisingly) on wiring Spring Boot apps via @Configuration (which leads me to believe there might be other/better methods...), but it does not address:

*

*How to specify singleton vs prototype bean instantiation patterns

*If multiple instances of a bean-class exist, how do I specify which instance gets wired into which dependency?

*How do I get around not defining value constructors for all my classes, and just let Spring/@Autowired inject fields automagically?

A: When you call chargeFactory() , spring won't create new instance everytime. Give it a try and see. Same object will be returned. Anyways
You can do something like this.
@Bean
public PaymentService paymentService(ChargeFactory chargeFactory) { return new DefaultPaymentService(chargeFactory); }


text:
Q: kafka streams example throws a class cast exception, serde windowed -> string. How to set the proper Serde? I'm attempting to reproduce this example.   My topology is:
@Bean("myTopo")
    public KStream<Object, Object> getTopo(@Qualifier("myKConfig") StreamsBuilder builder) {
        var stream = builder.stream("my-events");
        stream.groupByKey()
                .windowedBy(TimeWindows.of(Duration.ofMinutes(2)))
                .count()
                .suppress(Suppressed.untilWindowCloses(Suppressed.BufferConfig.unbounded()))
                .toStream()
                .foreach((k, v) -> {
                    System.out.println("k + v = " + k + " --- " + v);
                });

I've set the serde and the windowed serde internal classes in the config:
        ...
        props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass());
        props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, JsonSerde.class);
        ...
        props.put(JsonDeserializer.VALUE_DEFAULT_TYPE, JsonNode.class);
        props.put(StreamsConfig.DEFAULT_WINDOWED_KEY_SERDE_INNER_CLASS, Serdes.String().getClass());
        props.put(StreamsConfig.DEFAULT_WINDOWED_VALUE_SERDE_INNER_CLASS, JsonSerde.class);
        var config = new KafkaStreamsConfiguration(props);
        return new StreamsBuilderFactoryBean(config);

The error I get is
org.apache.kafka.streams.errors.StreamsException: ClassCastException invoking Processor.
Do the Processor's input types match the deserialized types?
Check the Serde setup and change the default Serdes in StreamConfig or provide correct Serdes via method parameters.
Make sure the Processor can accept the deserialized input of type key:
   org.apache.kafka.streams.kstream.Windowed,
and value:
   org.apache.kafka.streams.kstream.internals.Change.

with underlying cause
java.lang.ClassCastException: class org.apache.kafka.streams.kstream.Windowed
cannot be cast to class java.lang.String (org.apache.kafka.streams.kstream.Windowed is in unnamed module of loader 'app';
java.lang.String is in module java.base of loader 'bootstrap')

I see count() returns KTable<Windowed<Object>, Long>.  So it looks like the problem is it wants a Windowed<String> serde for the key.  Apparently, DEFAULT_WINDOWED_KEY_SERDE_INNER_CLASS isn't sufficient.
How do I create and set this?

A: I think I ran into this bug:
https://issues.apache.org/jira/browse/KAFKA-9259
I added a Materialized to the count() method
        var store = Stores.persistentTimestampedWindowStore(
                "some-state-store",
                Duration.ofMinutes(5),
                Duration.ofMinutes(2),
                false);
        var materialized = Materialized
                .<String, Long>as(store)
                .withKeySerde(Serdes.String());

Now the code runs without exception.


text:
Q: linq query to get dependent data in one connection using entity framework 6 I have the following SQL Statements:
DECLARE @UserID INT

SELECT Col1, Col2, Col3, @UserID = UserID
FROM Users
WHERE UserName = <username> AND Password = <password>

SELECT Col1, Col2, Col3
FROM ClientUser
WHERE UserID = @UserID

There are two select statements in the above queries, one to get the UserID,other column information from Users table and second one to get information from another table based on @UserID value. How to write a linq query on entity framework context to do this selection without connecting to database multiple times?

A: Lets assume that you have two classes, User and ClientUser that are part of your entity framework model.  They might look something like this.
public class User
{
    public int UserId { get; set; }
    public string Col1 { get; set; }
    //More to be here

    public virtual ICollection<ClientUser> Clients { get; set; }
}

public class ClientUser
{
    public int ClientId { get; set; }
    public int UserId { get; set; }

    public virtual User User {get; set;}
}

The default situation would have you working with lazy loaded since I have these defined as Virtuals.  If you know you need more, just do something like this
var query = YourContext.Users.Get().Include(x => x.Clients);

Then add what you need to the query.  By using "include" it ensures that EF pulls the data eagerly rather than lazily.


text:
Q: Unique migration safe user id in firebase auth I'm using firebase auth in my android app. What should be my unique user id in case of google and facebook login which I can associate with a user so that if in future we migrates our auth process to our own servers, we will be able to identify users ?
I know I'm currently getting a unique uid and an idp token but I'm not sure they are going to be same after migration.


text:
Q: Traversing of table in jquery Hello I am new to jquery I stuck in table traversing.I know simple traversing but I dont in this how to do it. my code is:

                        1000

                                        2000

I want the price only 1000 not price from variant div and also I want image src.I dont need a price from variant div.How can I do it.

A: In this case you could use the ":first" pseudo-class like so:
$('#compare tr .prc:first').text()


text:
Q: How do I seperate AdView and NestedScrollView from each other and stop them from overlaping in android studio? I am trying to create a space for my adView banner ad in android studio but the adView is overlapping my widget NestedScrollView, and is covering the words at the bottom which are in the NestedScrollView. All of my xml code is encased in a widget ConstraintLayout. How do I seperate the adView and NestedScrollView widget from overlapping one another? This is the current format of my android studio activity_main.xml page
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@color/grey"
    tools:context=".MainActivity">

    <androidx.core.widget.NestedScrollView
        android:id="@+id/ScrollView"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

</androidx.core.widget.NestedScrollView>
    <com.google.android.gms.ads.AdView
        xmlns:ads="http://schemas.android.com/apk/res-auto"
        android:id="@+id/adView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_alignParentBottom="true"
        ads:adSize="BANNER"
        ads:adUnitId="ca-app-pub-3940256099942544/6300978111"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent">
    </com.google.android.gms.ads.AdView>

</androidx.constraintlayout.widget.ConstraintLayout>

A: Your NestedScrollView's height is set to match_parent this makes it the size of the ConstraintSet.
If you set it to 0dp and constrain top to top of the parent and bottom to top of the
adView it would layout with the two separated.
    <androidx.core.widget.NestedScrollView
        android:id="@+id/ScrollView"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toTopOf="@id/adView"  >


text:
Q: Encryption in iPhone with 3DES I need encrypt a NSString with 3DES and i cant do it. Its return me a big NSString in result:
ccStatus = CCCrypt(kCCEncrypt,
                   kCCAlgorithm3DES,
                   kCCOptionECBMode | kCCOptionPKCS7Padding ,
                   vkey, //"123456789012345678901234", //key
                   kCCKeySize3DES,
                   vinitVec,// vinitVec, //"init Vec", //iv,
                   vplainText, //"Your Name", //plainText,
                   plainTextBufferSize,
                   (void *)bufferPtr,
                   bufferPtrSize,
                   movedBytes);

NSString *result;
NSData *myData = [NSData dataWithBytes:(const void *)bufferPtr length:(NSUInteger)movedBytes];
result = [myData base64Encoding];

NSLog(@"%@", result);

A: Try this.. It worked for me.
    NSData *data = [NSString dataUsingEnconding:NSASCIIStringEncoding];
    NSData *key = [self create3DesKey]; //This should be 24 characters, or 24 bytes

    const void *vplainText;
    size_t plainTextBufferSize;
    plainTextBufferSize = [data length];
    vplainText = (const void *)[data bytes];

    CCCryptorStatus ccStatus;
    uint8_t *bufferPtr = NULL;
    size_t movedBytes = 0;

    bufferPtr = (uint8_t *) malloc( [data length] * sizeof(uint8_t));
    memset((void *)bufferPtr, 0x0, [data length]);

    NSString *initVec = @"init_Vec";

    const void *vkey = (const void *) [key bytes];
    const void *vinitVec = (const void *) [initVec UTF8String];

    ccStatus = CCCrypt(kCCEncrypt,//encryptOrDecrypt,
                       kCCAlgorithm3DES,
                       plainTextBufferSize % 8 == 0 ? kCCOptionECBMode : KCCOptionPKCS7PAdding , //
                       vkey, //this should 24 bytes from 0x00 to 0xFF
                       kCCKeySize3DES,
                       vinitVec, //"init Vec", //iv,
                       vplainText, //This should be a multiple of 8 bytes or you will have to use KCCOptionPKCS7PAdding
                       plainTextBufferSize,
                       (void *)bufferPtr,
                       [data length],
                       &movedBytes);

NSString *result;
NSData *myData = [NSData dataWithBytes:(const void *)bufferPtr length:(NSUInteger)movedBytes];
result = [myData base64Encoding];

NSLog(@"%@", result);

This function should be used to create the key the proper way:
-(NSData*)create3DesKey
{
NSMutableData *mData = [[NSMutableData alloc] init];
    NSMutableData *mAuxData = [[NSMutableData alloc] init];

    for(int i = 0; i < 16; ++i)
    {
        u_int32_t aux = arc4random() % 255;

        [mData appendBytes:&aux length:1];

        if(i < 8)
        {
            [mAuxData appendBytes:&aux length:1];
        }
    }

    [mData appendData:mAuxData];

    return mData;
}

I've been working around with it myself. Note that, the createkey function, creates a EDE key, which states that the first 8 bytes of the key is exactly equal to the 8 last bytes. It could also be created in a way that all 3 blocks of 8 bytes are the same, or completely different. You should check which one your server processes.
Hope it helps.


text:
Q: How to restrict mailman list subscriptions to certain domains? Is there any way to restrict a mailman mailing list to only allowing subscriptions from one specific domain?
I know how to ban specific email addresses or domains from subscribing, but is there a way to ban all domains that aren't, say, example.com? Or maybe a couple specific domains?
We're starting to get hit by subscription attempts to some of our lists from what I'm sure are spammers on botnets1 and it's annoying list owners. Some lists are configured with a subscribe_policy of "Require approval" or "Confirm and approve" because the lists are intended to be only for our local users and it would be nice to minimize the annoyance of the list owners by automatically rejecting subscriptions from outside email addresses that won't be allowed to subscribe by the list owner anyways.
We can't simply restrict access to the local networks because we have lists intended for a worldwide audience and some of our "local" users can be anywhere.

1 One email address subscribes to a couple dozen unrelated lists from different IPs over a few hours; then the next day another round with a new email address and different IPs. In a few cases list owner has emailed them a question about why they were signing up for the list and received no reply.

A: Mailman uses Python's regular expression engine, which is flexible enough to match everything except a certain domain.
Put something like this in the ban_list for the list: ^(?!.*example\.edu) or: ^(?!.*(example\.edu|example\.com))
If lists are restricted and getting spam subscriptions, you may want to not advertise the list in mailman (make the link available elsewhere). Setting the mailing list subscription policy to "Confirm and Approve" instead of "Approve" so that spammers have to handle a piece of email before the list owner is annoyed can help, too.

A: Other answers will not stop an email address like "enemy@xxxexample.com". This will: ^(?!.*[@.]example\.com) (assumes all subdomains of example.com are okay). To apply run:
config_list -i <(echo 'ban_list = [ "^(?!.*[@.]example\.com)$", ]' ) listname

A: Some regex foo should do the trick. Example on the Berkeley MailMan page - https://calmail.berkeley.edu/docs/mailman/regexp.html#settings

A: See the GNU Mailman Wiki how to restrict membership to a single domain -
only emails from that domain will be able to subscribe:
Go to the mailing list administration privacy options, for example in redhat.com:
https:// listman.redhat.com/mailman/admin/your-mail-list/privacy/subscribing
In the Ban list enter:
^.*@(?!redhat\.com$)


text:
Q: Using navigationView with tabLayout So I've recently been working on updating my app to use the new material design support library. My application has one main activity with a drawerLayout and navigation view. The main content of app is shown in a frameLayout, through fragments. However, I am trying now to add material tabs to one of the navigation drawer's fragments. However, I am not sure how to implement this while keeping my fragments in the nav drawer functioning. A good example of what I am trying to achieve is shown below:

In this app (Google play music), only some of the navigation drawer's items have tabs while others do not. So my question is, how would I implement this? (Not looking for code, just an overview of how my layout should be organized)

To recap/clarify:
  I have a main layout with a frameLayout (for my app's content), and a navigationView (for navigating the different item fragments). I then have a listener which replaces the main layout's frameLayout with the item's respective fragment. Now, I need to add tabs to just one of these fragments (to navigate between 4 other fragments). I am also using a toolbar which I include as a separate layout.

Any advice is appreciated. I'm sorry if my description is a little confusing; I will clarify any necessary details.

A: Ok suppose your NavigationView has two options, the first one displays the fragment with tabs (tab layout) and the second one displays just a fragment with a toolbar. You have two options then:

*

*You can have a main layout with just a frame layout and replace it with all what you want

*You can have a main layout with coordinator layout -> app bar -> toolbar -> tab layout and a frame layout to put content

I prefer the second option to avoid having to always configure the toolbar so this is what I did once:
<!-- layout_main -->
<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <android.support.design.widget.CoordinatorLayout
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.design.widget.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="?attr/colorPrimary"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
                app:layout_scrollFlags="scroll|enterAlways"/>

            <android.support.design.widget.TabLayout
                android:id="@+id/tab_layout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:visibility="gone"
                app:tabGravity="fill"
                app:tabMode="fixed" />

        </android.support.design.widget.AppBarLayout>

        <FrameLayout
            android:id="@+id/main_content"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior" />

    </android.support.design.widget.CoordinatorLayout>

    <!-- The NavigationView -->
    <fragment
        android:id="@+id/navigation_fragment"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:name="some.path.to.the.NavigationViewFragment"
        tools:layout="@layout/fragment_navigation_view" />

</android.support.v4.widget.DrawerLayout>

As you see I change the visibility of TabLayout to "gone" so that the fragment with tabs take care to set as visible. The Fragment with the tabs just have the ViewPager in the Layout:
<!-- fragment_with_tabs -->
<android.support.v4.view.ViewPager
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/view_pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

Now the fragment with tabs initialize the ViewPager with the fragments for each page:
@Override
public onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    // The getChildFragmentManager() is Very important! Because fragments inside fragments are
    // not supported with the tipical fragmentManager, it requires NestedFragments and those
    // uses a childFragmentManager(). In other case a strange behaviour occurs
    ViewPagerAdapter adapter = new ViewPagerAdapter(getChildFragmentManager());
    adapter.addFragment(new TabOneFragment(), "Tab 1");
    adapter.addFragment(new TabTwoFragment(), "Tab 2");
    viewPager.setAdapter(adapter);

    tabLayout = (TabLayout) getActivity().findViewById(R.id.tab_layout);
    tabLayout.setVisibility(View.VISIBLE);
    tabLayout.setupWithViewPager(viewPager);
}

And finally do whatever you want in your TabFragments, this works fine for me and I hope this be useful for you too. Sorry for some problem with code syntax, I develop android with Kotlin and not with Java.

A: I can't recommend what Yiyo suggested. If you are going to have Fragments with different layouts, you should let the Fragments customize these layouts in the XML. This is why the introduction of Toolbar made so much sense for Android development. In the future, you might even have more requirements that differ between each Fragment. Some of them might not want a Toolbar, some of them might need another View above the Toolbar, some of them will have a RecyclerView that you would like to be accessible to the CoordinatorLayout and AppBar so that the scrolling behavior works properly.
I recommend you to put only a FrameLayout as the content of your DrawerLayout (as Yiyo mentioned in point 1). Here you will load each Fragment from the callbacks of the NavigationView.
<android.support.v4.widget.DrawerLayout
    ...
    android:fitsSystemWindows="true"
    >

    <FrameLayout
        android:id="@+id/drawer_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

    <android.support.design.widget.NavigationView
        ...
        />

</android.support.v4.widget.DrawerLayout>

In each Fragment's XML you will put, if required by that Fragment, a Toolbar. In your tabbed Fragment's XML you will put the TabLayout, and if you so wish, the CoordinatorLayout and AppBarLayout. From each Fragment that has a Toolbar, you will set the Toolbar as the ActionBar:
Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
AppCompatActivity activity = (AppCompatActivity) getActivity();
activity.setSupportActionBar(toolbar);

That's all there is to it. Of course you don't want to repeat yourself in every Fragment, so you can, for example, put this code in a DrawerFragment and subclass it for fragments with a Toolbar. You will also want to put your Toolbar XML configuration in a single file and include it in the Fragment's XML <include layout="@layout/toolbar" />. Or you might want to remove the Toolbar from some fragments, or change its color, theme, etc.

A: You can do it like this. I have checked by doing it myself and it works very well
Step 1 : Create a layout of your main activity like this

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appBarLayout" android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar" android:layout_width="match_parent"
            android:layout_height="wrap_content" android:background="@color/blue"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
            android:titleTextAppearance="@style/TextAppearance.AppCompat.Small"
            app:layout_scrollFlags="scroll|enterAlways" />

        <android.support.design.widget.TabLayout
            android:id="@+id/tab_layout" style="@style/FreeWiFiTabLayout"
            android:layout_width="match_parent" android:layout_height="wrap_content"
            android:layout_gravity="center" android:background="@color/blue"
            android:visibility="gone" android:fitsSystemWindows="true"
            android:minHeight="?attr/actionBarSize" />
    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/wifi_type_pager" android:layout_width="match_parent"
        android:layout_height="match_parent" android:clipToPadding="false"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
<fragment android:id="@+id/navigation_drawer"
    android:name="com.easyway.freewifi.NavigationDrawerFragment"
    android:layout_width="wrap_content" android:layout_height="match_parent"
    android:layout_gravity="start|bottom" android:layout_marginTop="?attr/actionBarSize"
    tools:layout="@layout/navigation_drawer_fragment" />

Step 2 :
In your activity you need to set onpagechangelistener on your viewpager:
 viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
  @Override
  public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

  }

  @Override
  public void onPageSelected(int position) {
        if(position ==0){
          tabLayout.setVisibility(View.GONE);
        }else{
          tabLayout.setVisibility(View.VISIBLE);
        }
  }

  @Override
  public void onPageScrollStateChanged(int state) {

  }
});

After this you need to add
 viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
Step 3 :
This is how you can make your adapter for viewpager :
public class WiFiPagerAdapter extends FragmentPagerAdapter {
    private final List registeredFragments = new ArrayList<>();
public WiFiPagerAdapter(final FragmentManager fm) {
  super(fm);
}

@Override
public Fragment getItem(final int pos) {
  Fragment fragment;
  fragment = WiFiFragment.newInstance(pos);
  registeredFragments.add(pos, fragment);
  return fragment;
}

@Override
public int getCount() {
  return tabLayout.getTabCount();
}

public List<Fragment> getRegisteredFragmentsList() {
  return registeredFragments;
}

@Nullable
public Fragment getRegisteredFragment(final int position) {
  final Fragment wr = registeredFragments.get(position);
  if (wr != null) {
    return wr;
  } else {
    return null;
  }
}

@Override
public void notifyDataSetChanged() {
  super.notifyDataSetChanged();
  for (int i = 0; i < registeredFragments.size(); i++) {
    WiFiFragment wiFiFragment = ((WiFiFragment) registeredFragments.get(i));
    wiFiFragment.setWiFiFragmentRecyclerViewAdapter();
  }
}

}


text:
Q: Length of root strings is at most 4 Let $\Phi$ be a root system. In his Introduction to Lie algebras and Representation Theory, J. Humphreys proves that if
$$\beta-p\alpha,\dots,\beta,\dots,\beta+q\alpha$$
is the $\alpha$-root string through $\beta$, then $$\frac{2(\beta,\alpha)}{(\alpha,\alpha)}=p-q.$$
Then, he states that it follows "at once" that root strings are of length at most four.
I dont get why. Of course, we know that $-4\le 2(\beta,\alpha)/(\alpha,\alpha)\le 4$, but then length of the root string is $p+q+1$, not $p-q$...

A: Here is a slight refinement of Sid's argument. Using Humphreys'  notation we know that $-3 \le \langle \alpha,\beta \rangle \le 3$ for all roots $\alpha,\beta$. Hence, in particular, for the $\alpha$-string through $\beta$ of length $q+r+1$ given by $\beta-r\alpha,\ldots ,\beta+q\alpha$ we find
$$
\langle \beta+q\alpha,\alpha\rangle \le 3\mbox{ and} -3\le \langle \beta-r\alpha,\alpha\rangle.
$$
But $\langle \alpha,\alpha\rangle=2$ therefore implies
$$
2q\le 3- \langle \beta ,\alpha\rangle  \mbox{ and } 2r\le 3+\langle \beta,\alpha\rangle.
$$
Thus together we find $q+r+1\le 4$.

A: By positive definiteness $0 \leq (\alpha, \beta)^2 < (\alpha, \alpha)( \beta, \beta )$ or, equivalently, $0 \leq (\alpha, \beta^\vee) (\beta, \alpha^\vee ) < 4$.  Note the strict inequality.
Edit: I replaced $\langle \, , \, \rangle$ by $(\, , \,)$ to denote the inner product because of their conflicting interpretations.

A: I had trouble with exactly the same sentence in Humphrey's book (last sentence before the exercise on page 45 --- there was no "at once" for me).  After googling, I ended up on this webpage, but I found the exchange of remarks tricky to follow.  For the record, an easy way to prove that a root string has length at most 4 is to note that the sequence
 $$ \langle \beta + i \alpha, \alpha \rangle, \enspace \hbox {where $i$ is an integer}, $$
 forms an AP with difference 2.  If $\phi$ and $\psi$ are any two linearly independent roots, then $$ \langle \psi, \phi \rangle =-3, -2, -1, 0, 1, 2 \hbox { or } 3, $$
from which it follows that the root string has length at most 4.
The formula $r - q = \langle \beta, \alpha \rangle$ becomes really useful slightly later when constructing the Hasse diagram of the positive roots from a base of simple roots using root strings:
 $$ \hbox {string length} = r + q + 1 = 2r + 1 - \langle \beta, \alpha \rangle. $$
 In particular, when $r=0$ (that is, when $\beta - \alpha$ is not a root, as happens when $\alpha$ and $\beta$ are simple roots), then the string length is $1 - \langle \beta, \alpha \rangle$.


text:
Q: Обновление несколько строк в sqlite3 Помогите пожалуйста, с обновлением сразу нескольких строк. У меня таблица с данными  ,где Id это номер квартиры,а остальные столбцы информация о собственнике, но возникла проблема с обновлением данных если собственников больше одного, id квартир одинаковы, а вот строк может быть две и более. Как правильно составить запрос?
        # Первый собственник
        nom = self.lineEdit.text()
        fam = self.lineEdit_2.text()
        imya = self.lineEdit_3.text()
        otch = self.lineEdit_4.text()
        tel = self.lineEdit_5.text()
        adres = self.textBrowser.toPlainText()
        email = self.lineEdit_8.text()
        kadastr = self.lineEdit_9.text()
        dolya = self.lineEdit_10.text()
        tarif = self.lineEdit_6.text()
        # Второй собственник
        fam2 = self.lineEdit_11.text()
        imya2 = self.lineEdit_12.text()
        otch2 = self.lineEdit_7.text()
        tel2 = self.lineEdit_13.text()
        adres2 = self.textBrowser_2.toPlainText()
        email2 = self.lineEdit_14.text()
        dolya2 = self.lineEdit_15.text()
        con = db.connect(database="Data/dom.db")
        cur = con.cursor()
        cur.executemany("""UPDATE dom SET Id = ?, Fam = ?, Imy = ?, Otch = ?, tel = ?, Adres = ?, Email = ?,
                    Kadastr = ?, Doly = ?, Tarif = ? WHERE Id=%s""" % int(nom),
                        [int(nom), (fam, fam2), (imya, imya2), (otch, otch2), (tel, tel2),
                         (adres, adres2), (email, email2), kadastr, (dolya, dolya2), tarif])
        con.commit()
        con.close()

Как правильно обновить данные?


text:
Q: Sound issues in jar file I have a very weird issue I cant fix.
I'm currently making a game and I want sound in the game. It is supposed to be run as a jar file and the game works perfectly fine when running it from eclipse.
The SoundPlayer is part of an external jar library that I use in the game. It then takes a name, a folder and plays the sound. The sound is located in a sub-folder of the folder where the FTSound object class is. I've checked the jar, and the sound files are included and they are in the same place as in eclipse. Now to the weird issue I've come across:
When I run the jar file by double-clicking it, everything works except the sound. It is completely missing. However, if I start the jar via cmd, the sound works fine. It is the exact same jar.
Any ideas? I'd much appreciate your help!
The sound is played with the following code:
public static void playSound(final FTSound sound) {
    new Thread(new Runnable() {
        @Override
        public void run() {
            try{
                Clip clip = AudioSystem.getClip();
                AudioInputStream inputStream = AudioSystem.getAudioInputStream(sound.getClass().getResource(sound.getFolderName() + "/" + sound.getSoundName()));
                clip.open(inputStream);
                clip.start();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }).start();
}

A: A few ideas come to mind. You said you're using eclipse.  When you extract your files to the .jar, be sure that your audio files are all extracted to the same place.  If you are clicking on the .jar outside of the directory which contains your sound files and it's not a shortcut, but your run inside the same directory in the cmd, this could cause the issue you have described.  Although it doesn't really fix the issue, a workaround I would suggest is writing a bat to start your game at the command prompt. this will give you a clickable file which also  plays the sound. I don't see any issues in your code, and if you have gotten the sound to play, then there probably aren't any. One other thing: the clip object can't run sound well for more than a few seconds.  If you're looking for a sound effect, it's great, but otherwise, you should try using this method:
new Thread(new Runnable()
{
    SourceDataLine soundLine;
    public void run()
    {
      soundLine = null;
          int BUFFER_SIZE = 64*1024;  // 64 KB

              // Set up an audio input stream piped from the sound file.
              try {
                 AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(this.getClass().getResource("title.wav"));
                 AudioFormat audioFormat = audioInputStream.getFormat();
                 DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat);
                 soundLine = (SourceDataLine) AudioSystem.getLine(info);
                 soundLine.open(audioFormat);
                 soundLine.start();
                 int nBytesRead = 0;
                 byte[] sampledData = new byte[BUFFER_SIZE];
                 while (nBytesRead != -1)
                 {
                    nBytesRead = audioInputStream.read(sampledData, 0, sampledData.length);
                    if (nBytesRead >= 0)
                    {
                       // Writes audio data to the mixer via this source data line.
                       soundLine.write(sampledData, 0, nBytesRead);
                    }

                 }
              } catch (Exception ex)
              {
                 ex.printStackTrace();
              }finally
              {
                 soundLine.drain();
                 soundLine.close();
              }
        }
}).start();


text:
Q: Reading in a .txt file to update an already stored 2D char array but not overwriting where the original source has blanks So I have a very perplexing issue. I got stuck for a few days so I skipped this step to continue the project. I did this by changing the supplied .txt file to the display the output I needed rather than continue to try an over ride my internally detailed 2D array.
I'm pretty sure I can't submit that amended .txt so the program won't work unless I'm able to work this out.
I need a way to copy a .txt file contents over an existing the 2D array but only update the positions that have a character. The other positions within the .txt file are blank.
.txt file Example;
 f  g  s   f
a  b    c  d
  a  b   c d
   abc   d
 f  g  s   f
a  b    c  d
  a  b   c d
   abc   d
a  b    c  d
  a  b   c d
 f  g  s   f

and I need to copy those over to a 12x12 char array already stored like the below,
    char source[12][12] = {
    " ---------- ",
    "|..........|",
    "|..........|",
    "|..........|",
    "|..........|",
    "|..........|",
    "|..........|",
    "|..........|",
    "|..........|",
    "|..........|",
    "|..........|",
    " ---------- ",
    };

I've successfully used the below code to write the .txt file contents to the screen so I'm hoping there's a way to add a method to the for loop to skip the blank spots in the .txt file and only update the 2D array when there is a character at the same corresponding position within the .txt file.
I've omitted some of the details and cose as it's an assignment but if it helps the characters in the .txt file are only 'o','b' and 'blanks'. Both source and destination are 12x12.

for (posX = 0; posX < 12; posX++) {

        for (posY = 0; posY < 12; posY++) {
            printf("%c", source[posX][posY]);
        }
        printf("\n");

Appreciate any help, it's got me stumped.
---EDIT---
A massive thanks so far.
I've managed to get the copy from the 10x10 .txt file to 12x13 array copied successfully. Progress..
The good news is think I only now need to worry about the " "(blanks) in the .txt file overwriting the ".", so this should make it much simpler?
I've not yet been able to create a if statement do do that. I've tried a few things but I'm now only guessing and need to be pointed to a source to read to understand how to tell the loop;
If you see a (blank) in .txt @ [posX][posY] - do not update the same [posX][posY] in source and continue to loop.
Any help is very much appreciated. The last and final step is a big one and will need this sorted before I can start on that.
 ----------
|f  g  s   |
|a  b    c |
|  a  b   c|
|   abc   d|
| f  g  s  |
|a  b    c |
|  a  b   c|
|   abc   d|
|a  b    c |
|  a  b    |
 ----------

fptr = fopen("XXX.txt", "r");

    for (posX = 1; posX < 11; posX++) {

        for (posY = 1; posY < 11; posY++) {

                fscanf(fptr, "%c", &source[posX][posY]);

        }
                fscanf(fptr, "%c", &newline);

        }
        fclose(fptr);
    }

A: You only need to check if the character is different from the space character ' ', and if it is different you insert it and if it does not continue the loop.
I don't know how you are accessing the file. But there should be a statement similar to this in the loop:
if(currentChar != " "){
  source[posX][posY]
}

A: Since the size of source is too small to hold its initializer, you have UB all over the place.  The string |..........| is 12 characters long, so it requires an array of size (at least) 13 to hold it.  Change your initializer to:
char source[12][13] = {
    " ---------- ",
    "|..........|",
    "|..........|",
    "|..........|",
    "|..........|",
    "|..........|",
    "|..........|",
    "|..........|",
    "|..........|",
    "|..........|",
    "|..........|",
    " ---------- "
};

If your code requires that the size of the array be exactly [12][12], then you cannot use string constants for the initializers.  You would need to do the more verbose:
char source[12][12] = {
    { ' ', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', ' ' },
    { '|', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '|' },
    { '|', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '|' },
    { '|', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '|' },
    { '|', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '|' },
    { '|', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '|' },
    { '|', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '|' },
    { '|', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '|' },
    { '|', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '|' },
    { '|', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '|' },
    { '|', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '|' },
    { ' ', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', ' ' }
};

(or use string constants to initialize the first 11 chars, and then fill in the tail at run time, but that's a bad idea.)
I'm not sure how standard this is (I believe the ... is a gnu extension), but some compilers will allow:
char source[12][12] = {
    [0]         = { [0] = ' ', [1 ... 10] = '-', [11] = ' ' },
    [1 ... 10 ] = { [0] = '|', [1 ... 10] = '.', [11] = '|' },
    [11]        = { [0] = ' ', [1 ... 10] = '-', [11] = ' ' }
};

A: I think the main issue is with your data receiving technique. What you are doing is, you are directly putting the data into your array without verifying your conditions whether it contains white space or not.
In order to correct it, do some update in your loop...
char ch;
ch = fgetc(fptr); //get a character from file pointer...

Answer to your edited part, to do the same thing you need this kind of if statement in your loop if I am getting you correctly... now check the conditions to hold the data in your array.
if(ch == " " || ch == "\n" || ch == "\r" || ch == "\t" || ch == "\0")
{
//TODO:
// handle white spaces here and correspondingly '\n','\r','\t'...
// print or do whatever you want to do...
}
else
{
//here we have only characters and update it to corresponding position in array...
source[posX][posY] = ch;
}