text:
Q: IndexOutOfBoundsException crashing android app I am clicking an item from a ViewList of the previous activity. This activity is supposed to take that object and display said object's characteristics. When I click on the viewList the app crashes. Here is the logcat:
04-16 19:37:09.183 22696-22696/cs4326.cook4me E/AndroidRuntime: FATAL EXCEPTION: main
Process: cs4326.cook4me, PID: 22696
java.lang.RuntimeException: Unable to start activity ComponentInfo{cs4326.cook4me/cs4326.cook4me.RecipeInstructActivity}: java.lang.IndexOutOfBoundsException: Index: 1, Size: 0
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
     at android.app.ActivityThread.-wrap12(ActivityThread.java)
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
     at android.os.Handler.dispatchMessage(Handler.java:102)
     at android.os.Looper.loop(Looper.java:154)
     at android.app.ActivityThread.main(ActivityThread.java:6119)
     at java.lang.reflect.Method.invoke(Native Method)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
        Caused by: java.lang.IndexOutOfBoundsException: Index: 1, Size: 0
     at java.util.ArrayList.add(ArrayList.java:457)
     at cs4326.cook4me.RecipeInstructActivity.onCreate(RecipeInstructActivity.java:45)
     at android.app.Activity.performCreate(Activity.java:6679)
     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
     at android.app.ActivityThread.-wrap12(ActivityThread.java)
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
     at android.os.Handler.dispatchMessage(Handler.java:102)
     at android.os.Looper.loop(Looper.java:154)
     at android.app.ActivityThread.main(ActivityThread.java:6119)
     at java.lang.reflect.Method.invoke(Native Method)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

Here is the corresponding activity code (error says at line 45):
package cs4326.cook4me;

import java.util.ArrayList;
import java.util.List;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;

public class RecipeInstructActivity extends FragmentActivity {

    private static final String TAG = "RecipeInstructActivity";
    /**
     * Identifier for the example fragment.
     */
    public static final int FRAGMENT_COMPLETE = 1;
    public static final int FRAGMENT_STEPPED = 2;

    /**
     * The adapter definition of the fragments.
     */
    private FragmentPagerAdapter _fragmentPagerAdapter;

    /**
     * The ViewPager that hosts the section contents.
     */
    private ViewPager _viewPager;

    /**
     * List of fragments.
     */
    private List<Fragment> _fragments = new ArrayList<>();

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        Log.d(TAG, "onCreate:");
        super.onCreate(savedInstanceState);

        this.setContentView(R.layout.activity_main);

        // Each fragment to our list.
        this._fragments.add(FRAGMENT_COMPLETE, new CompleteInstructionFragment());
        this._fragments.add(FRAGMENT_STEPPED, new SteppedInstructionFragment());

        // Setup the fragments, defining the number of fragments, the screens and titles.
        this._fragmentPagerAdapter = new FragmentPagerAdapter(this.getSupportFragmentManager()){
            @Override
            public int getCount() {
                return RecipeInstructActivity.this._fragments.size();
            }
            @Override
            public Fragment getItem(final int position) {
                return RecipeInstructActivity.this._fragments.get(position);
            }
            @Override
            public CharSequence getPageTitle(final int position) {
                // Define titles for each fragment.
                switch (position) {
                    case FRAGMENT_COMPLETE:
                        return "Complete Recipe";
                    case FRAGMENT_STEPPED:
                        return "Step-by-Step";
                    default:
                        return null;
                }
            }
        };

        this._viewPager = (ViewPager) this.findViewById(R.id.pager);
        this._viewPager.setAdapter(this._fragmentPagerAdapter);

        // Set the default fragment.
        this.openFragment(FRAGMENT_COMPLETE);
    }

    /**
     * Open the specified fragment.
     * @param fragment
     */
    public void openFragment(final int fragment) {
        this._viewPager.setCurrentItem(fragment);
    }

    /**
     * Get the fragment object for the specified fragment.
     * @param fragment
     * @return
     */
    public Fragment getFragment(final int fragment) {
        return this._fragments.get(fragment);
    }
}

Here is the code from the parent viewList activity:
package cs4326.cook4me;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;

import java.util.Comparator;
import java.util.TreeSet;

public class RecipesActivity extends AppCompatActivity implements AdapterView.OnItemClickListener{
    private static final String TAG = "RecipesActivity";
    private DatabaseReference databaseReference;
    private ListView mainListView ;
    private ArrayAdapter<String> listAdapter ;
    private TreeSet<Recipe> allRecipeData;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recipes);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        //Initialize reference to database
        databaseReference = FirebaseDatabase.getInstance().getReference();
        //Initialize recipe data set
        allRecipeData = new TreeSet<Recipe>(new Comparator<Recipe>() {
            @Override
            public int compare(Recipe o1, Recipe o2) {
                return o1.getTitle().compareToIgnoreCase(o2.getTitle());
            }
        });
        // Create ArrayAdapter
        listAdapter = new ArrayAdapter<String>(this, R.layout.row_layout);
        //Create query for recipes
        Query recipesReference = databaseReference.child("recipes").orderByChild("title");
        recipesReference.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                // Get Recipe object and use the values to update the UI
                Recipe recipe = dataSnapshot.getValue(Recipe.class);
                listAdapter.add(recipe.getTitle());
                allRecipeData.add(recipe);
                Log.d(TAG, "loadRecipe:onChildAdded");
            }

            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String previousName) {
                // Get Recipe object and use the values to update the UI
                Recipe recipe = dataSnapshot.getValue(Recipe.class);
                listAdapter.remove(previousName);
                listAdapter.add(recipe.getTitle());
                Log.d(TAG, "loadRecipe:onChildChanged");
            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {
                // Get Recipe object and use the values to update the UI
                Recipe recipe = dataSnapshot.getValue(Recipe.class);
                listAdapter.remove(recipe.getTitle());
                allRecipeData.remove(recipe);
                Log.d(TAG, "loadRecipe:onRemoved");
            }

            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String olden) {
                // Get Recipe object and use the values to update the UI
                Recipe recipe = dataSnapshot.getValue(Recipe.class);
                listAdapter.remove(olden);
                listAdapter.add(recipe.getTitle());
                Log.d(TAG, "loadRecipe:onChildMoved");
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                // Getting Recipe failed, log a message
                Log.w(TAG, "loadRecipe:onCancelled", databaseError.toException());
            }
        });

        // Find the ListView resource.
        mainListView = (ListView) findViewById( R.id.listViewRecipes );
        //Add list items!
        mainListView.setAdapter( listAdapter );

        //TODO: Make it so clicking / tapping on each item redirects to Recipe
        mainListView.setOnItemClickListener(this);

        //Floating login button
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent transfer = new Intent(RecipesActivity.this, LoginActivity.class);
                startActivity(transfer);
            }
        });

        //If you type, it will automatically start searching
        setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
        //Floating search button
        FloatingActionButton floatingSearch = (FloatingActionButton) findViewById(R.id.search_recipes);
        floatingSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onSearchRequested();
            }
        });

        //Redirects back to Main Menu if press up button
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    public void onItemClick(AdapterView<?> l, View v, int position, long id) {
        Log.d(TAG, "You clicked " + listAdapter.getItem(position));
        String nameOf = listAdapter.getItem(position);
        Recipe selectedRecipe = new Recipe();
        // Then you start a new Activity via Intent
        Intent specialTransfer = new Intent(RecipesActivity.this, RecipeInstructActivity.class);
        for (Recipe r : allRecipeData) {
            if (r.getTitle().equals(nameOf)) {
                selectedRecipe = r;
            }
        }
        //Pass selected recipe
        specialTransfer.putExtra("recipe_object", selectedRecipe);
        startActivity(specialTransfer);

    }

}

Here is the AndroidManifest.XML:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="cs4326.cook4me">

    <uses-permission android:name="android.permission.INTERNET" />

    <!-- To auto-complete the email text field in the login form with the user's emails -->
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.READ_PROFILE" />
    <uses-permission android:name="android.permission.READ_CONTACTS" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/icon"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/Theme.AppCompat.Light">
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".LoginActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="cs4326.cook4me.MainActivity" />
        </activity>

        <activity
            android:name=".RegisterActivity"
            android:label="Register User"
            android:parentActivityName=".LoginActivity" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="cs4326.cook4me.LoginActivity" />
        </activity>

        <activity
            android:name=".ProfileActivity"
            android:label="User profile"
            android:parentActivityName=".LoginActivity" />
        <activity
            android:name=".SettingsActivity"
            android:label="@string/title_activity_settings"
            android:parentActivityName=".MainActivity" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="cs4326.cook4me.MainActivity" />
        </activity>
        <!--
        <activity
            android:name=".RecipeFragment"
            android:label="@string/title_activity_recipe_fragment"
            android:theme="@style/AppTheme.NoActionBar" />
        <activity
            android:name=".ProfileFragment"
            android:label="@string/title_activity_profile_fragment"
            android:theme="@style/AppTheme.NoActionBar"></activity>
        -->
        <activity
            android:name=".RecipesActivity"
            android:label="@string/title_activity_recipes"
            android:parentActivityName=".MainActivity"
            android:theme="@style/AppTheme.NoActionBar">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="cs4326.cook4me.MainActivity" />
            <meta-data android:name="android.app.default_searchable"
                android:value=".SearchRecipeActivity" />
        </activity>
        <activity
            android:name=".CookingTerminologyActivity"
            android:label="@string/title_activity_cooking_terminology"
            android:parentActivityName=".MainActivity"
            android:theme="@style/Theme.AppCompat.Light.NoActionBar">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="cs4326.cook4me.MainActivity" />
        </activity>
        <activity
            android:name=".TermActivity"
            android:label="@string/title_activity_term"
            android:parentActivityName=".CookingTerminologyActivity"
            android:theme="@style/Theme.AppCompat.Light.NoActionBar">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="cs4326.cook4me.CookingTerminologyActivity" />
        </activity>

        <activity
            android:name=".SearchRecipeActivity"
            android:label="@string/title_activity_search_recipe"
            android:parentActivityName=".RecipesActivity"
            android:theme="@style/Theme.AppCompat.Light.NoActionBar">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="cs4326.cook4me.RecipesActivity" />
            <intent-filter>
                <action android:name="android.intent.action.SEARCH" />
            </intent-filter>
            <meta-data android:name="android.app.searchable"
                android:resource="@xml/searchable"/>
        </activity>

        <activity
            android:name=".RecipeInstructActivity"
            android:parentActivityName=".RecipesActivity">
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="cs4326.cook4me.RecipeInstructActivity" />

        </activity>
    </application>

</manifest>

A: Problem 1: Static initialisation
private List<Fragment> _fragments = new ArrayList<>(); //be careful doing this!

Field initialisation doesn't work well in Android Activities and Fragments because their lifecycles are controlled. While in this case it's not causing the problem, you can run into trouble if you use findViewById(int id) or other such methods in field initialization. Until the lifecycles of Activities and Fragments are really clear, it may be better just to avoid and to put the code inside the onCreate() or onResume() callbacks as necessary.
Problem 2: Rolling our own FragmentManager
In this code, Fragments are being cached inside a list. There is no need for this - it's the job of the FragmentManager to cache fragments.
Also, the method FragmentPagerAdapter#getItem() should be used for instantiation, not retrieving from a list. It's not really your fault - I think the method is poorly named. It really means something more like "createItem()" and it should look something more like this:
    this._fragmentPagerAdapter = new FragmentPagerAdapter(this.getSupportFragmentManager()){
        @Override
        public int getCount() {
            return RecipeInstructActivity.this._fragments.size();
        }
        @Override
        public Fragment getItem(final int position) {
            switch (position) {
                case FRAGMENT_COMPLETE:
                    return new CompleteInstructionFragment();
                case FRAGMENT_STEPPED:
                    return new StepByStepFramgment();
        }

It's best to leave everything to the ViewPager if possible. If you can't and you need to manipulate Fragments yourself, then when you are adding Fragments use the overload that lets you add a tag to the Fragment when you complete a transaction and then when you need a handle on the Fragment you can use findFragmentByTag to retrieve it.

A: Thanks to suggestions, I changed directions and went a different route with the initialization and adapter. This is the resulting code that worked for me to create an activity that encompasses a tabbed layout.
Main Activity:
package cs4326.cook4me;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.net.Uri;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentManager;

public class RecipeInstructActivity extends AppCompatActivity implements
        CompleteInstructionFragment.OnFragmentInteractionListener,
        SteppedInstructionFragment.OnFragmentInteractionListener {

    private static final String TAG = "RecipesActivity";
    private SectionsPagerAdapter mSectionsPagerAdapter;

    /**
     * The ViewPager that hosts the section contents.
     */
    private ViewPager mViewPager;

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        this.setContentView(R.layout.activity_recipe_instruct);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        //setActionBar();
        setSupportActionBar(toolbar);

        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(mViewPager);
    }

    @Override
    public void onFragmentInteraction(Uri uri) {

    }

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

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            Fragment fragment = null;
            switch (position) {
                case 0: {
                    fragment = new CompleteInstructionFragment();
                    break;
                }
                case 1: {
                    fragment = new SteppedInstructionFragment();
                    break;
                }
            }

            return fragment;
        }

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

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "Full Recipe";
                case 1:
                    return "Step-by-Step";
            }
            return null;
        }
    }
}

Fragment #1:
package cs4326.cook4me;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * Created by nathan1324 on 4/16/17.
 */

public class CompleteInstructionFragment extends Fragment {

    private OnFragmentInteractionListener mListener;

    public CompleteInstructionFragment() {
        // required empty constructor
    }

    //Recipe robj= getIntent().getParcelableExtra("recipe_object");

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {

        }
    }

    public static CompleteInstructionFragment newInstance() {
        CompleteInstructionFragment fragment = new CompleteInstructionFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

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

        // view created from XML layout
        View view = inflater.inflate(R.layout.fragment_completeinstruction, container, false);

//        Create
//                View
//                        Here

        // could add other customization here for loyout components later
        return view;
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    public interface OnFragmentInteractionListener {
        void onFragmentInteraction(Uri uri);
    }

}

Fragment #2:
package cs4326.cook4me;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * Created by nathan1324 on 4/16/17.
 */

public class SteppedInstructionFragment extends Fragment {

    private OnFragmentInteractionListener mListener;

    public SteppedInstructionFragment() {
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    public static SteppedInstructionFragment newInstance() {
        SteppedInstructionFragment fragment = new SteppedInstructionFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
        }
    }

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

        // view created from XML layout
        View view = inflater.inflate(R.layout.fragment_steppedinstruction,container, false);

        // could add other customization here for layout components later

        return view;
    }

    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    public interface OnFragmentInteractionListener {
        void onFragmentInteraction(Uri uri);
    }
}


text:
Q: Global variable in C++ I'm writing c++ project, which contains several classes. I created .h file named Position.h, with one array and one function:
class Position
{
public:
    Coord positions[25];

public:
    void setPos(int index, double x, double y)
    {
        positions[index].x = x;
        positions[index].y = y;
    }
};

I want to set values in this array from another classes, so every class in this project will see the same values.
I included "Position.h" in other classes, but i can't access the "positions" array.
Anyone can help me plz??

A: positions is a member variable associated with a class instance, and therefore not a global. You can make it similar to a global by making it static. Doing so, it will become a class-scoped variable, and not bound to an instance.
You will need to define it in a single implementation file.
An even better alternative would be having an std::vector<Coord>.

A: Just chnage the statement :
Coord positions[25];

to
static Coord positions[25];

also change void setPos
to
static void setPos

while accesing the array ,access it as:
Position::positions[any value]

But before accessing the array,make sure you call the function setPos

A: As suggested by others, you can make the members static.
You can also create an instance of the Position class as a global variable, and use that:
Position globalPosition;

void function_using_position()
{
    globalPosition.setPos(0, 1, 2);
}

int main()
{
    function_using_position();
}

Or make it a local variable, and pass it around as a reference:
void function_using_position(Position &position)
{
    position.setPos(0, 1, 2);
}

int main()
{
    Position localPosition;

    function_using_position(localPosition);
}

redpajama_set_name: RedPajamaStackExchange


text: Q: CSS not loading properly when html element appended using jquery in django template I'm working on an ecommerce app where  trying to get products using ajax and append the product list using .append method and data is being appended the problem is that css doesn't load properly also icons are loading. CSS loads sometimes when hard reloaded then again not loading once refreshed normally. Please find the below codes for your reference and help to resolve.


text:
Q: When should assert() be used? In developing a large C++ programming project with many developers, we have run into issues with inappropriate use of assert() in the code which results in poor quality where the assertion does indeed occur and the product crashes.
The question is what are good principles to apply to use assert() appropriately?  When is it proper to use an assert() and when is it not?  Is there a list of criteria that each assertion should pass in order to be legitimate?  How can we encourage proper use of assert()?
As a first crack at this, I would say that assert() should only be used to document a condition that is believed to be impossible to reach and which should be identified as an assert() failure at run time where it ever to arise because programming assumptions are being violated.
Can folks do better than this?  What is your experience with assert()?

A: Use Exceptions for error condition which come from the outside (outside the method or outside the program) like parameter checking and missing/defective external ressources like files or connections or user input.
Use Assertions to indicate an internal defects like programming errors, conditions that shouldn't occur, e.g. class/method invariants and invalid program state.

A: You should use assert to check all conditions that should never happen:

*

*Preconditions on input parameters

*Results of intermediate calculations

*Postconditions on object state

But you should include those asserts only in debug builds or when explicitly activated for release (not in builds released to the customers).

A: I use asserts to check for any unwanted program state:

*

*Function preconditions

*Sometimes I insert them in a macro after every API call: glDrawArray(); checkOpenGLError();--checkOpenGLError() will call getGLError() if turned on

*Data structure integrity: assert(something == null);

*Sometimes GDB lies to me (iOS SDK 3.2). I use asserts to prove it.

Note that "unwanted program state" excludes errors that naturally occur at runtime, such as being unable to open a user-selected file due to permissions or HD failure. In these cases it is not wise to use assertions.

A: Much code nowadays has a lot of external dependencies and connections.  I don't tend to use traditional assertions much these days, I favor exceptions.  I don't feel like I can assume "this can never happen" and the checks can safely be removed in a non-debug build.


text:
Q: How do i make 1 button play random sounds each time i press the button using android studio public class MainActivity extends AppCompatActivity {
MediaPlayer mp;
ImageButton soundbutton;

//This is sounds being added
int[] sounds ={R.raw.yeet1, R.raw.yeet2, R.raw.yeet3, R.raw.yeet4, R.raw.yeet5, R.raw.yeet6, R.raw.yeet7, R.raw.yeet8, R.raw.yeet9, R.raw.yeet10, R.raw.yeet11, R.raw.yeet12, R.raw.yeet13};
Random r = new Random();
int Low = 0;
int High= 13;
int rndm = r.nextInt(High-Low) + Low;

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

//creating the Mediaplayer
    soundbutton = (ImageButton) this.findViewById(R.id.button_view);
    mp = MediaPlayer.create(getApplicationContext(),sounds[rndm]);
    soundbutton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            try {
                if (mp.isPlaying()) {
                    mp.stop();
                    mp.release();
                    rndm = r.nextInt(High - Low) + Low;
                    mp = MediaPlayer.create(getApplicationContext(), sounds[rndm]);
                }
                mp.start();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

This code wont run and i'm not sure whats causing it thanks for helping!

A: When mp is not playing the if block is not executed.
Change to this:
@Override
public void onClick(View view) {
    try {
        if (mp.isPlaying()) {
            mp.stop();
            mp.release();
        }
        rndm = r.nextInt(High - Low) + Low;
        mp = MediaPlayer.create(getApplicationContext(), sounds[rndm]);
        mp.start();
    } catch (Exception e) {
        e.printStackTrace();
    }
}


text:
Q: Java compare object element and if "name" attribute is same print it once Is it possible to compare attributes of objects in a list & if the attribute "name" happens to be the same then print out the one that is older (with the rest that does not have same name) and if their name & age happens to be the same then print out one of them (with the rest that does not have same name)? I need to compare a list with objects. I sorted the list and started with nestled for-loops but then got stuck. Are there better ways of doing this? Maybe placing some method in the Person class or another way?
enter code here
public class Person {

private String name;
private int age;

public Person(String name, int age) {
    this.name = name;
    this.age = age;
}

public String getName() {
    return name;
}

public int getAge() {
    return age;
    }

}

public class Main {
    public static void main(String[] args){
    Person[] persons = new Student[4];
    persons[0] = new Person("Erik",20);
    persons[1] = new Person("Bob",21);
    persons[2] = new Person("Erik",25);
    persons[3] = new Person("Fredrik",20);

    Arrays.sort(persons, Comparator.comparing(Person::getName));

    for (int i = 0; i<persons.length; i++)
        for(int j = 0; j<i; j++){
            if (persons[i].getAge() == persons[j].getAge())

             }

        //output: Bob, Erik, Fredrik

    }
}

A: Since you only want each name to be once, and the oldest, you can create what's called a HashMap, ( Key-> value association with unique key) in which you store only the oldest person
Once you have this hashmap, you then can iterate through it to print exactly what you want
Example :
public static void main(String[] args){
    Person[] persons = new Student[4];
    persons[0] = new Person("Erik",20);
    persons[1] = new Person("Bob",21);
    persons[2] = new Person("Erik",25);
    persons[3] = new Person("Fredrik",20);

    HashMap<String, Integer> oldest_people = new HashMap<>();
    for (Person p: persons){
        int person_age = oldest_people.getOrDefault(p.getName(), -1);
        if (person_age != -1) {
            if (p.getAge() > person_age) {
                oldest_people.put(p.getName(), p.getAge());
            }
        }
        else {
            oldest_people.put(p.getName(), p.getAge());
        }
    }

    for (Map.Entry<String, Integer> entry : oldest_people.entrySet()) {
        System.out.println(entry.getKey() + " age : "+entry.getValue().toString());
    }
}

A: Alternate approach based on your program,
override these below methods on a Person class
@Override
public int hashCode() {
    return name.hashCode();
}

@Override
public boolean equals(Object obj) {
    if(obj == null || !(obj instanceof Person)) return false;
    Person p = (Person) obj;
    if(this.name.equals(p.getName())) return true;
    return false;
}

And you can add custom comparator to sort person on the array
Comparator<Person> comparePerson = new Comparator<Person>() {
    @Override
    public int compare(Person p1, Person p2) {
        //name in ascending order
        int nameCompare = p1.getName().compareTo(p2.getName());

        //age in descending order means from higher age
        int ageCompare = Integer.compare(p2.getAge(), p1.getAge());

        return  nameCompare == 0 ? ageCompare : nameCompare;
    }
};

Arrays.sort(persons, comparePerson);

After, you can find unique Person. Below, the Set collection will only add
a unique Person, this time oldest age person will add.
Set<Person> personSet = new HashSet<>();
for(Person p : persons) {
    if(!personSet.contains(p)) personSet.add(p);
}

Now, you can get a unique Person in collection.


text:
Q: How to use selenium to click a button with only type and class I tried to use selenium to click the button of "Submit" on Expedia. But none of the methods works.
I tired XPATHs, which doesn't work... And actually I am not sure which class I should feed into the XPATHs function.html code of "submit" button

A: If you are trying to click on button you can use below methods.
driver = webdriver.Chrome(r"your_path_to_chromedriver\chromedriver.exe") #path to connect with webdriver and chrome
driver.get("https://www.your_website.com")
driver.find_element_by_id("enter_id").click() #add the id of button to click
driver.find_element_by_class_name("enter_class").click() #add the class of button to click
driver.find_element_by_xpath("enter_expath").click() #add the xpath to click on button

You can use id, class, or Xpath any of method to get the element and click on it.

A: Either of the below code should work.
//button[@type='submit'][@class='btn-primary.btn-action.gcw-submit']
//button[type='submit'][class='btn-primary.btn-action.gcw-submit']


text:
Q: Given 1 billion numbers we need to find the largest 1 million numbers I have been stuck in one question.
Given 1 billion numbers we need to find the largest 1 million numbers. One approach is to sort the
numbers and then take the first million numbers from that is in O(n log n). Propose an algorithm that has
expected O(n) time complexity.
Is it Heap sort which can do that with having O(n) complexity?

A: The general version of the problem you're trying to solve here seems to be the following:

Given n numbers, report the largest k of them in (possibly expected) time O(n).

If you just need to find the top k elements and the ordering doesn't matter, there's a clever O(n)-time algorithm for this problem based on using fast selection algorithms. As a refresher, a selection algorithm takes as input an array A and a number m, then reorders the array A so that the m smallest elements are in the first m slots and the remaining elements occupy the larger slots. The quickselect algorithm does this in (expected) time O(m) and is fast in practice; the median-of-medians algorithm does this in worst-case O(m) time but is slower in practice. While these algorithms typically are framed in terms of finding the smallest k elements, they work just as well finding the largest k elements.
Using this algorithm as a subroutine, here's how we can find the top k elements in time and space O(m):
Initialize a buffer of 2k elements.
Copy the first k elements of the array into the buffer.

While there are elements remaining in the array:
    Copy the next k of them into the buffer.
    Use a selection algorithm to place the k largest elements
      of the buffer in the first k slots of the buffer.
    Discard the remaining elements of the buffer.

Return the contents of the buffer.

To see why this works, notice that after each iteration of the loop, we maintain the invariant that the buffer holds the k largest elements of the ones that have been seen so far (though not necessarily in sorted order). Therefore, the algorithm will identify the top k elements of the input and return them in some order.
In terms of time complexity - there's O(k) work to create the buffer, and across all iterations of the loop we do O(n) work copying elements into the buffer. Each call to the selection algorithm takes (expected) time O(k), and there are O(n / k) calls to the algorithm for a net runtime of O(n + k). Under the assumption that k < n, this gives an overall runtime of O(n), with only O(k) total space required.

A: No general sorting algorithm can do this in O(n) time. Furthermore, without additional constraints (e.g., the billion numbers are taken from the numbers 1 to 1,000,000) there is no sorting algorithm at all that is going to work for this.
However, there is a simple O(n) algorithm to do this:

*

*initialize a return buffer with 1,000,000 empty cells

*for each item in your list of 1,000,000,000, do the following:

*check each of the 1,000,000 cells in order

*if the number from the input is bigger than the number in your buffer, swap them and keep going

*if you're looking at a blank cell, put the number you're holding down

*if you get to the end of the list and are holding a number, throw it out

Here's an example with a list of 10 things and we want the biggest 5:
Input:  [6, 2, 4, 4, 8, 2, 4, 1, 9, 2]
Buffer: [-, -, -, -, -]
        [6, -, -, -, -] … see a blank, drop the 6
        [6, 2, -, -, -] … 2 < 6, skip, then see a blank, drop the 2
        [6, 4, 2, -, -] … 4 < 6 but 4 > 2, swap out 2, see blank, drop 2
        [6, 4, 4, 2, -] … 4 <= 4,6 but 4 > 2, swap out 2, see blank, drop 2
        [8, 6, 4, 4, 2] … 8 > 6, swap, then swap 6 for 4, etc.
        [8, 6, 4, 4, 2] … 2 <= everything, drop it on the floor
        [8, 6, 4, 4, 4] … 4 <= everything but 2, swap, then drop 2 on floor
        [8, 6, 4, 4, 4] … 1 <= everything, drop it on the floor
        [9, 8, 6, 4, 4] … 9 > everything, swap with 8 then drop a 4 on the floor
        [9, 8, 6, 4, 4] … 2 <= everything, drop it on the floor

You do 1,000,000 comparisons and potentially up to 1,000,000 swaps for every element in the input (consider input in sorted ascending order). That means you do work proportional to 1,000,000 * n, a linear amount of work in the size of the input n.

A: You can generally do better than sorting. Most people would solve this problem by using a heap as the structure. The time complexity to build the heap will be O(n). But you will then have to do a million "pop" operations, the time complexity for each pop being O(log n), but you are not doing the full n pops (only n/1000 pops in this case).
I say you can "generally" do better than sorting because most sorting algorithms in libraries are O(n log n). But there is the "distribution sort" that is actually O(n + k), where k is the number of possible values in the range you are sorting and depending on the value of k, you might do better sorting.
Update
To incorporate the suggestion made by @pjs, create a "minimum" heap with the first million values from the billion where a pop operation removes the minimum value from the heap. Then for the next 999,000,000 values, check to see if each one is greater than the current minimum value on the heap and if so, pop the current minimum value from the heap and push the new value. When you are done, you will be left with the 1,000,000 largest values.


text:
Q: Package erros problem with php 7.4 install on Centos 7.8 I'm having issues with Centos 7.8 and PHP7 I've gone through Stack Overlfow and found some similar posts but am not getting a answer for my issue. I have php 5.6 and when I try to install php 74 I get the errors down below. I've tried installing the Required file but it just throws another error saying that it requires that same file.
Error:
Package: php-mcrypt-7.1.33-10.el7.remi.x86_64 (remi-php71)
           Requires: php-common(x86-64) = 7.1.33-10.el7.remi
           Removing: php-common-5.6.40-23.el7.remi.x86_64 (@remi-php56)
               php-common(x86-64) = 5.6.40-23.el7.remi
           Updated By: php-common-7.4.12-1.el7.remi.x86_64 (remi-php74)
               php-common(x86-64) = 7.4.12-1.el7.remi
           Available: php-common-5.4.16-48.el7.x86_64 (base)
               php-common(x86-64) = 5.4.16-48.el7
           Available: php-common-5.4.45-18.el7.remi.x86_64 (remi)
               php-common(x86-64) = 5.4.45-18.el7.remi
           Available: php-common-5.6.40-22.el7.remi.x86_64 (remi-php56)
               php-common(x86-64) = 5.6.40-22.el7.remi
           Available: php-common-7.1.33-9.el7.remi.x86_64 (remi-php71)
               php-common(x86-64) = 7.1.33-9.el7.remi
           Available: php-common-7.1.33-10.el7.remi.x86_64 (remi-php71)
               php-common(x86-64) = 7.1.33-10.el7.remi
           Available: php-common-7.2.33-1.el7.remi.x86_64 (remi-php72)
               php-common(x86-64) = 7.2.33-1.el7.remi
           Available: php-common-7.2.34-1.el7.remi.x86_64 (remi-php72)
               php-common(x86-64) = 7.2.34-1.el7.remi
           Available: php-common-7.3.23-1.el7.remi.x86_64 (remi-php73)
               php-common(x86-64) = 7.3.23-1.el7.remi
           Available: php-common-7.3.24-1.el7.remi.x86_64 (remi-php73)
               php-common(x86-64) = 7.3.24-1.el7.remi
           Available: php-common-7.4.11-1.el7.remi.x86_64 (remi-php74)
               php-common(x86-64) = 7.4.11-1.el7.remi
Error: Package: php-recode-7.3.24-1.el7.remi.x86_64 (remi-php73)
           Requires: php-common(x86-64) = 7.3.24-1.el7.remi
           Removing: php-common-5.6.40-23.el7.remi.x86_64 (@remi-php56)
               php-common(x86-64) = 5.6.40-23.el7.remi
           Updated By: php-common-7.4.12-1.el7.remi.x86_64 (remi-php74)
               php-common(x86-64) = 7.4.12-1.el7.remi
           Available: php-common-5.4.16-48.el7.x86_64 (base)
               php-common(x86-64) = 5.4.16-48.el7
           Available: php-common-5.4.45-18.el7.remi.x86_64 (remi)
               php-common(x86-64) = 5.4.45-18.el7.remi
           Available: php-common-5.6.40-22.el7.remi.x86_64 (remi-php56)
               php-common(x86-64) = 5.6.40-22.el7.remi
           Available: php-common-7.1.33-9.el7.remi.x86_64 (remi-php71)
               php-common(x86-64) = 7.1.33-9.el7.remi
           Available: php-common-7.1.33-10.el7.remi.x86_64 (remi-php71)
               php-common(x86-64) = 7.1.33-10.el7.remi
           Available: php-common-7.2.33-1.el7.remi.x86_64 (remi-php72)
               php-common(x86-64) = 7.2.33-1.el7.remi
           Available: php-common-7.2.34-1.el7.remi.x86_64 (remi-php72)
               php-common(x86-64) = 7.2.34-1.el7.remi
           Available: php-common-7.3.23-1.el7.remi.x86_64 (remi-php73)
               php-common(x86-64) = 7.3.23-1.el7.remi
           Available: php-common-7.3.24-1.el7.remi.x86_64 (remi-php73)
               php-common(x86-64) = 7.3.24-1.el7.remi
           Available: php-common-7.4.11-1.el7.remi.x86_64 (remi-php74)
               php-common(x86-64) = 7.4.11-1.el7.remi

A: It seems you have various php repositories (remi-php71, remi-php72...) enabled, only keep the one you want
As explained by the wizard
yum-config-manager --disable 'remi-php*'
yum-config-manager --enable   remi-php74

Package: php-mcrypt-7.1.33-10.el7.remi.x86_64 (remi-php71)

The mcrypt extension is deprecated and have been removed from PHP 7.2
Also read: About libmcrypt and php-mcrypt

Error: Package: php-recode-7.3.24-1.el7.remi.x86_64 (remi-php73)

The recode extension is deprecated and have been removed from PHP 7.4
So you have to remove these extensions before upgrading, and if you "really" need them, you cannot upgrade.
yum remove php-recode php-mcrypt

Notice: php-pecl-mcrypt and php-pecl-recode are available for legacy applications, but are discouraged and won't be supported.


text:
Q: Accessing specific blocks of an array in matlab I want to access specific blocks of an array in matlab. Suppose my array A is of size 10x10.
Now I have two variables lets say
B = [ 1 2 3; 4 5 6]
C = [1;2]

Then I want to access 1,2,3 rows of 1st col of A and 4,5,6 rows of 2nd col of A so that I get this result array of size 3x2. How can I do it efficiently in matlab without using for loops.

A: Use following :
A(B(1,:),C(1,1))

A(B(1,:),C(2,1))

Finally 3x2 as
D = [A(B(1,:),C(1,1)) A(B(1,:),C(2,1))] ;

A: This can be done efficiently using a linear index built with bsxfun:
result = A(bsxfun(@plus, B.', (C.'-1)*size(A,1)));

This approach works for accessing any number of columns of A (that is, for any number of rows in B and C).
How it works: bsxfun builds a linear index from the desired row and column indices, given respectively by B and C. Note that C.'-1 is multiplied by size(A,1) because a new column in linear indexing means a step of size(A,1). Transposition of matrices B and C is needed so that the result matrix has the desired shape.


text:
Q: How to set locale for `LC_MESSAGES` through the config files? In setting up gettext for PHP, one needs to declare (among others) these two things (in my example I'm using en_US):
setlocale(LC_MESSAGES, 'en_US.utf8');
putenv('LANG=en_US.utf8');

I was trying to move these things into the PHP configuration file instead, so I've set the environment variable for LANG as such:
env[LANG] = 'en_US.utf8'

Which seems to be okay, and the second command is no longer necessary for it to work.
But there doesn't seem to be any such alternative for the LC_MESSAGES. Setting it up as an environment variable in my case didn't work, despite the fact that the documentation for setlocale() says:

If locale is NULL or the empty string "", the locale names will be set
  from the values of environment variables with the same names as the
  above categories, or from "LANG".

Because in my case the LC_MESSAGES isn't empty, but instead it returns C, which i have no idea what it means and where that value comes from.
The closest thing i have found in the php.ini file was one called intl.default_locale, which I've set to intl.default_locale=en_US.utf8, but with no change.
So I'm just wondering if it can be done via config files?


text:
Q: Why is my COUNTA formula counting too high? I know a similar but different question has been asked, but I don't know how to use query or where to learn, so I figured I'd ask…
I'd like to use this formula:
=COUNTA(FILTER($L:$L,OFFSET($L:$L,0,1)="Draw",$L:$L=$E2))
L:L is a range of names, which it should test against E2:E, a range of unique names. I also need to ensure that the cell in the column to the right of each instance of the name in E2:E has a specific word in it ("Draw"). I tried using AND, but this just sets everything to 1, even when one of them has 3 draws. There are no losses, so the loss column should show up as all 0s, but it is instead 1s. The infuriating thing about this is that the draw column is all right for some reason. Picture below. For reference, Losses(as well as draws and wins)are the end goal.
image

A: COUNT is meant for counting numeric values, COUNTA for non empty cells. COUNTIF or COUNTIFS would probably be your best choice. Try with:
=COUNTIFS($L:$L,E2,OFFSET($L:$L,0,1),"Draw")


text:
Q: How to find the values and the corresponding column of those values in a matrix in R So on a small scale, let's say I have 5 patients which are the rows of a matrix. In the columns, I have some information like age, sex etc. But the question is on some medications. so let's say I have 4 categorical medications. 1 means the patients received them and 0 otherwise. now for some patients I have this vector (1,1,?,?) meaning that the first two values SHOULD be 1 and I know them, but I don't know what are the "?" for each patient.
I assume it should be a matrix of 5 rows and at least 4 columns. now, how can I find the values of "?" for each row? Also, it is SO important to know that this value belongs to which treatment. (I'm not sure if this part of the question makes sense but I also want to know whether for example (1,1,0,1) was the most repeated combination or (1,1,0,0) was or ( 1,1,1,0) or...
I have almost zero knowledge on stat or math but here is the situation and I would appreciate if someone can explain how I can do it in R.

A: How about something like this, where n is the number of observations that have each pattern:
library(dplyr)
dat <- data.frame(patient = LETTERS[1:20],
                d1 = 1,
                d2 = 1,
                d3 = sample(c(0,1), 20, replace=TRUE),
                d4 = sample(c(0,1), 20, replace=TRUE))

dat %>%
  group_by(d1, d2, d3, d4) %>%
  tally()
#> # A tibble: 4 × 5
#> # Groups:   d1, d2, d3 [2]
#>      d1    d2    d3    d4     n
#>   <dbl> <dbl> <dbl> <dbl> <int>
#> 1     1     1     0     0     1
#> 2     1     1     0     1     6
#> 3     1     1     1     0     9
#> 4     1     1     1     1     4

Created on 2022-02-15 by the reprex package (v2.0.1)


text:
Q: Math function incudes 3 variable but one of them seems not counted l m trying to do a math game includes many levels. so far, l completed 3-level but on level-2, math function did not work. there are 3 variable and last variable seems not counted while doing math functions.
for example: 5 (Q1) + 7 (Q2)- 2 ( Q3) here result is 10 but on my code, it gives 12, Q3 variable not counted.
on level 3, also l use three variable and l checked level 3 works well. so got code of it and pasted in level 2 and l made some arrangements but still same problem.
here is the code of level-2 and level-3
     private void level2()
      {
        int Q21, Q22, Q23,top = 0;
        List<string> opersembols = new List<string> { "/", "+", "-", "*"};
        Random rnd = new Random();
        Random rndOP = new Random();
        int OPIndex = rndOP.Next(1, 3);
        int OPIndex2 = rndOP.Next(1, 3);
        pn1.Hide();
        pn2.Show();

        Q21 = rnd.Next(0, 20);
        Q22 = rnd.Next(0, 20);
        Q23 = rnd.Next(0, 20);

        Q21BTN.Text = Convert.ToString(Q21);
        Q22BTN.Text = Convert.ToString(Q22);
        Q23BTN.Text = Convert.ToString(Q23);

        OPBTN1.Text = opersembols[OPIndex];
        OPBTN2.Text = opersembols[OPIndex2];
        switch (OPBTN1.Text)
        {
            case "+":
                switch (OPBTN2.Text)
                {
                    case "+":
                        top = (Q21 + Q22) + Q23;
                        BTNREST2.Text = Convert.ToString(top);
                        break;
                    case "-":
                        top = (Q21 + Q22)-Q23;
                        BTNREST2.Text = Convert.ToString(top);
                        break;

                }

                break;

            case "-":
                switch (OPBTN2.Text)
                {
                    case "+":
                        top = (Q21 - Q22) + Q23;
                        BTNREST2.Text = Convert.ToString(top);
                        break;

                    case "-":
                        top = (Q21 - Q22) - Q23;
                        BTNREST2.Text = Convert.ToString(top);
                        break;

                }

                break;

        }

    }
    private void level3()
    {
        int Q21, Q22, Q23 = 0;
        List<string> opersembols = new List<string> { "/", "+", "-","*" };
        Random rnd = new Random();
        Random rndOP = new Random();
        int OPIndex = rndOP.Next(1, 4);
        int OPIndex2 = rndOP.Next(1, 4);
        pn1.Hide();
        pn2.Show();
        TimeBTN.Text = "0";
        timer1.Start();

        Q21 = rnd.Next(0, 10);
        Q22 = rnd.Next(0, 10);
        Q23 = rnd.Next(0, 10);

        Q21BTN.Text = Convert.ToString(Q21);
        Q22BTN.Text = Convert.ToString(Q22);
        Q23BTN.Text = Convert.ToString(Q23);
        timer1.Start();

        OPBTN1.Text = opersembols[OPIndex];
        OPBTN2.Text = opersembols[OPIndex2];
        switch (OPBTN1.Text)
        {
            case "+":
                switch (OPBTN2.Text)
                {
                    case "+":
                        BTNREST2.Text = Convert.ToString(Q21 + Q22 + Q23);
                        break;
                    case "-":
                        BTNREST2.Text = Convert.ToString(Q21 + Q22 - Q23);
                        break;
                    case "*":
                        BTNREST2.Text = Convert.ToString(Q21 + Q22 * Q23);
                        break;

                }

                break;

            case "-":
                switch (OPBTN2.Text)
                {
                    case "+":
                        BTNREST2.Text = Convert.ToString(Q21 - Q22 + Q23);
                        break;
                    case "-":
                        BTNREST2.Text = Convert.ToString(Q21 - Q22 - Q23);
                        break;
                    case "*":
                        BTNREST2.Text = Convert.ToString(Q21 - Q22 * Q23);
                        break;

                }

                break;

            case "*":
                switch (OPBTN2.Text)
                {
                    case "+":
                        BTNREST2.Text = Convert.ToString(Q21 * Q22 + Q23);
                        break;
                    case "-":
                        BTNREST2.Text = Convert.ToString(Q21 * Q22 - Q23);
                        break;
                    case "*":
                        BTNREST2.Text = Convert.ToString(Q21 * Q22 * Q23);
                        break;

                }

                break;

        }


text:
Q: Android crash at app launch - Illegal meta data value: the child service doesn't exist I am getting this below crash on fresh app install. This happens only once. If I restart the app the crash won't happen. Event after clear app data the crash doesn't happen. Any solution for this?
Fatal Exception: java.lang.RuntimeException: Illegal meta data value: the child service doesn't exist
       at Fj.a(Fj.java:95)
       at org.chromium.content.browser.ChildProcessLauncherHelperImpl.a(ChildProcessLauncherHelperImpl.java:134)
       at tk.run(tk.java:434)
       at android.os.Handler.handleCallback(Handler.java:938)
       at android.os.Handler.dispatchMessage(Handler.java:99)
       at android.os.Looper.loopOnce(Looper.java:233)
       at android.os.Looper.loop(Looper.java:344)
       at android.os.HandlerThread.run(HandlerThread.java:67)


text:
Q: Git How to make a master repo that tracks two other repos We are working on an app and use Github to hold and version our code.
Currently, we are 2 people each working on a seprate repo (RepoA and RepoB).
We decided that it would be best if we had 1 master repo to hold the complete app, but we also want to continue working on our separate repos on our own.
I followed this tutorial to merge both our repos into a new master repo (RepoC).
Everything worked perfectly but now we have the issue where changes to RepoA or RepoB don't reflect in RepoC and vice-versa.
So I was wondering... Is there any way, that we can tell RepoC to "track" RepoA and RepoB for changes, and sync with them when needed.
If the above is not possible, is there atleast a way where we can contribute to our own repos and then do something like "git fetch RepoA, git fetch RepoB" on our master RepoC so that it can reflect the changes we've made.

A: In theory, one repo can track infinitive number of repos by different remotes and branches.
Suppose RepoA's url is git://host/repoa.git and RepoB's is git://host/repob.git. Each has three branches, master, feature, and release, for example.
In RepoC, we can create two remotes.
git add remote origina git://host/repoa.git
git add remote originb git://host/repob.git

And then
git fetch --all

All branches in both repos can be tracked.
However, this approach has some problems.

*

*You can checkout only one of these branches which means you cannot have 2 repos' codes in the same working tree.

*When you checkout/create local branches from the remote tracking
branches, you need to name them carefully not to confuse yourself.

*When RepoA and RepoB have tags with the same name, only one of them
can be fetched into RepoC.

Since you have merged them into RepoC, you could create two remotes and track both in addition. But why not use two repos to track them?

A: Take a look at the git submodules feature: https://git-scm.com/book/en/v2/Git-Tools-Submodules
Regards
Andoni


text:
Q: Finding the tangent to a parametric curve $(t^3, t^5)$ at $(0,0)$ The curve $(t^3, t^5)$ at that point $(0,0)$ does not have a tangent vector as when you work it out, you will arrive at $(0,0)$.
Question: How can you find a new parametrisation for the curve such that you get a tangent vector at $(0,0)$. Is this even possible.
My attempts:

Changing the curve's position by taking $t \to t+1$ won't work because it just changes the position of the point we're trying to find the tangent on
A trig sub may be possible, however I have had no luck

Any help or guidance would be greatly appreciated!

A: $\frac {dy}{dx} = \frac {\frac {dy}{dt}}{\frac {dx}{dt}}$
$\frac {5t^4}{3t^2} = \frac 53 t^2$
As noted the derivative appears to not exist when $t=0$  But, the limit exists.
$\lim_\limits{t\to 0} \frac 53 t^2 = 0$
$y = 0$
An alternative would be to say
$y^3 = x^5 \\
y = x^\frac 53\\
y' = \frac 53 x^\frac 23$

A: $(0,0) $ is a singular point.
but
$$t^3=0+0t+0t^2+t^3+0t^4+0t^5+t^5\epsilon(t)$$
and
$$t^5=0+0t+0t^2+0t^3+0t^4+t^5+t^5\epsilon(t)$$
so
$(0,0)$ is an inflexion point with $\vec{i}=(1, 0) $ as the tangent vector.


text:
Q: Reformatting JSON Files in R I have a JSON file formatted as follows:
[
  {
    "StreetAddress": "",
    "City": "",
    "State": "",
    "Zip": "V6A 2P3",
    "County": "",
    "Country": "",
    "SPLC": "",
    "CountryPostalFilter": "",
    "AbbreviationFormat": "",
    "CountryAbbreviation": ""
  },
  {
    "StreetAddress": "",
    "City": "",
    "State": "",
    "Zip": "V6A 2P3",
    "County": "",
    "Country": "",
    "SPLC": "",
    "CountryPostalFilter": "",
    "AbbreviationFormat": "",
    "CountryAbbreviation": ""
  }
]

Is there R script I can use to reformat the file as follows:
{
  "Locations": [
    {
      "Address": {
        "StreetAddress": "1000 Herrontown Rd",
        "City": "Princeton",
        "State": "NJ",
        "Zip": "",
        "County": "",
        "Country": null,
        "SPLC": "",
        "CountryPostalFilter": 0,
        "AbbreviationFormat": 0,
        "CountryAbbreviation": "US"
      }
    },
    {
      "Address": {
        "StreetAddress": "457 N Harrison St",
        "City": "",
        "State": "",
        "Zip": "08540",
        "County": "",
        "Country": null,
        "SPLC": "",
        "CountryPostalFilter": 0,
        "AbbreviationFormat": 0
      }
     }
  ]
}

A: df <- jsonlite::fromJSON('[
  {
    "StreetAddress": "",
    "City": "",
    "State": "",
    "Zip": "V6A 2P3",
    "County": "",
    "Country": "",
    "SPLC": "",
    "CountryPostalFilter": "",
    "AbbreviationFormat": "",
    "CountryAbbreviation": ""
  },
  {
    "StreetAddress": "",
    "City": "",
    "State": "",
    "Zip": "V6A 2P3",
    "County": "",
    "Country": "",
    "SPLC": "",
    "CountryPostalFilter": "",
    "AbbreviationFormat": "",
    "CountryAbbreviation": ""
  }
]')

In comparison with @Brian's answer, I don't set simplifyDataFrame = F so the JSON form will be converted to a data.frame object in R. Then use tibble() to put this data frame into a 2x1 data frame with column name Address(This is a little tricky because base data.frame() cannot do that).
res <- list(Locations = tibble::tibble(Address = df))
jsonlite::toJSON(res, pretty = T)

Edit: This method works even when I set simplifyDataFrame = F, because tibble() also allow named lists as columns.

Output
{
  "Locations": [
    {
      "Address": {
        "StreetAddress": "",
        "City": "",
        "State": "",
        "Zip": "V6A 2P3",
        "County": "",
        "Country": "",
        "SPLC": "",
        "CountryPostalFilter": "",
        "AbbreviationFormat": "",
        "CountryAbbreviation": ""
      }
    },
    {
      "Address": {
        "StreetAddress": "",
        "City": "",
        "State": "",
        "Zip": "V6A 2P3",
        "County": "",
        "Country": "",
        "SPLC": "",
        "CountryPostalFilter": "",
        "AbbreviationFormat": "",
        "CountryAbbreviation": ""
      }
    }
  ]
}

A: df<-jsonlite::fromJSON('[
  {
    "StreetAddress": "",
    "City": "",
    "State": "",
    "Zip": "V6A 2P3",
    "County": "",
    "Country": "",
    "SPLC": "",
    "CountryPostalFilter": "",
    "AbbreviationFormat": "",
    "CountryAbbreviation": ""
  },
  {
    "StreetAddress": "",
    "City": "",
    "State": "",
    "Zip": "V6A 2P3",
    "County": "",
    "Country": "",
    "SPLC": "",
    "CountryPostalFilter": "",
    "AbbreviationFormat": "",
    "CountryAbbreviation": ""
  }
]', simplifyDataFrame = F)

purrr::map(df, ~list(Address = .x)) %>%
  list(Locations = .) %>%
  jsonlite::toJSON(pretty = T, auto_unbox = T)

I think this reproduces your desired output exactly.


text:
Q: Using gradient on div border with rounded corners I have some divs that have rounded corners and colored borders. I want the borders of the div to have the gradient so that it will change when the user hovers overs the div.
I have found all of the sites on how to use the gradient (http://css-tricks.com/css3-gradients/, http://gradients.glrzad.com/, etc.) but I still can't figure out how to get this to work for rounded edge borders.
Will someone please guide me to a site that describes how to do this or even help me with the code?

A: Here is the SIMPLE solution for that :

Outcome :  CSS rounded corners with gradient border

.yourClass {
  display: inline-flex;
  border: double 6px transparent;
  border-radius: 80px;
  background-image: linear-gradient(white, white), radial-gradient(circle at top left, #f00, #3020ff);
  background-origin: border-box;
  background-clip: content-box, border-box;
}

A: You can nest two elements and let the outer div act as the gradient border then you can work around this problem, example:

    ...

And then in your CSS:
/*
   unprefixed for conciseness, use a gradient generator por production code
*/

.container {
   background: linear-gradient(red, black);
 }

.content   {
   background: white;
   padding: 10px;
 }

For a working example take a look at https://stackoverflow.com/a/7066176/524555

A: Using a :before element is the most ideal solution in my opinion, as you then have full control via CSS and the HTML markup stays clean.
.circle {
  width: 300px;
  height: 200px;
  background: white;
  border-radius: 100%;
  position: relative;
  text-align: center;
  padding: 20px;
  box-sizing: border-box;
}
.circle::before {
  border-radius: 100%;
  width: 100%;
  height:100%;
  content: '';
  background-image: linear-gradient(to bottom, #3acfd5 0%, #3a4ed5 100%);
  padding: 10px;
  top: -10px;
  left: -10px;
  position:absolute;
  z-index:-1;
}

You can tweak the padding and the top and left values to adjust the border thickness.
Here is a JSFiddle that shows a practival example: http://jsfiddle.net/wschwarz/e2ckdp2v/

A: I know this answer was already answered and accepted, but I wanted to post a different approach I used, because this accepted answer wouldn't work if the button was over a background with another gradient, or an image, for example.
My solution works only for horizontal gradients and rounded-cornered (but not circle) buttons. I used both the "border-image" property and pseudo-elements to achieve this effect:
The button would have only the top and bottom "border-image" borders. The left and right borders would be completed with pseudo-elements.
Here's a working example:
HTML:

  <button class="button">
    My button!
  </button>

CSS:
*, *:before, *:after {
    box-sizing: border-box;
}

.background {
  background: linear-gradient(to bottom, #002e4b 0%,#1c4722 100%);
  width:500px;
  height:500px;
  display:flex;
  align-items:center;
  justify-content:center;
}

.button {
    box-sizing:border-box;
    display: inline-block;
    padding:0.5em 0;
    background:none;
    border:none;
    border-top:2px solid #0498f8;
    border-bottom:2px solid #0498f8;
    border-image: linear-gradient(to right, #0498f8 0%, #4db848 100%);
    border-image-slice: 1;
    position: relative;
    text-transform: lowercase;
    transition:background 0.3s;
    color: #fff;
    cursor: pointer;
    font-size:1em;
    &:before,
    &:after {
        content: '';
        display: block;
        width: 2em;
        height: calc(100% + 4px);
        border-radius: 3em 0 0 3em;
        border: 2px solid #0498f8;
        position: absolute;
        border-right: none;
        transition:background 0.3s;
        left: -2em;
        top: -2px;
    }
    &:after {
        border-radius: 0 3em 3em 0;
        border: 2px solid #4db848;
        position: absolute;
        border-left: none;
        left:auto;
        right: -2em;
        top: -2px;
    }
    &:hover {
        background:rgba(0,0,0,0.3);
        &:after,
        &:before {
            background:rgba(0,0,0,0.3);
        }
    }
}

https://jsfiddle.net/fnbq92sc/2/

A: border="solid 1px transparent"
background="linear-gradient(Canvas, Canvas) padding-box, linear-gradient(red, blue) border-box"
borderRadius="1rem"

second part for background is the gradient you desire ^


text:
Q: Problem trying to deserialize a json with a model I am trying to deserialize a json (using Newtonsoft.Json), i created the classes, but in json code there is a variable that i don't know if it is corrected or i don't know how to deserialize.
I am getting a null exception on line : MessageBox.Show(root.matriculations._14000.name)
    private void btnImportaDados_Click(object sender, EventArgs e)
    {

        string getDataUrl = "https://xxx.xxx.com/api/matriculations/get.json?entity_code=14000";

        try
        {
            using (var webClient = new System.Net.WebClient())
            {
                var json = webClient.DownloadString(getDataUrl);

                var root = JsonConvert.DeserializeObject<Rootobject>(json);

                MessageBox.Show(root.matriculations._14000.name);
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }

    }

    public class Rootobject
    {
        public Matriculations matriculations { get; set; }
    }

    public class Matriculations
    {
        public _14000 _14000 { get; set; }
    }

    public class _14000
    {
        public string entity_code { get; set; }
        public string name { get; set; }
        public string street { get; set; }
        public string local { get; set; }
        public string postal_code { get; set; }
        public string sub_postal_code { get; set; }
        public string phone1 { get; set; }
        public object phone2 { get; set; }
        public string email1 { get; set; }
        public object email2 { get; set; }
        public string entity_code_2 { get; set; }
        public string courseaction_ref { get; set; }
        public string courseaction_id { get; set; }
        public string course_code { get; set; }
        public string course { get; set; }
        public Billingorderplan[] billingorderplans { get; set; }
    }

    public class Billingorderplan
    {
        public string id { get; set; }
        public string paid { get; set; }
        public string date { get; set; }
        public object obs { get; set; }
        public object payment_doc_num { get; set; }
        public string value { get; set; }
        public string description { get; set; }
        public string entity_code { get; set; }
        public object paid_date { get; set; }
    }

The result(json data) from the url is:
{"matriculations":{"14000":{"entity_code":"14000","name":"Fabio Danilson Sivone Antonio","street":"Rua Dr. Pereira Jardim, Bl. 3 - 25 - 4 B","local":"Luanda","postal_code":"2685","sub_postal_code":"093","phone1":"923810539","phone2":null,"email1":"fabiodanilson1@hotmail.com","email2":null,"entity_code_2":"9957","courseaction_ref":"EPCE_01","courseaction_id":"1828","course_code":"EPCE","course":"Especializa\u00e7\u00e3o Avan\u00e7ada em Investiga\u00e7\u00e3o de Crime Econ\u00f3mico [E-learning]","billingorderplans":[{"id":"298","paid":"0","date":"2020-05-06","obs":null,"payment_doc_num":null,"value":"0.00","description":"Inscri\u00e7\u00e3o","entity_code":"14000","paid_date":null},{"id":"299","paid":"0","date":"2019-11-21","obs":null,"payment_doc_num":null,"value":"0.00","description":"1\u00aa presta\u00e7\u00e3o","entity_code":"14000","paid_date":null},{"id":"300","paid":"0","date":"2019-12-08","obs":null,"payment_doc_num":null,"value":"0.00","description":"2\u00aa presta\u00e7\u00e3o","entity_code":"14000","paid_date":null},{"id":"301","paid":"0","date":"2020-01-08","obs":null,"payment_doc_num":null,"value":"0.00","description":"3\u00aa presta\u00e7\u00e3o","entity_code":"14000","paid_date":null},{"id":"302","paid":"0","date":"2020-02-08","obs":null,"payment_doc_num":null,"value":"0.00","description":"4\u00aa presta\u00e7\u00e3o","entity_code":"14000","paid_date":null},{"id":"303","paid":"0","date":"2020-03-08","obs":null,"payment_doc_num":null,"value":"0.00","description":"5\u00aa presta\u00e7\u00e3o","entity_code":"14000","paid_date":null},{"id":"304","paid":"0","date":"2020-04-08","obs":null,"payment_doc_num":null,"value":"0.00","description":"6\u00aa presta\u00e7\u00e3o","entity_code":"14000","paid_date":null},{"id":"305","paid":"0","date":"2020-05-08","obs":null,"payment_doc_num":null,"value":"0.00","description":"7\u00aa presta\u00e7\u00e3o","entity_code":"14000","paid_date":null},{"id":"306","paid":"0","date":"2020-06-08","obs":null,"payment_doc_num":null,"value":"0.00","description":"8\u00aa presta\u00e7\u00e3o","entity_code":"14000","paid_date":null},{"id":"16595","paid":"0","date":"2020-08-27","obs":null,"payment_doc_num":null,"value":"20.00","description":"EExt - Atividade","entity_code":"14000","paid_date":null},{"id":"16596","paid":"0","date":"2020-08-27","obs":null,"payment_doc_num":null,"value":"45.00","description":"EExt - Teste","entity_code":"14000","paid_date":null},{"id":"16597","paid":"0","date":"2020-08-27","obs":null,"payment_doc_num":null,"value":"20.00","description":"EExt - Atividade","entity_code":"14000","paid_date":null},{"id":"16598","paid":"0","date":"2020-08-27","obs":null,"payment_doc_num":null,"value":"45.00","description":"EExt - Teste","entity_code":"14000","paid_date":null},{"id":"16599","paid":"0","date":"2020-08-27","obs":null,"payment_doc_num":null,"value":"20.00","description":"EExt - Atividade","entity_code":"14000","paid_date":null},{"id":"16601","paid":"0","date":"2020-08-27","obs":null,"payment_doc_num":null,"value":"45.00","description":"EExt - Teste","entity_code":"14000","paid_date":null},{"id":"16600","paid":"0","date":"2020-08-27","obs":null,"payment_doc_num":null,"value":"20.00","description":"EExt - Atividade","entity_code":"14000","paid_date":null}]}}}

But that "14000" is a varible value depending from the parameter passed.
How can i do it?
Thank You.

A: You do not have _14000 in returned JSON but 14000 under matriculations.

A: Since 14000 cannot be a variable name you will have to resort to some manual intervention to capture that dynamic value. The cleanest way is to remove the Matriculations class and replace it with Dictionary<int, _14000> (or Dictionary<string, _14000>).
public class Rootobject
{
    public Dictionary<int, _14000> matriculations { get; set; }
}

This will ensure that the key is captured correctly even if it is a number. You can read the object from the dictionary's values as such: root.matriculations.Values.First().name. (Remember to import System.Linq for using .First().)
For clarity you can rename _14000 to something more descriptive.


text:
Q: Initializing unknown type in Actionscript 3.0 To keep my program running smoothly, I have to create objects only when I need them. In my case, I want to see if an object of an unspecified class is null, and if not, then call tell it to initialize. (I think "initialize" is the correct term, correct me if I am wrong)
if (someObject == null) {
    someObject = new someObject.class()
}

Obviously, this code does not work. The idea seems right, but Actionscript does not agree with me. How can this be achieved?
Edit - Perhaps this will help to simplify (or complicate) the answer. I know that someObject extends my class SuperClass. Can I use a property from SuperClass to instantiate someObject?

A: If you know what type someObject is supposed to be, it's easy:
var someObject:SomeClass;

if(someObject==null)
{
     someObject = new SomeClass(); // creates an instance of the class
}

If you don't, you're making it hard for yourself. You'll have to rethink your design I guess.

A: I'm going to make an attempt at getting on the right track toward a useful answer.
Firstly, looking at your example:
if (someObject == null) {
    someObject = new someObject.class()
}

I'm not sure what you're trying to convey here. If someObject is null, you cannot extract any information about anything from it. Even if you type someObject e.g:
var someObject:Sprite;

You cannot access information about the fact that the property someObject is expecting a Sprite*
*You can use describeType() to access the type if someObject is a member of a class, but lets not go there.
If you want to be able to:

*

*Check if an instance of a specific class exists, and if not;

*Create an instance of the specified class.

You can write something like:
var existing:Object = { };

function findOrMake(type:Class):*
{
    var key:String = type.toString();

    if(!existing.hasOwnProperty(key))
    {
        // We need to make a new instance of this class.
        existing[key] = new type();
    }

    return existing[key];
}

Which can be used like:
var someObject:Sprite = findOrMake(Sprite); // Makes a new Sprite.
someObject = findOrMake(Sprite);            // References the above Sprite.

A: Don't name the instance with the exact name of the class you're instantiating.
If you do this:
var someobject;

if (someobject == null)
{
    someobject = new someObject()
}

it works.


text:
Q: Serving Intranet Website to specific clients using internet & VPN I own a company with three branches in different locations. I developed a portal application using php and mysql which run on Xampp latest version. I have a server computer in my main office where I installed my portal application. Now I want to serve this application to only my three branches. These three branches get access to internet. So using internet, how can my three branches access the portal site which I am serving from my main office using internet and IP address? Is this possible to setup in Windows OS? SO without spending much money for hosting and domain, I thought this suffice my needs. Please advise and share. Thanks.

A: I have two ways I can think of that will work
In either case, you should secure the web application with SSL and passwords or client certificates or a combination of both or some other combination. You don't necessarily need to buy a domain name or purchase SSL certificates. If your three offices have static IP addresses, you can further restrict access based on that (for either way).
Port forwarding

*

*Forward a port to your web application from your firewall

*Connect to the application directly from within the source network or use NAT reflection

*Connect via port forwarding to the application from the other sites (e.g. https://example.com/app or https://example.com:8088/app).

VPN

*

*Connect all three sites via a VPN solution (such as OpenVPN), making the main office subnet available to the other offices

*Connect to the web application as if it were a local server from any of the three sites via the regular internal IP/hostname

The VPN solution is nice because it will probably have more uses in the future.


text:
Q: sql query to find the value exist in source I have the following query,
select Vendor_ID, Descr, source, Name, Parent_Vendor_ID from VENDOR;

Data:
VendorID       Descr    Source  name     Parent Vendor ID
1234          ONLINE    ABC     JACK     6666
5689          OFFSHORE  XYZ      SAM     5555
9999          SHOP      TTT     EBAY     1234
6666         ECOMMERCE  FRE    AMERICAS

From the above table data 5555 doesn't exist in Vendor ID field. so I need the output as below
VendorID    Descr      Source   name    Parent Vendor ID    EXIST
1234        ONLINE      ABC     JACK    6666                Yes
5689        OFFSHORE    XYZ     SAM    **5555               No**
9999        SHOP        TTT     EBAY    1234                Yes
6666        ECOMMERCE   FRE    AMERICAS

I need to find if the Parent_Vendor_ID exist in Field 1 Vendor_ID. if exist simply need a column with Yes/No. If yes YES else NO
Output should be all fields + Parent_Vendor_ID_Exist
select Vendor_ID, Descr, source, Name, Parent_Vendor_ID,Parent_Vendor_ID Exist

I tried to if else but its not returning all values. Can someone please suggest?

A: select v1.Vendor_ID, v1.Descr, v1.source, v1.Name, v1.Parent_Vendor_ID,
       case when v2.Vendor_ID is null
            then 'NO'
            else 'YES'
       end as Parent_Vendor_ID_Exist
from vendor v1
left join vendor v2 on v1.Parent_Vendor_ID = v2.Vendor_ID

A: SELECT v1.Vendor_ID
     , v1.Descr
     , v1.source
     , v1.Name
     , v1.Parent_Vendor_ID
     , nvl2(v2.vendor_id,'Yes','No') as parent_exist
  FROM VENDOR v1
  LEFT OUTER JOIN vendor v2
      ON (v1.parent_vandor_id = v2.vendor_id);

A: Try this..
SELECT Vendor_ID, Descr, source, Name, Parent_Vendor_ID,
CASE
     WHEN
         EXISTS( SELECT Vendor_ID FROM VENDOR v2 WHERE v1.Parent_Vendor_ID = v2.Vendor_ID)
    THEN
        'Yes'
    ELSE
        'No'
    END as "Parent_Vendor_ID Exist"
 FROM VENDOR v1;

let me know if this works.


text:
Q: Issue with AndroidClientHandler: is it possible to edit src/Mono.Android/Xamarin.Android.Net/AndroidClientHandler.cs? I'm experiencing issues with AndroidClientHandler. Have added try/catch on each WebClient task but sometimes it makes app crash with exception:
JniEnvironment+InstanceMethods.CallIntMethod (Java.Interop.JniObjectReference instance, Java.Interop.JniMethodInfo method, Java.Interop.JniArgumentValue* args)
Java.IO.IOException: Read error: ssl=0x79aa9b2e08: I/O error during system call, Connection reset by peer

After some research, I found this thread [AndroidClientHandler] Observe cancellation requests more #4589, and what I understand reading this is that I need to edit src/Mono.Android/Xamarin.Android.Net/AndroidClientHandler.cs changing the highlighted lines as HERE . I'm able to find AndroidClientHandler.cs but it seems to be readonly and it's really different from the file on that github url. Do I really need to edit that file? Is there a higher level workaround for this issue?


text:
Q: HTTPS form url in Smarty template I need to change form action urls from http to https, I've added the following code to .htaccess but that doesn't change form urls:
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

The ecommerce system uses the Smarty function _createUrl for the form action url, and I see in that function in Abstract.php there is the following code:
$isSecure = preg_match('/on/i', $_SERVER['HTTPS']) ? 1 : 0;

So I guess either that is not working or it's being overridden.
If I add the following line below the above check, it makes no difference.
$isSecure = 1;

However if I add the following then the form action url becomes a relative path and therefore uses https.
$aParamList['secure'] = 1;

Any ideas please?


text:
Q: State changes but component doesn't update - ANGULAR I'm using ionic with angular, when i'm creating alert in ok button's callback function i'm changing my state. State changes, but this change doesn't effects in iu, i think component is not updating. How can I fix this?
async presentAlert() {
    const alert = await this.alertController.create({
      header: '',
      message: '',
      buttons: [
        'cancel',
        {
          text: 'ok',
          handler: () => {
            this.currentScreen = "";
            this.dates[this.currentDateIndex].isOrdered = false;//disable order
          }
        }
      ]
    });
    await alert.present();
  }

A: You can try to use ChangeDetectorRef to explicitly state that change has been made and view needs to be updated.
Reference: https://angular.io/api/core/ChangeDetectorRef
Example:
Declare ChangeDetectorRef in constructor
constructor(public cd: ChangeDetectorRef) {}

Then use it in your callback:
buttons: [
    'cancel',
    {
      text: 'ok',
      handler: () => {
        this.currentScreen = "";
        this.dates[this.currentDateIndex].isOrdered = false;//disable order
        this.cd.detectChanges();
      }
    }
  ]


text:
Q: Making the horizontal scroll wheel work in a VCL application, even with a Logitech MX Master mouse I am attempting to implement support for the horizontal scroll wheel in various of my own custom VCL controls, but it seems to be tricky, at least if you are using the Logitech MX Master mouse.
To be concrete, let's drop an ordinary TScrollBox on a form and add a few child controls:

Without adding any code, I am not able to scroll it vertically using the primary mouse wheel. Scrolling the wheel, nothing happens, as expected.
However, if I resize the form to make the horizontal scroll bar appear and use the thumb wheel on my MX Master mouse to scroll horizontally, a strange thing happens: the horizontal scroll bar becomes unthemed and moves according to the wheel, but the client area isn't scrolled:

That's odd, isn't it?
Well, by implementing an OnMouseWheel handler, it is trivial to make the main scroll wheel scroll vertically:
procedure TForm1.ScrollBox1MouseWheel(Sender: TObject; Shift: TShiftState;
  WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
begin
  ScrollBox1.VertScrollBar.Position := ScrollBox1.VertScrollBar.Position - WheelDelta;
  Handled := True
end;

To get the secondary scroll wheel to do horizontal scrolling, I try
procedure TScrollBox.WndProc(var Message: TMessage);
begin
  case Message.Msg of
    WM_MOUSEHWHEEL:
      begin
        HorzScrollBar.Position := HorzScrollBar.Position + TWMMouseWheel(Message).WheelDelta;
        Message.Result := 0;
      end;
  else
    inherited;
  end;
end;

to no avail.
However, if I change Message.Result to 1 (ignoring the documentation which states otherwise), it works as expected as long as the mouse is not above any windowed child control.
I seem to recall that my old Microsoft Touch Mouse was able to scroll horizontally without any issues. Also, Google suggests that many end users have issues with horizontal scrolling using the MX Master. Still, I am able to use my MX Master to scroll horizontally in web browsers, Microsoft Office, Notepad, and Paint.
What is the correct way to implement support for horizontal scrolling? And, if the correct approach is incompatible with the MX Master, is there any way to work around this incompatibility? After all, it is a common pointing device from a major manufacturer.


text:
Q: Создать регулярное выражение posix: любые года, кроме двух лет Нужно создать регулярное выражение в posix, которое будет находить любые года в скобках, кроме 2021 и 2022 года. Пока получилось только такое:
/\([0-9][0-9][^2][^1-2]\)
Нужно чтобы находило 1,3,5 строки. А это выражение не находит 1.
(2020)
(2021)
(1999)
(2022)
(2030)

A: Выражение, совместимое со стандартом POSIX ERE:
\([0-9]{2}([01][0-9]|20|2[3-9]|[3-9][0-9])\)

См. пример работы регулярного выражения.
Подробности:

*

*\( - (

*[0-9]{2} - две цифры

*([01][0-9]|20|2[3-9]|[3-9][0-9]):

*

*[01][0-9]| - от 00 до 19 или

*20| - 20 или

*2[3-9]| - от 23 до 29

*[3-9][0-9] - от 30 до 99

*\) - )
Для преобразования выражения в POSIX BRE (расширенный в утилитах GNU) измените экранирование:
([0-9]\{2\}\([01][0-9]\|20\|2[3-9]\|[3-9][0-9]\))


text:
Q: Other mathematical theories that are "tiered" like the iterative conception of sets? In the usual way of constructing the cumulative hierarchy under the iterative conception of sets, sets are constructed in levels. George Boolos, in his "The Iterative Conception of Set", devises a "stage theory" where each level/stage is akin to a possible world in modal logic and there is an "accessibility relation" that relates each stage to its predecessor stages. One popular way of understanding accessibility in this context is as a relation of dependence so that each stage depends on its predecessor stages.
Obviously this view of things isn't forced on us, but grant for the sake of the question this idea that the levels of the hierarchy "depend" on preceding levels. My question is whether there are other mathematical theories that seem to exhibit this same sort of "dependence" phenomena. For an intuitionist, just about any theory has this flavor since an object can be said to "depend" on any objects used in its construction. But are there examples from non-explicitly intuitionistic mathematical theories that seem to have this dependence/modal feature?


text:
Q: Problem with resolving superclass of a MapView ("Could not find class" problem) I'm trying to add MapView to one of my application.
View with correct mapView is added.
Permissions in Manifest are also following rules.
Project compiles with out a problem.
Library with maps is added.
But I'm still receiving this error.
Anyone had same problem and found a solution?
If you need more data, just let me know.
02-17 14:16:22.196: WARN/dalvikvm(20884): Unable to resolve superclass of Lnet/gynsoft/citydusseldorf/MapViewController; (27)
02-17 14:16:22.196: WARN/dalvikvm(20884): Link of class 'Lnet/gynsoft/citydusseldorf/MapViewController;' failed
02-17 14:16:22.204: ERROR/dalvikvm(20884): Could not find class 'net.gynsoft.citydusseldorf.MapViewController', referenced from method net.gynsoft.citydusseldorf.startActivity$5.onClick
02-17 14:16:22.204: WARN/dalvikvm(20884): VFY: unable to resolve const-class 121 (Lnet/gynsoft/citydusseldorf/MapViewController;) in Lnet/gynsoft/citydusseldorf/startActivity$5;

A: Yes, you must have referenced maps.jar library externaly rather then selecting google add on platform target for your application.
Select Google API as a  Target instead of adding maps.jar file externaly.
This will for sure remove this problem as i also faced it before

A: I usually get this error when I run an app that requires maps in the standard emulator. You need an emulator running Google API's as opposed to the standard one.
You can do this in the Android SDK and AVD manager.

A: Create lib folder, libs folder is for native libraries. I made it, add library to lib and to build path as internal library and it works!


text:
Q: If key not in JSON then set value to null and insert into dataframe I'm trying to get a value from a key in a JSON string and then insert that data into a dataframe.
But sometimes the column might appear in the structure or not, so if the key do not exist it gives me a error like 'KeyError': 'Company_Name_Abb'.
So if I get this error, the data will not be inserted to the dataframe and will pass to the next contract, but that's not what I want. If some key doesn't exist, I'd like to set a Null value to it, so it can be inserted normally to a dataframe.
So if you notice in the JSON string below, I didn't get the Company_Name_Abb key .
{
  "success": "true",
  "code": 200,
  "messages": null,
  "response": {
    "templateType": "",
    "metadata": {
      "AUTO_RENEWAL_PERIOD_MONTHS": "0",
      "Reminder_date": "",
      "Monetary_Type": "",
      "Legal_Entity": "Test Inc.",
      "BIZ_DEV_CONTACT": "Goofy",
      "Business_Owner": "Minnie Mouse",
      "Contract_Status": "Active",
      "Cond_exp_terms": "",
      "Contract_Category": "General",
      "Contract_Term_Period_UoM": "Years",
      "Customer_ID_Intel": "",
      "Expiry_Date_words": "June 08, 2024",
      "Royalty_Max_Value": "",
      "TIMEZONE": "US/Pacific - (GMT-8:00)",
      "Audit_Section_Num": "",
      "Same_as_Contract_Signed_Date": "Enter Date",
      "CNDA_Number": "12345",
      "Contract_Title": "'TEST AGREEMENT FOR API No 2",
      "ConfidentialContract": "No",
      "Heirarchy_Status": "Master Agreement",
      "RSNDA_Number": "",
      "Contract_Signed_On_date": 1623263400000,
      "Termination_Section_Num": "",
      "Region": "N.A.",
      "Contract_Expiration_Date": 1717785000000,
      "Historical_Audit_Date": "",
      "RSNDA_Date": "",
      "PCM_Contact": "",
      "License_Technology": "",
      "PCM_Obligation": "No",
      "MILES_SUMM": "",
      "Effective_Date_words": "June 09, 2021",
      "Amendments": [],
      "Contract_Effective_Date": 1623177000000,
      "Folder": "Default",
      "RUNDA_Date": "",
      "Contract_Owner": "test@test.com",
      "Licensed_Tech_Name": "",
      "Payment_Terms": "",
      "SUBLICENSE": "Test",
      "AUTO_RENEW": "Fixed",
      "ATTORNEY_NOTES": "",
      "Vendor_ID_Intel": "",
      "Attorney_Owner": "",
      "Monetary_Num": "",
      "RUNDA_Number": "",
      "Notes": "",
      "Contract_Desc": "This is a test",
      "ContractualDoc": [],
      "Contract_Renewal_Date": "",
      "Monetary_Sec_Num": "",
      "SearchableContract": "Yes",
      "AUTO_RENEWAL_MAXIMUM_NUMBER_OF_RENEWALS": "0",
      "AUTO_RENEWAL_NOTICE_DAYS": "0",
      "Intel_Product_Family": "",
      "CNDA_Date": 1623177000000,
      "DEV_PARTNER": "",
      "Contract_Term": "3"
    },
    "contractNumber": "INTEL29017",
    "supportingDocuments": [],
    "statusCode": "",
  },
  "responseMap": null
}

In the example below I just created two variables, but I'm getting all
of the keys from the JSON. And also the JSON above is just one
example, since the Foor Loop retrieves many JSON string as the one
above.

How I'm getting the values (JSON.text I'm retrieving from a API):
for element in jsoncontracts['response']['rows']:
    try:
        jsoncontractsdetails = json.loads(JSON.text)

        Auto_Renewal_Period_Months, Company_Name_Abb = jsoncontractsdetails['response']['metadata']['AUTO_RENEWAL_PERIOD_MONTHS'], jsoncontractsdetails['response']['metadata']['Company_Name_Abb']

        df_contractnumberdetails = pd.DataFrame([[Auto_Renewal_Period_Months, Company_Name_Abb]], columns=['AUTO_RENEWAL_PERIOD_MONTHS', 'Company_Name_Abb'], index=None)

    except Exception as e:
        print('ContractNumberError: ' + contract)
        print(e)
        pass

I already tried to Except KeyError and was able to assigned a value to it's key, but I couldn't insert to a dataframe because it was passing to the next contract in the loop.
UPDATE:
I tried to use defaultdict function from collections module, but after I try to access the key from the function I still get KeyError: 'Company_Name_Abb'.
jsoncontractsdetails = defaultdict(lambda: -1, jsoncontractsdetails)
Company_Name_Abb = jsoncontractsdetails['response']['metadata']['Company_Name_Abb']

A: pandas can handle dictionaries, you could feed the rows to pd.DataFrame and then select only the columns you need:
df = pd.DataFrame([m['response']['metadata'] for m in jsoncontracts['response']['rows']])

if you want to select the columns beforehand:
df = pd.DataFrame(
    [
        {
           k:v for k,v in m['response']['metadata'].items()
          if k in ('AUTO_RENEWAL_PERIOD_MONTHS', 'Company_Name_Abb')
        }
        for m in jsoncontracts['response']['rows']
    ]
)

A: There are several ways to do it.

*

*First, on the more fancy side is to use schema library and define JSON object schema you expect. You can set both required and optional fields, potentially with default values.

*Second, even more fancy, is to use dataclasses and dataclasses-json library for even more convenient access. I would call this way the most preferable in the long term since you have a really convenient data structure to work with.

*Lastly, the quickest way would be to use get() (for getting values) or setdefault() (for setting values to the nested dictionaries which might not exist) dict methods. For example, you can access one of your fields as jsoncontractsdetails.get('response', {}).get('metadata', {}).get('AUTO_RENEWAL_PERIOD_MONTHS', None). This method quickly gets messy, but works great for one-offs or in small quantities :)


text:
Q: Sort and Display XML Output in Powershell I've got a file called file.xml formatted as such:
<Sources>
  <add id="TestName" type="TestType" priority="1">
    <parameters>
      <otherIdentifiers>TestNameIdentifier</otherIdentifiers>
      <reportSource>TestReportSource</reportSource>
      <activeStatus>true</activeStatus>
      <UploadStatus>false</UploadStatus>
      <displayTypes>Image\,Report</displayTypes>
      <address.host>192.168.1.2</address.host>
    </parameters>
  </add>
  <add id="TestName2" type="TestType" priority="2">
    <parameters>
      <otherIdentifiers>TestName2Identifier</otherIdentifiers>
      <reportSource>TestReportSource2</reportSource>
      <activeStatus>true</activeStatus>
      <UploadStatus>false</UploadStatus>
      <displayTypes>Image\,Report</displayTypes>
      <address.host>192.168.1.3</address.host>
    </parameters>
  </add>
</Sources>

In Powershell I declare my file as:
[xml]$File = gc file.xml

The specific values I'm interested in are
$File.Sources.add.id
$File.Sources.add.type
$File.Sources.add.priority
$File.Sources.add.parameter.activeStatus
$File.Sources.add.parameter."address.host"

I know that I can get them each individually as formatted above, but I'm struggling to figure out how to display the information for each add node by itself formatted in a table as:
Source     Type     Priority     Active     IP Address

And the last thing I'm struggling to figure out is how to sort this by priority.  These sources are sorted in the order they were added, and sometimes a newer source gets a higher priority, so they're not necessarily in that order.
If anyone is able to help point me in the right direction, I'd be greatly appreciative.

A: You can use calculated properties.
This will get you started:
$f.Sources.add | Select-Object @{n='Source';e={$_.id}}, @{n='Type';e={$_.type}}, @{n='Priority';e={$_.priority}} | Sort-Object -Property Priority