text:
Q: Cannot Maintain RecyclerView Position on Screen Rotation I am loading a RecyclerView that is based on calls to Retrofit and data stored in a local SQLite database.
On Screen rotation, the RecyclerView keep resetting. In addition, when I favorite a movie (add the movie to my local room database), there are instances where my spinner doesn't align with the data to populate in the RecyclerView. Below is my code:
public class MainActivity extends AppCompatActivity {

private RecyclerView mMovieResults;
private MyAdapter mMovieResultsAdapter;
private String query;
private String mBaseURL;
private int lastFirstVisiblePosition;
//TODO: How is someone able to load my API Key if I am storing it

private ArrayList<String> mMovieURLS;
private ArrayList<Movie> mMovies;
private List<Movie> mMovieResultsList;

private static final String SPINNER_SELECTION = "SPINNER_SELECTION";

private boolean mIsFavoriteSelected;

private AppDatabase mDb;

private Spinner mSpinner;

private SharedPreferences mPrefs;
private SharedPreferences.Editor mPrefsEditor;

private static Bundle mBundleRecyclerViewState;

private int saved_selection = -1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.v("ONCREATE", "ONCREATE");
    if (savedInstanceState != null){
        saved_selection = savedInstanceState.getInt(SPINNER_SELECTION);
    }

    if (isOnline()) {
        setContentView(R.layout.activity_main);
        Stetho.initializeWithDefaults(this);
        mDb = AppDatabase.getInstance(getApplicationContext());
        mMovieResults = findViewById(R.id.main_recyclerview_image_results);
        GridLayoutManager glm = new GridLayoutManager(this, 3);
        glm.setOrientation(LinearLayoutManager.VERTICAL);
        mMovieResults.setLayoutManager(glm);
        mMovieURLS = new ArrayList<>();
        mMovies = new ArrayList<>();
        mMovieResultsList = new ArrayList<>();
        mMovieResultsAdapter = new MyAdapter(mMovieResultsList);
        mMovieResults.setAdapter(mMovieResultsAdapter);
        mDb = AppDatabase.getInstance(getApplicationContext());
        mPrefs = getSharedPreferences("prefs", MODE_PRIVATE);

        mPrefsEditor = mPrefs.edit();
        switch (saved_selection){
                case 0:
                    mBaseURL = "https://api.themoviedb.org/3/movie/popular/";
                    calltoRetrofit(mBaseURL);
                    break;
                case 1:
                    mBaseURL = "https://api.themoviedb.org/3/movie/top_rated/";
                    calltoRetrofit(mBaseURL);
                    break;
                case 2:
                    mIsFavoriteSelected = true;
                    mMovieURLS.clear();
                    retrieveMovies();
                    break;

                default:
                    mBaseURL = "https://api.themoviedb.org/3/movie/popular/";
                    break;
            }

    } else {
        setContentView(R.layout.activity_no_internet);
        return;
    }

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.action_bar_spinner, menu);
    MenuItem item = menu.findItem(R.id.spinner);
    mSpinner = (Spinner) item.getActionView();
    if (isOnline()) {
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getApplicationContext(), R.array.spiner_list_item_array, R.layout.custom_spinner);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mSpinner.setAdapter(adapter);
        if (saved_selection >= 0){
            mSpinner.setSelection(saved_selection);
        }
        mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                mPrefsEditor.putInt(SPINNER_SELECTION, i);
                mPrefsEditor.commit();
                switch (i) {
                    case 0:
                        mBaseURL = "https://api.themoviedb.org/3/movie/popular/";
                        calltoRetrofit(mBaseURL);
                        break;
                    case 1:
                        mBaseURL = "https://api.themoviedb.org/3/movie/top_rated/";
                        calltoRetrofit(mBaseURL);
                        break;
                    case 2:
                        mIsFavoriteSelected = true;
                        mMovieURLS.clear();
                        retrieveMovies();
                        break;

                    default:
                        mBaseURL = "https://api.themoviedb.org/3/movie/popular/";
                        break;
                }

            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        return true;
    } else {
        return true;
    }
}

@Override
protected void onSaveInstanceState(Bundle outState) {
    outState.putInt(SPINNER_SELECTION, mSpinner.getSelectedItemPosition());
    super.onSaveInstanceState(outState);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    super.onOptionsItemSelected(item);
    int x = item.getItemId();
    Log.v("OPTIONS_ID", String.valueOf(x));
    return true;
}

private void retrieveMovies() {
    //TODO: I am unsure if I am handling correctly. When I favorite and unfavorite a movie, and then go back to the MainActivity, it is not displaying the correct item from the Spinner.
    //TODO: For example, favorites may be listed in the Spinner, however the screen may be displaying "TOP"
    //TODO: How could I tell if I am making unnecessary queries to Room? I know it is a project requirement, but I was not sure how to handle if I am making unnecessary calls
    //TODO: on screen rotation
    MainViewModel viewModel = ViewModelProviders.of(this).get(MainViewModel.class);
    final LiveData<List<Movie>> movies = viewModel.getMovies();
            movies.observe(this, new Observer<List<Movie>>() {
        @Override
        public void onChanged(@Nullable final List<Movie> movies) {
            for (Movie movie : movies) {
                String photoURL = "http://image.tmdb.org/t/p/w185" + movie.getPoster_path();
                Log.v("FAVORITE_URL", photoURL);
                mMovieURLS.add(photoURL);
            }
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mMovieResultsList = movies;
                    mMovieResultsAdapter.notifyDataSetChanged();
                }
            });

        }
    });
}

@Override
protected void onResume() {
    super.onResume();
    ((GridLayoutManager) mMovieResults.getLayoutManager()).scrollToPositionWithOffset(lastFirstVisiblePosition,0);
}

private void calltoRetrofit(String mBaseURL) {
    mMovieURLS.clear();
    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);
    OkHttpClient client = new OkHttpClient
            .Builder()
            .addInterceptor(interceptor)
            .build();

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(mBaseURL)
            .client(client)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    final ApiInterface apiInterface = retrofit.create(ApiInterface.class);

    Log.v("API", API_KEY);
    Call<Movies> call = apiInterface.getImages(API_KEY);
    call.enqueue(new Callback<Movies>() {
        @Override
        public void onResponse(Call<Movies> call, Response<Movies> response) {
            Log.v("RESPONSE", response.body().toString());
            String totalPages = String.valueOf(response.body().getTotal_pages());
            Log.v("TOTAL", totalPages);
            mMovieResultsList = response.body().getResults();
            for (Movie movie : mMovieResultsList) {
                if (movie.getPoster_path() != null) {
                    String photoURL = "http://image.tmdb.org/t/p/w185" + movie.getPoster_path();
                    mMovieURLS.add(photoURL);
                }
                mMovieResultsAdapter.notifyDataSetChanged();
            }
        }

        @Override
        public void onFailure(Call<Movies> call, Throwable t) {
            Log.v("FAILURE", t.toString());
        }
    });
}

@Override
public void onPointerCaptureChanged(boolean hasCapture) {

}

@Override
protected void onPause() {
    super.onPause();
    lastFirstVisiblePosition = ((GridLayoutManager)mMovieResults.getLayoutManager()).findFirstCompletelyVisibleItemPosition();

}

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {

    public class ViewHolder extends RecyclerView.ViewHolder {

        protected ImageView mResultImage;

        public ViewHolder(View itemView) {
            super(itemView);
            mResultImage = itemView.findViewById(R.id.movie_poster_image);
        }
    }

    public MyAdapter(List<Movie> mDataset) {
        mMovieResultsList = mDataset;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.movie_poster_image, parent, false);
        return new ViewHolder(v);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, final int position) {
        final String urlForPhoto = "http://image.tmdb.org/t/p/w185" + mMovieResultsList.get(position).getPoster_path();

        Picasso.get()
                .load(urlForPhoto)
                .into(holder.mResultImage);

        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(getApplicationContext(), IndividualMovieActivity.class);
                i.putExtra("Movie", mMovieResultsList.get(position));
                startActivity(i);
            }
        });

    }

    @Override
    public int getItemCount() {
        return mMovieResultsList.size();
    }

}

public interface ApiInterface {
    @GET("?language=en-US")
    Call<Movies> getImages(@Query("api_key") String api_key);
}

private boolean isOnline() {
    ConnectivityManager cm =
            (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    return netInfo != null && netInfo.isConnectedOrConnecting();
}

A: RecyclerView only saves its scroll position up until you call setAdapter. By calling setAdapter while you still have no data, the scroll position is discarded (it can't scroll to position 4 if there's no position 4).
You should wait until you have data to call setAdapter.

A: When you rotate your device, android detects the change in configuration and restarts the activity by default. in this way your activity calls the adapter again and your recyclerview returns to zero position. by adding the command below, you mean that you handle this configuration changes yourself, so the android won't restart your activity.
add this line to activity tag in manifest file
android:configChanges="screenSize|orientation"
like this:
    <activity
        android:name=".SearchActivity"
        android:configChanges="screenSize|orientation"
        android:label="@string/search"
        android:theme="@style/AppTheme.NoActionBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>


text:
Q: PHP Form not working like last week My hosting supplier just upgraded PHP from 5.3 to 5.4 so I'm not sure whether this has affected any forms on my website because it was working last week fine.
This is my form
<form action="insert.php" method="post">

1. Artist Name: <input id="artist" name="artist" type="text" />

2. Song Name: <input id="song" name="song" type="text" />

3. Label: <input id="label" name="label" type="text" />

4. Genre:
<select name="genre"><option value="RnB">RnB</option></select>
<select name="genre"><option value="Hip Hop">Hip Hop</option></select>
<select name="genre"><option value="Reggae">Reggae</option></select>
<select name="genre"><option value="Gospel">Gospel</option></select>
<select name="genre"><option value="Dance">Dance</option></select>
<select name="genre"><option value="Jazz">Jazz</option></select>
<select name="genre"><option value="Afrobeats">Afrobeats</option></select>
<select name="genre"><option value="Soul">Soul</option></select>

5. Country/Area:
<select name="country"><optgroup label="Country"><option value="UK">UK</option>  </optgroup></select>
<select name="country"><optgroup label="Country"><option value="US">US</option></optgroup></select>
<select name="country"><optgroup label="Country"><option value="CANADA">CANADA</option> </optgroup></select>
<select name="country"><optgroup label="Country"><option value="JAMAICA">JAMAICA</option></optgroup></select>

<select name="country"><optgroup label="Area"><option value="CARIBBEAN">CARIBBEAN</option></optgroup></select>
<select name="country"><optgroup label="Area"><option value="S.AMERICA">S.AMERICA</option></optgroup></select>
<select name="country"><optgroup label="Area"><option value="AFRICA">AFRICA</option></optgroup></select>
<select name="country"><optgroup label="Area"><option value="EUROPE">EUROPE</option></optgroup></select>
<select name="country"><optgroup label="Area"><option value="AUS">AUS</option></optgroup></select>
<select name="country"><optgroup label="Area"><option value="ASIA">ASIA</option></optgroup></select>

6. Song Link (Youtube Only): <input id="songlink" name="songlink" size="50" type="text" />

7. Artist Photo Link (Square): <input id="artistphoto" name="photolink" size="35" type="text" />

8. Email Address: <input id="email" name="email" type="text" />

<input type="submit" />

</form>

This is the bulk of my my insert.php file
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

// Get values from form
$Artist=$_POST['artist'];
$Song=$_POST['song'];
$Label=$_POST['label'];
$Genre=$_POST['genre'];
$Country=$_POST['country'];
$SongLink=$_POST['songlink'];
$PhotoLink=$_POST['photolink'];
$Email=$_POST['email'];

// Insert data into mysql
$sql="INSERT INTO $tbl_name(artistname, songname, label, genre, country, songlink, photolink, email)VALUES('$artist','$song','$label','$genre','$country','$songlink','$photolink','$email')";
$result=mysql_query($sql);

// if successfully insert data into database, displays message "Successful".
if($result){
echo "Successful";
echo "
";
echo "Back to main page";
}

else {
echo "ERROR";
}
?>

<?php
// close connection
mysql_close();
?>

When I submit the form now it shows up empty in my sql database.

A: Your POST variables' letter-cases do not match your values.
$Artist=$_POST['artist'];
$Song=$_POST['song'];
$Label=$_POST['label'];
$Genre=$_POST['genre'];
$Country=$_POST['country'];
$SongLink=$_POST['songlink'];
$PhotoLink=$_POST['photolink'];
$Email=$_POST['email'];

and your VALUES
('$artist','$song','$label','$genre','$country','$songlink','$photolink','$email')

doesn't match. They're case-sensitive.
Change it to:
('$Artist','$Song','$Label','$Genre','$Country','$SongLink','$PhotoLink','$Email')

Footnotes:
Add error reporting to the top of your file(s)
error_reporting(E_ALL);
ini_set('display_errors', 1); when in development.
mysql_* functions deprecation notice:
http://www.php.net/manual/en/intro.mysql.php
This extension is deprecated as of PHP 5.5.0, and is not recommended for writing new code as it will be removed in the future. Instead, either the mysqli or PDO_MySQL extension should be used. See also the MySQL API Overview for further help while choosing a MySQL API.
These functions allow you to access MySQL database servers. More information about MySQL can be found at » http://www.mysql.com/.
Documentation for MySQL can be found at » http://dev.mysql.com/doc/.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python: How to check if value is in between multiple indices of two lists? I am analysing a video frame by frame with cv2, in which I want to save the frame as 1 if the frame number is in between certain timestamps and as 0 if not.
I've got two lists, one with the start times and one with the end times:
start_times = [0, 10, 15]
end_times = [2, 12, 17]

I want to save the frame as 1 for frame numbers 0,1,2 & 10,11,12 & 15,16,17 and as 0 for the others.
My code saves the correct frames as 1, but it saves unwanted frames as 0 because I'm using a for loop. See the simplified example below:
start_times = [0,10,15]
end_times = [2,12,17]

currentframe = 0

while True:
    try:
        for index,time in enumerate(start_times):
            if start_times[index] <= currentframe <= end_times[index]:
                print('save images as 1')
            else:
                print('save images as 0')
        currentframe += 1

        if currentframe == 20:
            break

    except IndexError:
        break

Which outputs for the first frame:
save images as 1
save images as 0
save images as 0

How can I change my code so the first frame is saved only as 1?

A: I'm not sure if I clearly understood you, but try this and tell me if it is what you want:
start_times = [0,10,15]
end_times = [2,12,17]

times = sorted(start_times + end_times)
print(times)

i = 0
while i + 1 < len(times):
  k = times[i]
  while k <= times[i + 1]:
    if i % 2 == 0:
      print('save [frame {}] as 1'.format(k))
    else:
      print('save [frame {}] as 0'.format(k))
    k += 1
  i += 1

A: I think this is what you are looking for?
while curr_frame < 20:
    is_in = any(filter(lambda start_end: start_end[0] <= curr_frame <= start_end[1],
                       zip(start_times, end_times))))
    print(f'Save image as {int(is_in)}')
    curr_frame += is_in

A: A friend of mine has given me the solution by using ranges:
current_frame = 0
start_times = [0, 10, 15]
end_times = [2, 12, 17]
ranges = [range(start, stop) for start, stop in zip(start_times, end_times)]

while True:
    if any([current_frame in my_range for my_range in ranges]):
        print('save image as 1')
    else:
        print('save image as 0')
...


text:
Q: Launch external process associated with a file and send this application to the back I've seen loads of code to launch an external application via a file, but that's not the problem. To clarify exactly the behaviour I want:

*

*For a given filename, launch the correct process.

*If there is no associated process, the proper shell dialog should prompt the user to associate one.

*While the application is launched, this application needs to go to the back of the Z-order (or just behind the app that is launching) and STAY THERE.

Step 3 is what I haven't got right. I am launching Photoshop via a psd file, but while the aplash screen is shown, it flashes as my app fights for the focus. Once it starts up properly, all is well, but I don't like the flickering while the flash screen is displayed.
Here is my best attempt so far:
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Romy.Core
{
    internal static class Example
    {
        public const int SW_RESTORE = 9;

        private static readonly IntPtr HWND_BOTTOM = new IntPtr(1);

        private const uint SWP_NOACTIVATE = 0x0010;

        private const uint SWP_NOMOVE = 0x0002;

        private const uint SWP_NOSIZE = 0x0001;

        public static void SendWindowBack(IntPtr handle)
        {
            NativeMethods.SetWindowPos(handle, HWND_BOTTOM, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE);
        }

        public static async void ShellExecuteFile(this IWin32Window window, string filename)
        {
            var p = Process.Start(new ProcessStartInfo()
            {
                FileName = filename,
                Verb = "open",
                UseShellExecute = true,
                ErrorDialog = true
            });

            SendWindowBack(window.Handle);

            try
            {
                await Task.Run(async () =>
                {
                    try
                    {
                        p.WaitForInputIdle();
                        IntPtr handle = p.MainWindowHandle;

                        while (handle == IntPtr.Zero)
                        {
                            await Task.Delay(TimeSpan.FromMilliseconds(250D));
                            handle = p.MainWindowHandle;
                        }

                        if (handle != IntPtr.Zero)
                        {
                            if (NativeMethods.IsIconic(handle))
                                NativeMethods.ShowWindowAsync(handle, SW_RESTORE);

                            if (NativeMethods.SetForegroundWindow(handle))
                                NativeMethods.SetActiveWindow(handle);
                        }
                    }
                    catch (InvalidOperationException) { }
                    catch (PlatformNotSupportedException) { }
                    catch (NotSupportedException) { }
                    catch (Exception ex) { ex.Log(); }
                }).TimeoutAfter(TimeSpan.FromSeconds(3D));
            }
            catch (TimeoutException) { }
        }

        [SuppressUnmanagedCodeSecurity]
        internal static class NativeMethods
        {
            [DllImport("user32.dll")]
            [return: MarshalAs(UnmanagedType.Bool)]
            internal static extern bool IsIconic(System.IntPtr hWnd);

            [DllImport("user32.dll")]
            [return: MarshalAs(UnmanagedType.Bool)]
            internal static extern bool SetForegroundWindow(System.IntPtr hWnd);

            [DllImport("user32.dll")]
            internal static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter,
                int X, int Y, int cx, int cy, uint uFlags);

            [DllImport("user32.dll")]
            [return: MarshalAs(UnmanagedType.Bool)]
            internal static extern bool ShowWindowAsync(System.IntPtr hWnd, int nCmdShow);

            [DllImport("user32.dll")]
            internal static extern System.IntPtr SetActiveWindow(System.IntPtr hWnd);
        }
    }
}

A: Try removing your call to SendWindowBack and replace SetForegroundWindow with SetWindowLong. This should meet your requierment:

...(or just behind the app that is launching) and STAY THERE..

const int GWL_HWNDPARENT = (-8);

[DllImport("user32.dll", SetLastError = true)]
static extern int SetWindowLong(IntPtr childHandle, int nIndex, IntPtr parentHandle);

if (handle != IntPtr.Zero)
{
    if (NativeMethods.IsIconic(handle))
        NativeMethods.ShowWindowAsync(handle, SW_RESTORE);

    SetWindowLong(handle, GWL_HWNDPARENT, window.Handle)
    NativeMethods.SetActiveWindow(handle);
}


text:
Q: How to check if an array contains empty elements? Let's make some examples:
array("Paul", "", "Daniel") // false
array("Paul", "Daniel") // true
array("","") // false

What's a neat way to work around this function?

A: So array_filter() will remove empty the elements from the array and then return this array.
Comparing the returned array to the original array would not be the same.
Meaning the array contains one or more empty elements.
$array = array("Paul", "", "Daniel");
if($array != array_filter($array)) {
    echo "Array contains empty values.";
}

A: function has_empty(array $array)
{
    return count($array) != count(array_diff($array, array('', null, array())));
}

A: Try using in_array:
return !in_array("", array("Paul", "", "Daniel")); //returns false

A: The answer depends on how you define "empty"
$contains_empty = count($array) != count(array_filter($array));

this checks for empty elements in the boolean sense. To check for empty strings or equivalents
$contains_empty = count($array) != count(array_filter($array, "strlen"));

To check for empty strings only (note the third parameter):
$contains_empty = in_array("", $array, true);

A: function testEmpty($array) {
  foreach ($array as $element) {
    if ($element === '')
      return false;
  }
  return true;
}

Please check out the comments down below for more information.

A: Not exactly the answer to the question, but many visitors come here by searching for a solution to this slightly different case:
Check, if an array ONLY contains empty strings
This would be a simple solution with implode(), that will fit to some needs
function testIfEmpty($array) {
    $flat = implode('', $array);
    return !empty($flat):
}

A: Since I do enjoy me some fancy anonymous functions here is my take on it. Not sure about performance, but here it is:
$filter = array_filter(
        ["Paul", "", "Daniel"],
        static function ($value) {
            return empty($value); // can substitute for $value === '' or another check
        }
    );

return (bool) count($filter);

Logically explained. If anonymous returns true, it means that it found an empty value. Which means the filter array will contain only empty values at the end (if it has any).
That's why the return checks if the filter array has values using count function.
The (bool) type cast is equivalent to return count($filter) === 0.
May you all find the happiness you seek.


text:
Q: Why does (?:...) regex behave differently for re.match and re.findall? I was working on a CS50 problem where you have to find consecutively repeating pattern of strings (nucleotides in a DNA sequence). I figured I'd use re since it's Python3 assignment and I've tinkered it with a little bit before and thought I could figure it out... but nope.
So I searched how I could accomplish this and found a topic where a user suggested using re.findall("(?:<pattern>)+", <string>) and it was exactly what I needed to solve the problem.
So I got curious about the ?: expression and looked up the documentation but couldn't understand what it meant by a non-capturing group and, again, had to look around for an answer when I found an explanation using a string composed of a web address.
In this specific example the user was using re.match:
"(?:https?|ftp)://(stackoverflow.com)"

output:
    group1: (stackoverflow.com)
vs

"(https?|ftp)://(stackoverflow.com)"

output:
    group1: (https)
    group2: (stackoverflow.com)

At this point I understood what non-capturing meant... but now I did not understand why ?: behaved differently for re.match and re.findall, where the match object, as described in the official documentation, does not capture the indicated group while the returned list from re.findall method seemingly capturing the matching substring and grouping consecutive repetitions as one.
My best guess is that since it's non-capturing the method continues to find matching substrings consecutively and once it ends it "closes" the group and that is why the repeated substrings are grouped as one. But I still don't know why re.findall returns what is not supposed to be captured and if someone can point me in the right direction I'd really appreciate it.

A: A 'capturing group' in regex is normally denoted by parentheses. In a regex like this:
<before>(<capture>)<after>

the 'capturing group' is (<capture>), and it means that this is the part of the string that we actually want - the rest of the regex is meant to target that. We need this for capturing, say, "numbers followed by the word 'dollar'":
(\d+)\s*dollar

re.match() returns a Match object, which has several 'groups' you can access with the .group(n) method.

*

*Group 0 always contains the entire matched string, regardless of any 'match groups' within it. In the above example, matched against the string "35 dollar item", it would be `"35 dollar".

*Group n > 0 contains the nth capture group in the regex. In the above example, matched against the string "35 dollar item", it would be simply "35".

re.findall() has behavior that differs based on the number of capturing groups in the regex:

*

*if there are no capturing groups, return a list of all strings matching the entire regex (e.g. .group(0))

*if there is exactly one capturing group, return a list of all strings matching just that capturing group (e.g. .group(1))

*if there is more than one capturing group, return a list of tuples of (.group(1), .group(2), ..., .group(n)).

The idea of a non-capturing group is that sometimes we want to use expressions that require parentheses to disambiguate them. Most commonly, |. For example, if I wanted to capture the surname (but not the title) of someone addressed by "Mr." or "Ms.", I might write a regex like so:
(?:Mr|Ms)\.\s*(\w+)

(?:Mr|Ms) is a non-capturing group, so it won't be treated as its own group (e.g. .group(1)). Meanwhile, (\w+) is a capturing group, so it will be treated as its own group. From there, we can observe the behaviors of re.match() and re.findall(), and see that they're consistent with their documentation:
>>> regex = r'(?:Mr|Ms)\.\s*(\w+)'
>>> mo = re.match(regex, 'Mr. Big and Ms. Small')
>>> mo.group(0)
'Mr. Big'
>>> mo.group(1)
'Big'
>>> re.findall(regex, 'Mr. Big and Ms. Small')
['Big', 'Small']

Because there's only one capture group, re.findall() ignores group 0.
Contrast behavior of the following, which would register Mr and Ms as capture groups, and thus produce different output (since now there's more than one capture group, so re.findall() changes its output format:
>>> regex2 = r'(Mr|Ms)\.\s*(\w+)'  # omitting the ?:
>>> re.findall(regex2, 'Mr. Big and Ms. Small')
[('Mr', 'Big'), ('Ms', 'Small')]


text:
Q: Only using certain parts of Autocomplete from Material UI I'm trying to use Material-UI's component <Autocomplete/>
However, I want to remove certain functionality that isn't necessarily customizable according to the API. For example I want to remove the multiselect filter tags and shown below. Would it be possible just to take the logic of passing in a list and being able to search/autocomplete?


text:
Q: Get the child element of another child element directly using map()? Using REST Countries API for a course exercise, for example all I need is the common of the name from the data, and later do common with filter() ,I write like this:
const name = countries.map((c) => c.name);
const commonName = name.map((n) => n.common);

filteredName = commonName.filter((n) => n.toLowerCase().includes(findCountry.toLowerCase()))

It works, but the variable name will not be used anymore, so maybe looks stupid?
If I write like this:
const name = countries.map((c) => c.name.map((n) => n.common);

or:
filteredName = name.common.filter((n) => n.toLowerCase().includes(findCountry.toLowerCase()))

totally not works.
I'm new to this and have read the MDN documentation on array and map(). Just like to know if there is an obvious way to extract the common from the data to make some functions.
THANKS A LOT!!

A: Map all name.common from all data (api /all).

const commonNames = fetch(`//restcountries.com/v3.1/all`)
  .then(r => r.json())
  .then(r => r.map(c => c.name.common))
  .then(names => console.log( `find Namibia: ${
      names.find(n => n === `Namibia`)}\n\nAll names:\n\n${
        names.join(`\n`)}`) );
.as-console-wrapper {
    max-height: 100% !important;
}


text:
Q: jQuery: How to redo an Ajax Post when it takes too long? Sometimes it seems that a request is frozen. How can I cancel it and call it again when it takes a long time?
Sometimes the latency is more than 10 minutes because the Ajax post checks the Twitter API, and Twitter API sometimes, you know! :)

A: You can use the timeout option. Have a look at the documentation.
You can set the timeout at a reasonable value. If a timeout occurs, the callback error will be called and the second argument will have "timeout" as value.

A: Use the timeout option:
http://docs.jquery.com/Ajax/jQuery.ajax#toptions

A: you can always place that call in a timeout or a queue and perform it ever x minutes... when it's thr, set a boolean variable to true and when that time comes, it will not call the function... when you need to call that again, set it again to false...
var getResults = true;

settimeout( function() {
    if( getResults ) {
       // call your ajax method
       ...
       onSuccess:
          ...
          getResults = false;
    }
}, 1000 );

something like this...


text:
Q: python logging multiple calls after each instantiation I have multiple modules and they each have their own log. The all write to the log correctly however when a class is instantiated more than once the log will write the same line multiple times depending on the number of times it was created.
If I create the object twice it will log every messages twice, create the object three times it will log every message three times, etc...
I was wondering how I could fix this without having to only create each object only once.
Any help would be appreciated.

A: I was adding the handler multiple times after each instantiation of a log. I checked if the handler had already been added at the instantiation and that fixed the multiple writes.


text:
Q: Show a function $F$ is quasi-concave Show that a function $F$ is quasi-concave if $h(x) = g(F(x))$ is a concave function for some strictly increasing function g from R to R.
I already know that if $h$ is concave, then $h$ must be quasi-concave, but given that $h$ being a monotone transformation of function $F$ is concave (also quasi-concave), how to prove that $F$ must also be quasi-concave?
Note that the a function is quasi-concave if for any $x_0$ and $x_1$ and any convex combination $x_\lambda$, if $f(x_1)\ge f(x_0)$ then $f(x_\lambda)\ge f(x_0)$.


text:
Q: Managing UFT scripts in bitbucket by integrating to ALM? We have a requirement to kick start the UFT code from ALM by importing the latest update from bit bucket.We are using hp alm 12.55 and UFT 14.03.
interested to know if there any plug in or any other way to manage efficiently?


text:
Q: Combine two different dimensional arrays PHP I have two different dimensional arrays.
Array 1:
Array1
(
[0] => Array
    (
        [id] => 123
        [price] => 5
        [purchase_time] => 2014/4/10
    )
[1] => Array
    (
        [id] => 123
        [price] => 5
        [purchase_time] => 2014/5/17
    )
)

Array 2:
Array2
(
    [0] => 5
    [1] => 8
)

I want something like this:
Array
(
[0] => Array
    (
        [id] => 123
        [price] => 5
        [purchase_time] => 2014/4/10
        [Qty] => 5
    )
[1] => Array
    (
        [id] => 123
        [price] => 5
        [purchase_time] => 2014/5/17
        [Qty] => 8
    )
)

Basically the first array is the information I got from a SQL table. The second array contains the quantity for the products sold. I now want to combine these two array together and use the combined array to create a new table. Since these two arrays have different dimensions. I'm not sure how to do it. Here is my try:
$i = 0;
foreach($array1 as $row)
{
    $newarray = array_merge($row,$array2[$i]);
    $i++;
}

A: Might be a simpler way, but for fun without foreach:
array_walk($array1, function(&$v, $k, $a){ $v['Qty'] = $a[$k]; }, $array2);

A: The simplest way is:
$i = 0;
foreach($array1 as &$row) {
    $row['Qty'] = $array2[$i++];
}

Or if keys of both arrays are the same (0,1,2...) and array have the same length:
foreach($array1 as $k => &$row) {
    $row['Qty'] = $array2[$k];
}

A: If the $array1 and $array2 are mapped by the same indexes, so they have same length, you can try:
foreach($array2 as $index=>$quantity){
  $array1[$index]['Qty'] = $quantity;
}

And it´s done!
If you want to keep the original $array1 untouched, you can make a copy before the foreach.

A: Create new array and store it there. You can access the value of $array2 because they have the same index of $array1 so you can use the $key of these two arrays.
   $array3 = [];
   foreach($array1 as $key => $val) {
     $array3[] = [
       'id' => $val['id'],
       'price' => $val['price'],
       'purchase_time' => $val['purchase_time'],
       'Qty' => $array2[$key]
     ];
   }

  print_r($array3);


text:
Q: Sorting a string based on a word in a dictionary value How can I sort the string based on the word value in a dictionary?
a = 'A B'
b = {'B':0, 'A':1}

Desired result:
c = 'B A'

What I've tried:
c = sorted(a, key=b.values())

But got an error:

TypeError: 'dict_values' object is not callable

Is there an easy way of sorting words in a string?
UPDATE
After using:
" ".join(sorted(b, key=b.get))

I get all of the b values, whereas I only want to sort the ones present in the string.
a = 'A B'
b = {'B':0, 'A':1, 'C':2}

Produces
'BAC`

I would only need:
'BA`

A: You are close to the solution. Unfortunately, a callable is different than a dictionary and key needs to be a callable (function):
c = ' '.join(sorted(a.split(), key=lambda v: b[v]))

A: You can sort a list, but not strings, also you need to specify things as "elements of a list", as the keys of the dictionary don't map to a string...(there's probably a better way of phrasing this).
Anyway the solution is to split a and then apply the sort:
c = sorted(a.split(), key=lambda x: b[x])

Output:
['B', 'A']

For completeness:
" ".join(sorted(a.split(), key=lambda x: b[x]))


text:
Q: Setting the line length in R Google R style guide suggests line length of maximum 80 characters. I was wondering how do I set the line length in R. In stata this is done as:
set linesize 80

A: Is:
options()$width

what you want?
You can set it like:
options(width=80)


text:
Q: What's the point in being a "skeptical" learner I have a big problem:
When I read any mathematical text I'm very skeptical. I feel the need to check every detail of proofs and I ask myself very dumb questions like the following: "is the map well defined?", "is the definition independent from the choice of representatives" etc... Even if  the author of the paper/book says that something is a easy to check, I have this impulse to verify by myself.
I think that this approach is philosophically a good thing, but it leads to severe drawbacks:

*

*I waste a lot of time in reading few lines of mathematics, and at the end of the day I look at what I've done and I realize that I managed to go through a few theorems without learning enough. Remember that  when one  is a (post)graduate student (s)he has plenty of things to learn, so the time is almost never enough.

*This kind of learning could be affordable for undergraduate texts, but very often is almost impossible to read a paper with a skeptics point of view. At a certain point things become very complicated and the only way out is to accept results on faith.
And finally the real object of my question:
3. Despite the big effort I've employed in reading very carefully something, after few  weeks or months I obviously forget the details. So, for example if I try to read again a proof after a while, maybe I would remember the big picture but probably I would check again the details as though I'd never done it yet.
Therefore, even if the common rules for a mathematician say that "learning" should ideally be done skeptically, I've finally realized that maybe this is not very healthy. Now, could you recommend  a sort of royal road for reading mathematics? It should be a middle way between accepting every result as true and going through every detail. I'd like to know  what to do in practice.

A: I think there's a time and place for both. On the one hand, if you can step through and see how the author got where they were going, you tend to learn the material at a much deeper, more nuanced level. One of my learning techniques is to explain how some new concept works to an imaginary friend, because that forces me to understand it myself.
On the other hand, if you're midway through the semester and you get hung up trying to figure out why something works, you may block out a week or two of critical lecture material explaining how to use it, which really sets you up for failure for the rest of the class. In this case, it's better to set aside your desire for detail until you've sorted out everything you need to know for upcoming homework and/or the next midterm.
One thing about the "faith-based" acceptance of the material, is that it really isn't in many cases. If you can take the end result and apply it to get practical results, it's obviously at least partially right. I don't have to algebraically solve a derivative to show the results of a given derivative are consistent with real-world data from my car, for example.
Another thing you mention is how you want to go back through every detail on subsequent readings. While you may have forgotten them since the last time, your brain probably retained a decent amount of it, so as you step back through it, you'll start to recall enough tidbits that it isn't as tedious and time-consuming. For things you plan to use a lot, this sort of refresher is a good thing.
However, if it's fairly abstract stuff you aren't going to use in practice, it might be better to take a bit of it on faith. After all, not only is the author a pretty smart person, but you confirmed their findings last time. There's no rational reason it's going to be different this time unless you've come up with a totally different set of assumptions you're trying to apply the result to.

A: @EricTowers answer is excellent, and it lines up the best with what I see asserted by top mathematicians about how they read proofs; there should be an initial "scanning" process for the big ideas and the overall structure of the proof. This should tell you whether the proof is "interesting" or novel in a way that deserves your time to dig into the gritty details.
Richard Lipton writes about this sometimes on his blog:

*

*Proofs and Elevator Rides (A guide to tell if a proof is a proof)

*Proving a Proof (How to convince someone your proof is really a proof)

*Is This a Proof? (Seeking the limits of mathematical proofs)

*Facts No One Really Checks (Basic theorems that rarely get proved in full detail)
I think that one of the points some of these guys make is that mathematics is still (or especially) a work of community, and to some extent you still have to trust/ communicate/ convince/ stand on the shoulders of other people as part of the work. I'm still wrestling with that idea myself, and you'll have to find your own way through that thicket, but it's food for thought.

A: My suggestion would be to take notes the first time you read a paper or a book. For instance, each time you ask yourself a question, just write a short answer in the margin${}^{(*)}$. In this way, when you read again the document, you will have an instant access to your answers. This method is especially useful if you collect examples and counterexamples and improves your understanding of mathematical objects.
${}^{(*)}$ Or in a notebook, as the margin is notoriously too small for some people...

A: I have the same "problem" like you, I want to understand every detail. And by this my progress is slow and I always have the feeling that there is still so much to learn and still so much to do.
But one thing I learned as time passed by, that some domains have certain standard arguments and how to think about certain constructions behind merely formal checking. And until you have not internalized them checking them makes it sometimes hard to follow arguments or understand the reasoning behind it.
Maybe I give you an example from my recent studies. I had to study group theory approximately 6 months ago and entered the field with almost no knowledge about it behind the basic definitions. I started reading certain papers and felt almost (and still do...) overwhelmed. In the domain I am concerned with a special class of groups called Frobenius groups arise, they have one quite obvious definition in terms of permutations groups, and then many others. It took me a while to handle them all, see all the connections and all the implications. When I now look at them they are much less intimidating and it is much easier to follow certain arguments about them, and also to remind facts about them.
So if you always have such a though time, then either the paper you are reading is a though one, or it might indicate that you are not familiar enough with some basic arguments and ways of thinking in your domain.
Maybe adapt the following strategy, if you have a specific paper. Read it and take notes what is not clear and what is clear to you, and try to think more deeply about selected portions of it. Then put it aside and the next week just study the field as a whole (reading books about the topic, secondary literature, other papers) and then after approximately a week come back to your paper and do the same again, and hopefully it is now easier to read it; work through it again, taking notes, think about it, but then put it aside again for another week and do "general research" again. Do this until you understand the paper. I know this might be time-consuming, especially if you have some deadline, but if not than this might work out well and gives you good overall knowledge in the end.

A: I wanted to post this as a comment but it got too long.  So forgive me for posting it as an answer:
Funny you really remind me of myself when I was younger.  Not to mention my favorite mathematician is Galois.  First off let me say that your  habit of checking details will serve you well.  Many people advance quickly by being fast and loose and they intimidate others but if you hammer them down on details you'll find their skills set so full of holes.  This happens worse the better university you attend, because they push the students to go so fast.  So if I were you I wouldn't give up the habit of checking details.  Just learn how to do both, how to read for higher level content and then read for details.  Maybe take one pass plowing through the details, then another pass higher level, then rinse and repeat.

A: You don't learn carpentry by looking at cabinets.
If your aim is to be able to do mathematics rather than answering prepared exam questions, you are doing the right thing.  There is no royal road to mathematics.  The only access is through the stable and the kitchens.

A: I have the following advice for reading papers:  read them (up to) three times.
The first time through, you do not check that the claims are correct.  You are attempting to get broad structural understanding.  Don't even look at the proofs.  Many details will be left dangling.  This is fine.  This is your first pass.  If you are doing a lot of reading, leave a note to yourself that you have read this paper coarsely.
If there is something in the paper justifying further understanding, read it again.  This time, read through the proofs quickly.  Again, don't check any details.  Just ask yourself: "Is this the sort of argument I have seen before?  Does this structure of proof match the broad structure I got from my first reading?"  If you are doing a lot of reading, or might come back to this paper in the future, leave a note to yourself that you have read this paper.
If there is still something in the paper to justify detailed understanding, read it a third time.  Check every line.  Ask yourself "why should I believe this is true" as often as possible.  If a particular claim needs an additional idea (for you to believe it), record this idea in the margin nearby.  If you are doing a lot of reading, or might come back to this paper in the future, leave a note to yourself that you have read this paper in detail.
You leave notes to yourself because you trust yourself to have applied the appropriate level of skepticism to the things you have read.
There are not enough hours in the day to read everything at the detailed level.  For results that are entirely predictable, you should arrive at that conclusion after one or maybe two readings (and you will have recorded that you believe those results at that level).  Only the results with complexity or surprise should merit a third read.
Is this method perfect?  No.  Does it help allocate time better?  I think so.
How does this apply to textbooks?  You can certainly write in your textbooks, so leaving notes should be no problem.  Clearly, the "big theorems" should be read three (or more) times.  Other results may only need to be believed at the "plausible" (coarse, once read) or "likely" (medium, twice read) level.  Is this ideal?  Probably not, but neither of us is immortal, so some accommodation of finite time must occur.

A: I think yours is the mentality a student should have when learning new material: doubt everything, check every little detail that's left as an exercise, etc. You shouldn't accept things as acts of faith, rather you should keep questioning until one day you look back at those books for reference and say "Oh, right, I remember how this fact was verified", because you tried it yourself!
Having said that, I think that remembering every detail of some proofs is not really necessary most of the times, but the 'big picture' or an idea of a sketch of the proof is: Perhaps a proof uses some nice trick which might be useful later, then you should make sure to learn it thoroughly. Otherwise, if you just know the sketch, a good idea is to sit down and try to fill in the details yourself. Sometimes reading and re-reading does not do enough. That's one of the reason math books have so many exercises (and details of proofs left as exercises too).


text:
Q: Bounded random walk I have a random walk algorithm that I want to implement, but I am getting a recursion depth issue. I am making a list of points that Z particles can be in over the domain $(-L/2,L/2)$. I am using a double For loop that will generate the values for the points of the different particles given this domain. The code is:
    Remove["Global`*"]
    Z = 3;
    NMAX = 3;
    l = 1;
    L = 100;
    x[0, i_] = 0;
    For[i = 0, i <= Z, i++,

    For[n = 1, n <= NMAX, n++,

    If[Abs[x[n - 1, i] + l Cos[2 π RandomReal[]]] >= L/2,
    x[n, i] := x[n, i] = x[n - 1, i] - l Cos[2 π RandomReal[]],
    x[n, i] := x[n, i] = x[n - 1, i] + l Cos[2 π RandomReal[]]]]]

    Table[x[n, i], {n, 0, NMAX}, {i, 0, Z}] // TableForm

$l$ is the uniform step that the particle will take and the If statement makes sure that the x position is assigned such that the value is within the domain. I would like to extend this also to y coordinates but that is something I will tackle after I can work this kink out.
I also started the list of particles (at time $n=0$) at position (0,0). The issue I am running into is that while the position for all (3) particles, starts off at 0 and then the first time step is shown but after that the out put is x[2,i] and x[3,i]. It works for the first time step, but not for any subsequent time steps. The error that I get is:

Recursion depth of 1024 exceeded.

I tried setting the recursion limit to 4000, since I found this somewhere else and it works for some problems, but ...

*

*I am not sure what setting the recursion limit does.

*It didn't work for me.
Any help would be appreciated!

A: Random walks are easy to implement with Mathematica. I think you would find many examples on this site if you were to search on "random walk". To implement the walk you describe, it just as easy to implement the 2D version you are aiming for as the 1D one, so the 2D walk is what I will discuss here.
First. Nested For-loops are not the way to go. I will use NestList which is a commonly used functional looping construct. I will also use recursion to handle the bounds constraint, but in a way the will not lead to uncontrolled recursion.
Second. I will use a divide-and-conquer implementation strategy. I break the problem in three parts.

*

*A function nextPt, which given the current point and the radius of the disk of possible next locations returns the next point of the walk. nextPt uses recursion to implement the boundary constraint.

*A function walk, which given the starting point, the radius of the disk of possible next locations, and the number of steps to be taken returns a list of points comprising the walk.

*A function walkPlot, which given a list made by walk produces a visualization of the walk. The stating point is shown as a red dot and ending point is shown as a blue dot. walkPlot will take additional options which will be passed on to Graphics, so the look of the plot can be modified to suit other needs. (The option handling could certainly be improved, but I thought adding the extra code required would distract from the main point of this answer.)
You may not need walkPlot for your work. You may just need first two functions to generated data for any further processing you have in mind.
With[{w = 10., h = 8.},
  With[{bounds = Rectangle[{-w/2., -h/2.}, {w/2., h/2}]},
    nextPt[ pt_, r_] :=
      Block[{nxt = pt + r {Cos[#], Sin[#]}&[RandomReal[2. π]]},
        If[RegionMember[bounds, nxt], Return[nxt]];
        nextPt[pt, r]];
    walk[start : {_Real, _Real}, r_Real?Positive, steps_Integer?Positive] :=
      NestList[nextPt[#, r] &, start, steps];
    walkPlot[path_, opts : OptionsPattern[]] :=
      Graphics[{
        Line[path],
        Red, Disk[First[path], Scaled[.015]],
        Blue, Disk[Last[path], Scaled[.015]]},
        opts,
        PlotRange -> Transpose[List @@ bounds],
        Frame -> True]]]

Note the following:

*

*RegionMember, a fairly recent addition to Mathematica, is used to test whether or not a candidate point lies within the boundary rectangle.

*The walk function is extremely simple in Mathematica's functional style. It also has much better performance than For.

Now let's run three experiments with the following code.
SeedRandom[2];
Column[Table[walkPlot[walk[{0., 0.}, 2., 150], ImageSize -> Medium], 3]]

Update
I have corrected an error in the function nextPt. The updated version
correctly generates steps of magnitude r.


text:
Q: Execute javascript on my website through linux server (node, socket.io) I have website with games in html5/JS. I want make it looks like there are many users playing to promote it faster. Results of games are presented in real time with websockets socket.io
So im writing bots that are imitating  players on my linux servers, everything is ok, results are in database but most important thing don't work. Displaying live results to other users through javascript. Server of websockets running on node js server so its user JS <--> server JS communication.
I don't know how to bite this problem:

*

*execute somehow website locally through node JS which is responsible for sending live result? (tryed that, node dont undertstand html and JS + HTML is used in process of communication with node JS live results server)

*execute my website with some kind of linux browser emulator with JS (that would be easiest, don't need to use bots then, only couple instances of this browser emulator. Something like this exist?

*Communicate php <--> node socket.io server? (im reading currently about this, maybe someone know < php 5.3 [without namespace] version of software like this?)


text:
Q: How search case insensitive values using Criteria, MongoTemplate and Java? I'm currently doing:
criteria = new Criteria().andOperator(where("car.color").is(car_color),
                                      where("car_size").is(car_size))

How to make this search works for both car_color = BLUE and car_color = blue ?

Update:
This partially works:
where("car.color").regex(car_color, "i"),

But then all values below would be updated:
BLUE
BBLUE
blue
bluee

And I want to update only what is matched in the car_color variable(case insensitive).

A: I think what you want is to pre process your string to be all caps or all lowercase. In java that's done like:
car_color.toLowerCase()
or
car_color.toUpperCase()
Then you know its all in caps or all in lowercase, and can compare the string appropriately

A: The solution for my problem is:
criteria = new Criteria().andOperator(where("car.color").regex("^" + car_color+ "$", "i"),
                                      where("car_size").is(car_size))


text:
Q: Matix Exponential Layer (Custom: Keras in R) I'm trying to make a layer in Keras (R) which (matrix) exponential a layer of shape (d,d).
ie.: Input to layer is a dxd matrix and the output is a dxd matrix which is the (matrix) exponential of the input matrix.
What I've Implemented to Date:
Here's what I've done (its a degree 4 approximation because I'm also not sure how to get the tensorflow matrix exponential command working in Keras):
  # Matrix Exponential
Matrix_Exp<- R6::R6Class("KerasLayer",

                         inherit = KerasLayer,

                         public = list(

                           call = function(x, mask = NULL) {
                             # Initialize Tenor-like Object -> Tensor Objects
                             ord0 = k_eye((k_shape(x)[1]))
                         ord1 = x
                         ord2 = (1/2)*k_dot(x,x) # note x is square so this works
                         ord3 = (1/6)*k_dot(x,ord2)
                         ord4 = (1/24)*k_dot(x,ord3)
                          ord0+ord1+ord2 +ord3+ord4
                           },

                           compute_output_shape = function(input_shape) {
                             c(d,d)
                           }
                         )
)
# Create layer wrapper function
layer_Matrix_Exp <- function(object) {
  create_layer(Matrix_Exp, object)
}

I'm plugging a model with this summary into the custom layer:
Model: "sequential_32"
_________________________________________________________________________________________________________________________________________________________________
Layer (type)                                                            Output Shape                                                    Param #
=================================================================================================================================================================
dense_63 (Dense)                                                        (None, 100)                                                     400
_________________________________________________________________________________________________________________________________________________________________
dense_64 (Dense)                                                        (None, 4)                                                       404
_________________________________________________________________________________________________________________________________________________________________
reshape_10 (Reshape)                                                    (None, 2, 2)                                                    0
=================================================================================================================================================================
Total params: 804
Trainable params: 804
Non-trainable params: 0
_________________________________________________________________________________________________________________________________________________________________

Problem/Error:
But I run into this error when passing layers_NE %>% layer_Matrix_Exp
WARNING:tensorflow:Entity <function wrap_fn.<locals>.fn at 0x7fbdd0cf2b90> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Evaluation error: object 'size' not found.
 Error in py_call_impl(callable, dots$args, dots$keywords) :
  RuntimeError: in converted code:

    /scratch/users/BIM/R/x86_64-redhat-linux-gnu-library/3.6/keras/python/kerastools/layer.py:30 call  *
        return self.r_call(inputs, mask)
    <string>:4 fn

    /scratch/users/BIM/R/x86_64-redhat-linux-gnu-library/3.6/reticulate/python/rpytools/call.py:21 python_function
        raise RuntimeError(res[kErrorKey])

    RuntimeError: Evaluation error: object 'size' not found.

Note:

*

*The problem is coming from the identity part but I don't know how to fix this.

Question:

*

*How to fix error.

*How to replace the order 4 (manual) approximation to the matrix exponential with the keras equivalent to the tensorflow matrix exponential command.

Thanks in advance.


text:
Q: Sending sensor data to a MySQL server with Arduino and Sim900a I am trying to send sensor data to a MySQL server of mine but can't achieve that. I followed several similar examples here in other questions but it isn't working. The Arduino code is given below. The idea is to measure the voltage and current across a load and send it to a MySQL server. TIA.
#include <SoftwareSerial.h>
SoftwareSerial gprsSerial(7, 8);

//variables that imitates actual voltage and current data
float a=random(300.0);
float b=random(2.00);
char  c[10]="B110";

void setup() {
  gprsSerial.begin(19200);
  Serial.begin(19200);
  Serial.println("Config SIM900A...");
  delay(2000);`enter code here`
  Serial.println("Done!...");
  gprsSerial.flush();
  Serial.flush();
  // attach or detach from GPRS service
  gprsSerial.println("AT+CGATT?");
  delay(100);
  toSerial();
  // bearer settings
  gprsSerial.println("AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\"");
  delay(2000);
  toSerial();
  // bearer settings
  gprsSerial.println("AT+SAPBR=3,1,\"APN\",\"my carrier apn here\"");
  delay(2000);
  toSerial();
  // bearer settings
  gprsSerial.println("AT+SAPBR=1,1");
  delay(2000);
  toSerial();
}

void loop() {
  // initialize http service
  gprsSerial.println("AT+HTTPINIT");
  delay(2000);
  toSerial();
  // set http param value
  gprsSerial.println("AT+HTTPPARA=\"URL\",\"http://mocdl.net/api/data/create?voltage="" + a + ""&current="" + b + "" &load_id="" + c + ""\"");
  delay(2000);
  toSerial();
  // set http action type 0 = GET, 1 = POST, 2 = HEAD
  gprsSerial.println("AT+HTTPACTION=0");
  delay(6000);
  toSerial();
  // read server response
  gprsSerial.println("AT+HTTPREAD");
  delay(1000);
  toSerial();
  gprsSerial.println("");
  gprsSerial.println("AT+HTTPTERM");
  toSerial();
  delay(300);
  gprsSerial.println("");
  delay(10000);
}

void toSerial() {
  while(gprsSerial.available()!=0) {
    Serial.write(gprsSerial.read());
  }
}

A: As Panciz said you should set you APN (i think you already know that).
You should also make a small change in your program.
gprsSerial.println("AT+HTTPPARA=\"URL\",\"http://mocdl.net/api/data/create?voltage="" + a + ""&current="" + b + "" &load_id="" + c + ""\"");

The above line wont work as you expected.
So edit the http request line as follows :
 gprsSerial.println("AT+HTTPPARA=\"URL\",\"http://mocdl.net/api/data/create?voltage=%f&current=%f&load_id=%f\"",a,b,c);

A: You must set your APN.
For example in my case I need to add
mySerial.println("AT+SAPBR=3,1,\"APN\",\"internet\"")


text:
Q: Sharing phone contact in Share Contract target terminates app Whenever I try to share a phonebook contact with a target app using Share Contract in WP 8.1, the target application always terminates before the ReportCompleted() method is called.
The contact is extracted using the GetStorageItemsAsync() as it's actually a .VCF file, but before I can direct the user through the target app's flow, the app terminates! The functionality is fine in case any other storage item (say an image) is shared.
Whatsapp(2.12.60 on WP 8.1) also shows the same behavior of terminating abrupty when a contact is shared.
Is this a bug in the OS? If not, how can I make this work?


text:
Q: Classic ASP on IIS7: refusing to send errors to browser on 500 Internal Server Error I have classic ASP running on IIS 7.
Even though I configured the ASP "Debugging Properties" to "Send Errors to Browser = True", the web app REFUSES to send errors to the browser and continues to send a 500 internal server error.

*

*My browser has "Show Friendly HTTP Error Messages" unchecked.

*Failed Request Tracing is installed (not sure if that's related)

*Happens both on web pages loaded locally on the server and remotely

*The App Pool is integrated (not sure if that matters)

Any ideas?

A: Try :
Internet Information Services (IIS) Manager —> Default Web Site —> Click Error Pages properties and select Detail errors

A: I was having the same issue with a Classic ASP app running in a subfolder of a site. I had enabled detailed errors and the 500 was still showing. My resolution was to enable parent paths in the ASP section in IIS for the site as the application was referencing the parent folder using "../":

A: I had this occuring on a Classic ASP application running in a subfolder of a site. The solution was:
IIS > Click into your Site > Click into your Application folder > Error Pages > Edit Feature Settings > set to: Detailed Errors

A: IIS Manager >> double click the ASP icon to open the ASP page. Expand the Debugging Properties node and set Send Errors To Browser to True.

Refer : http://www.chestysoft.com/asp-error-messages.asp

A: If your website is configured to connect to the physical path of the website as a specific user, instaed of using pass-through authentication, you may get this error if there is a permissions error with this user. It may also be necessary to restart the Windows Process Activation Service and then restart IIS.

A: If you are hosting the project in a shared environment then you can use the following snippet to view the errors.
<configuration>
<system.webServer>
    <httpErrors errorMode="Detailed" />
</system.webServer>
<system.web>
    <customErrors mode="Off" />
    <compilation debug="true" />
</system.web>

Refer this URL for complete information http://blogs.iis.net/rickbarber/working-past-500-internal-server-error
Hope it helps someone

A: I had a 500 error with an ASP Classic application I had just installed on a new server (Windows 2019). Every URL on the application returned 500, no matter what. But no errors were being shown in the Windows event log, and despite configuring detailed errors, as mentioned in several the other answers here, no specific error was being displayed in the browser.
The only clue was in the IIS logs, which showed the HTTP status code as 500, and the IIS substatus code as 19. So a 500.19 error.
That led me to
and the specific issue I was having was answered by the second part of this section:
https://learn.microsoft.com/en-us/troubleshoot/iis/http-error-500-19-webpage#hresult-code-0x80070005
which says:

Don't configure the website to use UNC pass-through authentication to
access the remote UNC share. Instead, specify a user account that has
the appropriate permissions to access the remote UNC share.

and (this is the part I needed to do):

Grant the Read permission to the IIS_IUSRS group for the
ApplicationHost.config or Web.config file. To do it, follow these
steps:
In Windows Explorer, locate the folder that contains the
ApplicationHost.config file that is associated with the website, or
locate the virtual directories or the application directories that
contain the Web.config file that is associated with the website.
Note
The Web.config file may not be in the virtual directories or the
application directories in IIS. Even in this situation, you have to
follow these steps.
Right-click the folder that contains the ApplicationHost.config file,
or right-click the virtual or application directories that may contain
the Web.config file.
Select Properties.
Select the Security tab, and then Select Edit.
Select Add.
In the Enter the object names to select box, type
\IIS_IUSRS, select Check Names, and then select OK.
Note
 is a placeholder for the computer name.
Select the Read check box, and then select OK.
In the Properties dialog box for the folder, select OK.
Note
Make sure that the folder properties are inherited by the
ApplicationHost.config and Web.config files so that IIS_IUSRS has the
Read permission for those files.


text:
Q: ScrollView not scrolling at all I can't make a ScrollView properly scrolling. It always cut off the content on the bottom, as if it were a normal LinearLayout.
My code
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true" >

    <LinearLayout android:id="@+id/scroll_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:isScrollContainer="true"
        android:orientation="vertical" >

Of course, I already tried to add / remove the "fillViewport" and "isScrollContainer" properties, and  it did not change anything at all.
This is for ScrollView (VERTICAL ONLY)
HorizontalScrollView must be used for horizontal scrolling.

A: Answer: the ScrollView is not working when used as the root element of an XML layout. It has to be wrapped inside a LinearLayout.
Solution then :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ScrollView android:id="@+id/scroll_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fillViewport="true" >

        <LinearLayout android:id="@+id/scroll_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" >

        </LinearLayout>
    </ScrollView>
</LinearLayout>

A: The selected answer IS NOT CORRECT!
You CAN use ScrollView as the root view, it doesnt work for you because you are missing the padding.
Add something like:
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"

A: remove the android:isScrollContainer in LinearLayout. As per the documentation android:isScrollContainer is used to set the view scrollable. I hope it helps you. Refer this link for definition.

A: Android Studio adds a NestedScrollView to the activity file of some of its templates (e.g. Master-Detail). Having a ScrollView in the fragment file and another one in that fragment's activity file prevents the scroll view from working. Removing the ScrollView in my fragment file and leaving the one in the activity file solved the issue for me.

A: Try this solution, just delay your scroll using post delayed method.
fragment_test.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/rootRelativeLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:fresco="http://schemas.android.com/apk/res-auto">

    <ScrollView
        android:id="@+id/scrollView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="40dp"
        android:fillViewport="true"
        android:scrollbars="none">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            ...
        </RelativeLayout>

    </ScrollView>

</RelativeLayout>

TestFragment.java
...
private ScrollView mScrollView;
...
mScrollView = (ScrollView) mView.findViewById(R.id.scrollView);
mScrollView.setSmoothScrollingEnabled(true);
...
new Handler().postDelayed(new Runnable() {
    @Override
     public void run() {
         if(isAdded()) {
             // Scroll 1000px down
             mScrollView.smoothScrollTo(0, 1000);
         }
     }
}, 150);

This worked for me, hope this helps.

A: Try this,
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:fillViewport="true" >

<LinearLayout android:id="@+id/scroll_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

A: ❌Tried all the above mentioned answers, but still my issue was unsolved.
And after some debugging and changes, my issue got fixed that is the ScrollView is getting scrolled.

*

*We need not to add any parent element to the ScrollView to make it scroll (as mentioned in some of the other answers here).

✔The Fix was for my issue✔

*

*changed the height of the ScrollView to 0dp
android:layout_height="0dp"

*Constrained the Top and Bottom to parent/respective views/elements
app:layout_constraintTop_toBottomOf="@+id/imageView4"
app:layout_constraintBottom_toBottomOf="parent"
The final xml looks like this
<ScrollView
    android:layout_width="match_parent"
    android:layout_height="0dp"
    app:layout_constraintTop_toBottomOf="@+id/imageView4"
    app:layout_constraintBottom_toBottomOf="parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

           <!-- Loong content -->

    </LinearLayout>
</ScrollView>

A: Scroll View as Parent has no issues. I faced such issue when we add padding/margin to the direct child of scrollview. Keep the child of scrollview with just height and width properties, den it will work fine.
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:animateLayoutChanges="true"
        android:fillViewport="true">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:animateLayoutChanges="true"
            android:orientation="vertical">
</LinearLayout>
</ScrollView>

A: I finally figured it out took me literally 5 hours building everything step by step and testing it every step at a time ugh....
Anyway if you have a problem with this i found out that setOntouch listener is messing up your code - at least in my case it was...
i have to figure a way around it, but try to delete your ontouch listener and test your code - it has to work

A: This fixed my problem: I added android:isScrollContainer="true" to a LinearLayout and Removed the ScrollView
Code Before:
    <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">
<ScrollView
    android:id="@+id/scrollViewRecords"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true">

    <LinearLayout
        android:id="@+id/sheepList"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

    </LinearLayout>
</ScrollView>
</LinearLayout>

Code After
    <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:isScrollContainer="true">

    <LinearLayout
        android:id="@+id/sheepList"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

    </LinearLayout>
</LinearLayout>

A: Is there a way to close this question? it is old and currently the answer marked as valid doesn't have sense. The only valid thing regarding ScrollView right now is this:

A view group that allows the view hierarchy placed within it to be scrolled. Scroll view may have only one direct child placed within it. To add multiple views within the scroll view, make the direct child you add a view group, for example LinearLayout, and place additional views within that LinearLayout.
  Never add a RecyclerView or ListView to a scroll view. Doing so results in poor user interface performance and a poor user experience.

Taken from official documentation: https://developer.android.com/reference/android/widget/ScrollView.html

A:     <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fillViewport="true">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">
......
</LinearLayout>
</ScrollView>
</LinearLayout>

A: Looks like you're not using some of the properties and rules.
android:layout_height="0dp"
android:scrollbars="none"
android:fillViewport="true"

Also, after this try to wrap all your scrolling content in Constraint Layout.
<tech.loung.views.SlidingScrollView
android:id="@+id/scrollview_settings"
android:layout_width="match_parent"
android:layout_height="0dp"
android:scrollbars="none"
android:fillViewport="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="@+id/top_layout">

A: In my scenario it worked when I update Linear layout inside the scroll view with Padding=10dp. That's it scroll view Scrolled successfully
<ScrollView
    android:id="@+id/mainScrollview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginTop="?attr/actionBarSize">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/top_layout"
        android:orientation="vertical"
        android:layout_margin="10dp"
        android:padding="10dp">

A: Add:
android:layout_weight="0"

In:
<ScrollView
.

*

*And set it to "0" as long as you don't want to apply a "layout_weight"

A: Wasted an hour with this issue my findings are listed below ,hope will help someone.

*

*You can have ScrollView as root tag

*You can have ScrollView child of any other layouts.

*You can only have single child ScrollView (I prefer LinearLayout)

*I prefer keeping height of scroll view to 0dp

*When your root is ConstraintLayout set layout_constraintBottom_toBottomOf="parent"

*The child view of ScrollView should not have margin or padding.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

<!-- you Custom toolbar or other non scrollable items here -->

   <ScrollView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintTop_toBottomOf="@+id/bpSyncDivider"
        app:layout_constraintBottom_toBottomOf="parent"
        android:background="@color/colorWhite">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">
        <!-- Items to be scrolled here -->

        </LinearLayout>

    </ScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>```


text:
Q: Run Windows Java program in Ubuntu 12.04 without Wine If a Windows program (*.msi) was written in Java, is there a way for me to extract the contents and install it taking advantage of Java's cross-platform capabilities? I'd like to install it bypassing Wine.

A: *

*Install msitools - it is needed to use msiextract
sudo apt-get install msitools

*Extract the MSI file
msiextract TAV.msi

*Go into Program Files/TAV
cd "Program Files/TAV"

*Extract the EXE file
unzip TAV.exe

*Check the MANIFEST.MF
Manifest-Version: 1.0
Class-Path: .:./org/hyperic/sigar/natives/
Created-By: 1.5.0_22 (Oracle Corporation)
Main-Class: tav.TAV

Your main class is tav.TAV

*Start the main class
java tav/TAV

and your app is running, without WINE ;)


text:
Q: When is a hypothesis test appropriate? For example, when would a hypothesis test bed used?

A: That's a fair question and the answer relates to the difference between taking a population census and taking a sample. It depends of how the statistics of 3.1% and 4.5% were obtained. Do you have complete data or were the proportions estimated from a sample of your target population?
If you have complete data, i.e., if you know the total number of people who play basketball in your target population, then there is indeed no purpose in a hypothesis test. You already know the truth.
If the proportions were instead estimated by polling a random collection of people, say by telephone or by a questionaire, then a hypothesis test would be needed in order to confirm that the increase from 3.1% to 4.5% is statistically significant and likely to be representative of the whole population. The null hypothesis in this case would be that the proportion has not changed. As well as conducting a hypothesis test, it would also be useful to attach a "margin of error" to each of the proportions, as is often done for political polls.


text:
Q: Video Upload more than 100MB throwing 404 error I am trying to enable the functionality of video upload up to 190MB. I am using .Net core with Ocelot Gateway. I am able to successfully upload videos up to 190MB locally. But when I try to upload with Ocelot Gateway(on test environment), I am getting a 404 error. We have Cloudflare on the test environment and that is enabled for up to 200MB video upload.
I have applied following changes:
In web.config of web project and gateway project
<system.web>
    <httpRuntime maxRequestLength="220200960" />
</system.web>

<requestLimits maxAllowedContentLength="220200960" />

On API Endpoint:
[RequestSizeLimit(220200960)]
[RequestFormLimits(MultipartBodyLengthLimit = 220200960)]

In web startup.cs
services.Configure<IISServerOptions>(options =>
{
  options.MaxRequestBodySize = int.MaxValue;
});
services.Configure<KestrelServerOptions>(options =>
{
  options.Limits.MaxRequestBodySize = int.MaxValue;
});
services.Configure<FormOptions>(x =>
{
  x.ValueLengthLimit = int.MaxValue;
  x.MultipartBodyLengthLimit = int.MaxValue;
  x.MultipartHeadersLengthLimit = int.MaxValue;
});

I am getting the following warning in Gateway:

Ocelot.Responder.Middleware.ResponderMiddleware[0]
requestId: 0HMFB1RBKJ31C:00000001, previousRequestId: no previous request id, message: Error Code: UnmappableRequestError
Message: Error when parsing incoming request, exception:
System.OutOfMemoryException: Exception of type
'System.OutOfMemoryException' was thrown.
at System.IO.MemoryStream.set_Capacity(Int32 value)
at System.IO.MemoryStream.EnsureCapacity(Int32 value)
at System.IO.MemoryStream.Write(Byte[] buffer, Int32 offset, Int32 count)
at System.IO.MemoryStream.WriteAsync(ReadOnlyMemory`1 buffer, CancellationToken cancellationToken)
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpRequestStream.CopyToAsyncInternal(Stream
destination, CancellationToken cancellationToken)
at Ocelot.Request.Mapper.RequestMapper.ToByteArray(Stream stream)
at Ocelot.Request.Mapper.RequestMapper.MapContent(HttpRequest request)
at Ocelot.Request.Mapper.RequestMapper.Map(HttpRequest request, DownstreamRoute downstreamRoute) errors found in
ResponderMiddleware. Setting error response for request
path:/v1/File/CreateFile, request method: POST

Nothing above helped me. Any help would be appreciated.
Thank you in advance.

A: Looking at your stack trace, it mentions as out of memory exception, which could point towards an issue copying such a large file into memory (if your server has low free memory). Have you verified your server has > 200 MB of free memory at the time of upload?
I also found this post, which sounds like a somewhat similar issue with Ocelot - https://github.com/ThreeMammals/Ocelot/issues/884
Could try setting MaxRequestBodySize to null to see what happens? Although they were not receiving 'out of memory' exception, so could be unrelated.


text:
Q: React Rest API issue I´m new to REST API and on the current project where I can create gallery categories and images inside the gallery I bumped into a problem.
I have multiple objects within the parent array as seen below. Some of them containing image.
[]
  0:
    0: {path: "test", name: "test"}
    1: {path: "puli", image: {…}, name: "puli"}
    2: {path: "animalsg", name: "animalsg"}
    3: {path: "animals", image: {…}, name: "animals"}
    4: {path: "Animals", image: {…}, name: "Animals"}
    5: {path: "sdfsf", name: "sdfsf"}
    6: {path: "viki", name: "viki"}
    7: {path: "pul", image: {…}, name: "pul"}
    8: {path: "testik", name: "testik"}
    __proto__: Object
    length: 1
__proto__: Array(0)

Is there a way to fetch all the name values from each object and also assign it an id?
Can you please help me modify this useEffect for this purpose?
useEffect(() => {
      const tempAlbum = [];
      fetch('http://someapi.xy/gallery')
        .then(response => response.json())
        .then(data => tempAlbum.push('???'));
    }, [])

A: If I understood right, you would want to do something like this
useEffect(() => {
      const tempAlbum = [];
      fetch('http://someapi.xy/gallery')
        .then(response => response.json())
        .then(data => { data[0].forEach(
                           (item,i) => {
                                tempAlbum.push({name: item.name, id: i})
                            })
                       });
         }, [])

About the id, this approach is using the same array index as id, that could work for you unless you need this id to render this array on your React application, in which case using the index is not recommended, so you could use a library like uuid to generate an id on the fly, it's very simple to use and does not require configuration.

A: If what you are trying to do is simply get an tempAlbum to have an array of like [{ name: 'rockers', id: '1234'}, ...] then you can do:
data.flat().forEach((x, idx) => tempAlbum.push({ name: x.name, id: idx }));
That should work for you.


text:
Q: SAT math problem about probability A drawer contains $3$ purple crayons and $5$ red crayons. What is the probability that you select two purple crayons if you reach in the drawer and randomly grab two crayons without replacement?
Answer: $\frac{3}{28}$

A: The answer is: (The probability that the first crayon is purple) $\times$ (The probability that the second crayon is purple assuming that you drew a purple the first time).
That is $$\frac{3}{8} \times \frac{2}{7} = \frac{3}{28}$$

A: First one you reach for it the probability it will be $\color{purple}{purple}$ is $$\color{purple}{\frac{3}{8}}$$
Because you divide the number of purple crayons over the total number of crayons.
Now $7$ crayons are left, and $2$ of them are purple assuimung that you get the first one purple and so the probability of the second one being $\color{purple}{purple}$ is $$\color{purple}{\frac{2}{7}}$$
And now just multiply the two fractions to get your answer as $$\color{purple}{\frac{3}{28}}$$

A: Probability = $\frac{favorable -events}{total -events}$
In this case number of favorable events = $^3C_2$ (select any 2 purple crayons out of the three)
Number of total events = $^8C_2$(select any 2 crayons out of the total 8)


text:
Q: Alfresco compatibility with Existing Oracle DB I have installed Enterprise Version of alfresco and trying to use it with existing Oracle DB schema.
For that I have changed properties in alfresco-global.properties file from PostgreSQL to Oracle.
And I am getting authenticate error while login into alfresco admin.

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.beans.factory.config.PropertyPathFactoryBean#48ff4096' defined in class path resource [alfresco/ibatis/ibatis-context.xml]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dialect' defined in class path resource [alfresco/hibernate-context.xml]: Cannot resolve reference to bean '&sessionFactory' while setting bean property 'localSessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSourceCheck' defined in class path resource [alfresco/core-services-context.xml]: Cannot resolve reference to bean '&sessionFactory' while setting bean property 'localSessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [alfresco/hibernate-context.xml]: Invocation of init method failed; nested exception is org.hibernate.HibernateException: Hibernate Dialect must be explicitly set
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:529)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveInnerBean(BeanDefinitionValueResolver.java:276)
    ... 105 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dialect' defined in class path resource [alfresco/hibernate-context.xml]: Cannot resolve reference to bean '&sessionFactory' while setting bean property 'localSessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSourceCheck' defined in class path resource [alfresco/core-services-context.xml]: Cannot resolve reference to bean '&sessionFactory' while setting bean property 'localSessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [alfresco/hibernate-context.xml]: Invocation of init method failed; nested exception is org.hibernate.HibernateException: Hibernate Dialect must be explicitly set
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:334)


text:
Q: Forgot how to do non-ajax dropdown in MVC I know this sounds silly but i forgot how to code non-ajax.
Specifically:
I am in MVC
I have a dropdown list with languages.
When a language is chosen i want to reload the whole page with the new language.
This all works but I have to manually refresh the page.
I mean I could call window.location.refresh after i return from the action but i feel like i should be able to do a full refresh. Am i suppose to call submit on a form?
I really feel like i am missing osme extremely easy right in front of my face thing.
I have been doing so many partial ajax updates in my life,i lost my plain old post and reload.

A: Yea you have to do a form submit, but whats wrong with window.location.refresh?

A: Normally selecting language for a site is independent of other form submissions, and you can get away with a GET instead of POST. So, in the onchange attribute of your select, you can put:
var lang = ...//get selected language value here
document.location = 'http://mysite.com/' + lang //or whatever your URL scheme is


text:
Q: How to make a div animate in on page load? notice how when you load squareup.com the form on the left animates in. How do you do a css3 animation like that? Is javascript required to add some class unload?
Thanks

A: Pure CSS 3 animation would be the best way to go - since it's clean, simple and easy.
However, older browsers wont support pure CSS 3 animation so you might be best off with jQuery for now (untill more people support CSS 3 animations perhaps).
<script>
$(function(){
      // make a basic fadeIn animation
      $("#divId").fadeIn();
});
</script>

Replace #divId with your div id attribute. Don't forget to display: none; the div.
For jQuery animations simply go to http://api.jquery.com/animate/

A: Actually, after reviewing the source code, that effect appears to be mostly, if not all, CSS3. Here's a snippet of the CSS:
.square-signup-form h1, .square-signup-form .pricing-prop, .square-signup-form p, .square-signup-form .instructions, .square-signup-form .cards-accepted, .cardcase-signup-form h1, .cardcase-signup-form .pricing-prop, .cardcase-signup-form p, .cardcase-signup-form .instructions, .cardcase-signup-form .cards-accepted {
        color: #fff;
        -moz-transition: all 800ms cubic-bezier(0.51, 0.01, 0.37, 0.98);
        -webkit-transition: all 800ms cubic-bezier(0.51, 0.01, 0.37, 0.98);
        -o-transition: all 800ms cubic-bezier(0.51, 0.01, 0.37, 0.98);
        transition: all 800ms cubic-bezier(0.51, 0.01, 0.37, 0.98);
}
.square-scene .square-signup-form {
    -moz-transform: translate(0pt, 0pt);
    opacity: 1;
    z-index: 3;
}
.ie8 .square-scene .square-signup-form {
    display: block;
}

You can view the full CSS at https://d1g145x70srn7h.cloudfront.net/static/db447699c3d01e60cd9b8e1e1c721ce8837f22bd/stylesheets/home.css
Here's a copy that's easier to read: http://pastebin.com/gHTn1YuA


text:
Q: Logging with OmniAuth and Devise RoR 5 I am following the docs from here LINK.
This is Users::OmniAuthCallbacksController facebook method:
def facebook
    # You need to implement the method below in your model (e.g. app/models/user.rb)
    @user = User.from_omniauth(request.env["omniauth.auth"])

    if @user.persisted?
        logger.debug "YES"
        sign_in_and_redirect @user, :event => :authentication #this will throw if @user is not activated
        set_flash_message(:notice, :success, :kind => "Facebook") if is_navigational_format?
    else
        logger.debug "No"
        session["devise.facebook_data"] = request.env["omniauth.auth"]
    end
end

This is part of 'application.html.erb' view

<%=user_signed_in? %>

If I try to login with Facebook it creates new row in users table for this user, it works, but I see user_signed_in? is false.
What I need to do to authenticate with Devise and OmniAuth ?


text:
Q: wpf setting datatable as itemsource get list but isn't visible DataGrid1.ItemsSource = mgr.srcData(0).DefaultView 'returns datatable
DataGrid1 has all the columns hidden but only 2 visibles
Running the application works, appear the rows but doesn't show the values, only blank rows although I can get their values
onclick -> gets value as datarowview and after I get the first element/field ---> Ok tested