text:
Q: Android Instrumented Test Database magically becomes read-only in @Before I have been working through some exercises to learn android.  The sample project I put together runs fine.  But, when I run all of the Instrumented Tests together, the tests for my content provider fail because the database is read-only when deletes are issued to the database.  When I run the test class separately, the tests pass with flying colors. My ContentProvider test looks like so:
public class TestProvider {

public static final String LOG_TAG = TestProvider.class.getSimpleName();

public void deleteAllRecordsFromProvider() {
    InstrumentationRegistry.getTargetContext()
            .getContentResolver().delete(
            WeatherEntry.CONTENT_URI,
            null,
            null
    );
    InstrumentationRegistry.getTargetContext()
            .getContentResolver().delete(
            LocationEntry.CONTENT_URI,
            null,
            null
    );

    Cursor cursor = InstrumentationRegistry.getTargetContext()
            .getContentResolver().query(
            WeatherEntry.CONTENT_URI,
            null,
            null,
            null,
            null
    );
    assertEquals("Error: Records not deleted from Weather table during delete", 0, cursor.getCount());
    cursor.close();

    cursor = InstrumentationRegistry.getTargetContext()
            .getContentResolver().query(
            LocationEntry.CONTENT_URI,
            null,
            null,
            null,
            null
    );
    assertEquals("Error: Records not deleted from Location table during delete", 0, cursor.getCount());
    cursor.close();
}

@Before
public void setUp() throws Exception {
    deleteAllRecordsFromProvider();
}

@After
public void after() {
    InstrumentationRegistry.getTargetContext()
            .getContentResolver()
            .acquireContentProviderClient(WeatherEntry.CONTENT_URI)
            .getLocalContentProvider()
            .shutdown();
}

@Test
public void testProviderRegistry() {
    PackageManager pm = InstrumentationRegistry.getTargetContext().getPackageManager();

    // We define the component name based on the package name from the context and the
    // WeatherProvider class.
    ComponentName componentName = new ComponentName(InstrumentationRegistry.getTargetContext().getPackageName(),
            WeatherProvider.class.getName());
    try {
        // Fetch the provider info using the component name from the PackageManager
        // This throws an exception if the provider isn't registered.
        ProviderInfo providerInfo = pm.getProviderInfo(componentName, 0);

        // Make sure that the registered authority matches the authority from the Contract.
        assertEquals("Error: WeatherProvider registered with authority: " + providerInfo.authority +
                        " instead of authority: " + WeatherContract.CONTENT_AUTHORITY,
                providerInfo.authority, WeatherContract.CONTENT_AUTHORITY);
    } catch (PackageManager.NameNotFoundException e) {
        // I guess the provider isn't registered correctly.
        assertTrue("Error: WeatherProvider not registered at " + InstrumentationRegistry.getTargetContext().getPackageName(),
                false);
    }
}

@Test
public void testGetType() {
    // content://com.example.android.sunshine.app/weather/
    String type = InstrumentationRegistry.getTargetContext()
            .getContentResolver()
            .getType(WeatherEntry.CONTENT_URI);
    // vnd.android.cursor.dir/com.example.android.sunshine.app/weather
    assertEquals("Error: the WeatherEntry CONTENT_URI should return WeatherEntry.CONTENT_TYPE",
            WeatherEntry.CONTENT_TYPE, type);

    String testLocation = "94074";
    // content://com.example.android.sunshine.app/weather/94074
    type = InstrumentationRegistry.getTargetContext().getContentResolver().getType(
            WeatherEntry.buildWeatherLocation(testLocation));
    // vnd.android.cursor.dir/com.example.android.sunshine.app/weather
    assertEquals("Error: the WeatherEntry CONTENT_URI with location should return WeatherEntry.CONTENT_TYPE",
            WeatherEntry.CONTENT_TYPE, type);

    long testDate = 1419120000L; // December 21st, 2014
    // content://com.example.android.sunshine.app/weather/94074/20140612
    type = InstrumentationRegistry.getTargetContext().getContentResolver().getType(
            WeatherEntry.buildWeatherLocationWithDate(testLocation, testDate));
    // vnd.android.cursor.item/com.example.android.sunshine.app/weather/1419120000
    assertEquals("Error: the WeatherEntry CONTENT_URI with location and date should return WeatherEntry.CONTENT_ITEM_TYPE",
            WeatherEntry.CONTENT_ITEM_TYPE, type);

    // content://com.example.android.sunshine.app/location/
    type = InstrumentationRegistry.getTargetContext().getContentResolver().getType(LocationEntry.CONTENT_URI);
    // vnd.android.cursor.dir/com.example.android.sunshine.app/location
    assertEquals("Error: the LocationEntry CONTENT_URI should return LocationEntry.CONTENT_TYPE",
            LocationEntry.CONTENT_TYPE, type);
}

@Test
public void testBasicWeatherQuery() {
    // insert our test records into the database
    WeatherDbHelper dbHelper = new WeatherDbHelper(InstrumentationRegistry.getTargetContext());
    SQLiteDatabase db = dbHelper.getWritableDatabase();

    ContentValues testValues = TestUtilities.createNorthPoleLocationValues();
    long locationRowId = TestUtilities.insertNorthPoleLocationValues(InstrumentationRegistry.getTargetContext());

    // Fantastic.  Now that we have a location, add some weather!
    ContentValues weatherValues = TestUtilities.createWeatherValues(locationRowId);

    long weatherRowId = db.insert(WeatherEntry.TABLE_NAME, null, weatherValues);
    assertTrue("Unable to Insert WeatherEntry into the Database", weatherRowId != -1);

    // Test the basic content provider query
    Cursor weatherCursor = InstrumentationRegistry.getTargetContext().getContentResolver().query(
            WeatherEntry.CONTENT_URI,
            null,
            null,
            null,
            null
    );

    // Make sure we get the correct cursor out of the database
    TestUtilities.validateCursor("testBasicWeatherQuery", weatherCursor, weatherValues);
    weatherCursor.close();
}

@Test
public void testBasicLocationQueries() {
    // insert our test records into the database
    WeatherDbHelper dbHelper = new WeatherDbHelper(InstrumentationRegistry.getTargetContext());
    SQLiteDatabase db = dbHelper.getWritableDatabase();

    ContentValues testValues = TestUtilities.createNorthPoleLocationValues();
    long locationRowId = TestUtilities.insertNorthPoleLocationValues(InstrumentationRegistry.getTargetContext());

    // Test the basic content provider query
    Cursor locationCursor = InstrumentationRegistry.getTargetContext()
            .getContentResolver()
            .query(
            LocationEntry.CONTENT_URI,
            null,
            null,
            null,
            null
    );

    // Make sure we get the correct cursor out of the database
    TestUtilities.validateCursor("testBasicLocationQueries, location query", locationCursor, testValues);

    // Has the NotificationUri been set correctly? --- we can only test this easily against API
    // level 19 or greater because getNotificationUri was added in API level 19.
    if ( Build.VERSION.SDK_INT >= 19 ) {
        assertEquals("Error: Location Query did not properly set NotificationUri",
                locationCursor.getNotificationUri(), LocationEntry.CONTENT_URI);
    }
    locationCursor.close();
}

@Test
public void testUpdateLocation() {
    // Create a new map of values, where column names are the keys
    ContentValues values = TestUtilities.createNorthPoleLocationValues();

    Uri locationUri = InstrumentationRegistry.getTargetContext().getContentResolver().
            insert(LocationEntry.CONTENT_URI, values);
    long locationRowId = ContentUris.parseId(locationUri);

    // Verify we got a row back.
    assertTrue(locationRowId != -1);
    Log.d(LOG_TAG, "New row id: " + locationRowId);

    ContentValues updatedValues = new ContentValues(values);
    updatedValues.put(LocationEntry._ID, locationRowId);
    updatedValues.put(LocationEntry.COLUMN_CITY_NAME, "Santa's Village");

    // Create a cursor with observer to make sure that the content provider is notifying
    // the observers as expected
    Cursor locationCursor = InstrumentationRegistry.getTargetContext().getContentResolver().query(LocationEntry.CONTENT_URI, null, null, null, null);

    TestUtilities.TestContentObserver tco = TestUtilities.getTestContentObserver();
    locationCursor.registerContentObserver(tco);

    int count = InstrumentationRegistry.getTargetContext().getContentResolver().update(
            LocationEntry.CONTENT_URI, updatedValues, LocationEntry._ID + "= ?",
            new String[]{Long.toString(locationRowId)});
    assertEquals(count, 1);

    // Test to make sure our observer is called.  If not, we throw an assertion.
    //
    // Students: If your code is failing here, it means that your content provider
    // isn't calling getContext().getContentResolver().notifyChange(uri, null);
    tco.waitForNotificationOrFail();

    locationCursor.unregisterContentObserver(tco);
    locationCursor.close();

    // A cursor is your primary interface to the query results.
    Cursor cursor = InstrumentationRegistry.getTargetContext().getContentResolver().query(
            LocationEntry.CONTENT_URI,
            null,   // projection
            LocationEntry._ID + " = " + locationRowId,
            null,   // Values for the "where" clause
            null    // sort order
    );

    TestUtilities.validateCursor("testUpdateLocation.  Error validating location entry update.",
            cursor, updatedValues);

    cursor.close();
}

@Test
public void testInsertReadProvider() {
    ContentValues testValues = TestUtilities.createNorthPoleLocationValues();

    // Register a content observer for our insert.  This time, directly with the content resolver
    TestUtilities.TestContentObserver tco = TestUtilities.getTestContentObserver();
    InstrumentationRegistry.getTargetContext().getContentResolver().registerContentObserver(LocationEntry.CONTENT_URI, true, tco);
    Uri locationUri = InstrumentationRegistry.getTargetContext().getContentResolver().insert(LocationEntry.CONTENT_URI, testValues);

    // Did our content observer get called?  Students:  If this fails, your insert location
    // isn't calling getContext().getContentResolver().notifyChange(uri, null);
    tco.waitForNotificationOrFail();
    InstrumentationRegistry.getTargetContext().getContentResolver().unregisterContentObserver(tco);

    long locationRowId = ContentUris.parseId(locationUri);

    // Verify we got a row back.
    assertTrue(locationRowId != -1);

    // Data's inserted.  IN THEORY.  Now pull some out to stare at it and verify it made
    // the round trip.

    // A cursor is your primary interface to the query results.
    Cursor cursor = InstrumentationRegistry.getTargetContext().getContentResolver().query(
            LocationEntry.CONTENT_URI,
            null, // leaving "columns" null just returns all the columns.
            null, // cols for "where" clause
            null, // values for "where" clause
            null  // sort order
    );

    TestUtilities.validateCursor("testInsertReadProvider. Error validating LocationEntry.",
            cursor, testValues);
    cursor.close();

    // Fantastic.  Now that we have a location, add some weather!
    ContentValues weatherValues = TestUtilities.createWeatherValues(locationRowId);
    // The TestContentObserver is a one-shot class
    tco = TestUtilities.getTestContentObserver();

    InstrumentationRegistry.getTargetContext().getContentResolver().registerContentObserver(WeatherEntry.CONTENT_URI, true, tco);

    Uri weatherInsertUri = InstrumentationRegistry.getTargetContext().getContentResolver()
            .insert(WeatherEntry.CONTENT_URI, weatherValues);
    assertTrue(weatherInsertUri != null);

    // Did our content observer get called?  Students:  If this fails, your insert weather
    // in your ContentProvider isn't calling
    // getContext().getContentResolver().notifyChange(uri, null);
    tco.waitForNotificationOrFail();
    InstrumentationRegistry.getTargetContext().getContentResolver().unregisterContentObserver(tco);

    // A cursor is your primary interface to the query results.
    Cursor weatherCursor = InstrumentationRegistry.getTargetContext().getContentResolver().query(
            WeatherEntry.CONTENT_URI,  // Table to Query
            null, // leaving "columns" null just returns all the columns.
            null, // cols for "where" clause
            null, // values for "where" clause
            null // columns to group by
    );

    TestUtilities.validateCursor("testInsertReadProvider. Error validating WeatherEntry insert.",
            weatherCursor, weatherValues);

    // Add the location values in with the weather data so that we can make
    // sure that the join worked and we actually get all the values back
    weatherValues.putAll(testValues);
    weatherCursor.close();
    // Get the joined Weather and Location data
    weatherCursor = InstrumentationRegistry.getTargetContext().getContentResolver().query(
            WeatherEntry.buildWeatherLocation(TestUtilities.TEST_LOCATION),
            null, // leaving "columns" null just returns all the columns.
            null, // cols for "where" clause
            null, // values for "where" clause
            null  // sort order
    );
    TestUtilities.validateCursor("testInsertReadProvider.  Error validating joined Weather and Location Data.",
            weatherCursor, weatherValues);
    weatherCursor.close();
    // Get the joined Weather and Location data with a start date
    weatherCursor = InstrumentationRegistry.getTargetContext().getContentResolver().query(
            WeatherEntry.buildWeatherLocationWithStartDate(
                    TestUtilities.TEST_LOCATION, TestUtilities.TEST_DATE),
            null, // leaving "columns" null just returns all the columns.
            null, // cols for "where" clause
            null, // values for "where" clause
            null  // sort order
    );
    TestUtilities.validateCursor("testInsertReadProvider.  Error validating joined Weather and Location Data with start date.",
            weatherCursor, weatherValues);
    weatherCursor.close();
    // Get the joined Weather data for a specific date
    weatherCursor = InstrumentationRegistry.getTargetContext().getContentResolver().query(
            WeatherEntry.buildWeatherLocationWithDate(TestUtilities.TEST_LOCATION, TestUtilities.TEST_DATE),
            null,
            null,
            null,
            null
    );
    TestUtilities.validateCursor("testInsertReadProvider.  Error validating joined Weather and Location data for a specific date.",
            weatherCursor, weatherValues);
    weatherCursor.close();
}

@Test
public void testDeleteRecords() {
    testInsertReadProvider();

    // Register a content observer for our location delete.
    TestUtilities.TestContentObserver locationObserver = TestUtilities.getTestContentObserver();
    InstrumentationRegistry.getTargetContext().getContentResolver().registerContentObserver(LocationEntry.CONTENT_URI, true, locationObserver);

    // Register a content observer for our weather delete.
    TestUtilities.TestContentObserver weatherObserver = TestUtilities.getTestContentObserver();
    InstrumentationRegistry.getTargetContext().getContentResolver().registerContentObserver(WeatherEntry.CONTENT_URI, true, weatherObserver);

    deleteAllRecordsFromProvider();

    // Students: If either of these fail, you most-likely are not calling the
    // getContext().getContentResolver().notifyChange(uri, null); in the ContentProvider
    // delete.  (only if the insertReadProvider is succeeding)
    locationObserver.waitForNotificationOrFail();
    weatherObserver.waitForNotificationOrFail();

    InstrumentationRegistry.getTargetContext().getContentResolver().unregisterContentObserver(locationObserver);
    InstrumentationRegistry.getTargetContext().getContentResolver().unregisterContentObserver(weatherObserver);
}

static private final int BULK_INSERT_RECORDS_TO_INSERT = 10;

static ContentValues[] createBulkInsertWeatherValues(long locationRowId) {
    long currentTestDate = TestUtilities.TEST_DATE;
    long millisecondsInADay = 1000 * 60 * 60 * 24;
    ContentValues[] returnContentValues = new ContentValues[BULK_INSERT_RECORDS_TO_INSERT];

    for (int i = 0; i < BULK_INSERT_RECORDS_TO_INSERT; i++, currentTestDate += millisecondsInADay) {
        ContentValues weatherValues = new ContentValues();
        weatherValues.put(WeatherContract.WeatherEntry.COLUMN_LOC_KEY, locationRowId);
        weatherValues.put(WeatherContract.WeatherEntry.COLUMN_DATE, currentTestDate);
        weatherValues.put(WeatherContract.WeatherEntry.COLUMN_DEGREES, 1.1);
        weatherValues.put(WeatherContract.WeatherEntry.COLUMN_HUMIDITY, 1.2 + 0.01 * (float) i);
        weatherValues.put(WeatherContract.WeatherEntry.COLUMN_PRESSURE, 1.3 - 0.01 * (float) i);
        weatherValues.put(WeatherContract.WeatherEntry.COLUMN_MAX_TEMP, 75 + i);
        weatherValues.put(WeatherContract.WeatherEntry.COLUMN_MIN_TEMP, 65 - i);
        weatherValues.put(WeatherContract.WeatherEntry.COLUMN_SHORT_DESC, "Asteroids");
        weatherValues.put(WeatherContract.WeatherEntry.COLUMN_WIND_SPEED, 5.5 + 0.2 * (float) i);
        weatherValues.put(WeatherContract.WeatherEntry.COLUMN_WEATHER_ID, 321);
        returnContentValues[i] = weatherValues;
    }
    return returnContentValues;
}

I have one other test that uses the InstrumentationRegistry:
public class TestFetchWeatherTask {
    static final String ADD_LOCATION_SETTING = "Sunnydale, CA";
    static final String ADD_LOCATION_CITY = "Sunnydale";
    static final Double ADD_LOCATION_LAT = 34.425833;
    static final Double ADD_LOCATION_LON = -119.714167;

    @Test
    public void testAddLocation() {
        // start from a clean state
        InstrumentationRegistry.getTargetContext()
                .getContentResolver()
                .delete(WeatherContract.LocationEntry.CONTENT_URI,
                WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + " = ?",
                new String[]{ADD_LOCATION_SETTING});

        FetchWeatherTask fwt = new FetchWeatherTask(InstrumentationRegistry.getTargetContext(), null);
        long locationId = fwt.addLocation(ADD_LOCATION_SETTING, ADD_LOCATION_CITY,
                ADD_LOCATION_LAT, ADD_LOCATION_LON);

        // does addLocation return a valid record ID?
        assertFalse("Error: addLocation returned an invalid ID on insert", locationId == -1);

        // test all this twice
        for ( int i = 0; i < 2; i++ ) {

            // does the ID point to our location?
            Cursor locationCursor = InstrumentationRegistry.getTargetContext()
                    .getContentResolver().query(WeatherContract.LocationEntry.CONTENT_URI,
                    new String[]{
                            WeatherContract.LocationEntry._ID,
                            WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING,
                            WeatherContract.LocationEntry.COLUMN_CITY_NAME,
                            WeatherContract.LocationEntry.COLUMN_COORD_LAT,
                            WeatherContract.LocationEntry.COLUMN_COORD_LONG
                    },
                    WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + " = ?",
                    new String[]{ADD_LOCATION_SETTING},
                    null);

            // these match the indices of the projection
            if (locationCursor.moveToFirst()) {
                assertEquals("Error: the queried value of locationId does not match the returned value" +
                        "from addLocation", locationCursor.getLong(0), locationId);
                assertEquals("Error: the queried value of location setting is incorrect",
                        locationCursor.getString(1), ADD_LOCATION_SETTING);
                assertEquals("Error: the queried value of location city is incorrect",
                        locationCursor.getString(2), ADD_LOCATION_CITY);
                assertEquals("Error: the queried value of latitude is incorrect",
                        Double.valueOf(locationCursor.getDouble(3)), ADD_LOCATION_LAT);
                assertEquals("Error: the queried value of longitude is incorrect",
                        Double.valueOf(locationCursor.getDouble(4)), ADD_LOCATION_LON);
            } else {
                fail("Error: the id you used to query returned an empty cursor");
            }

            // there should be no more records
            assertFalse("Error: there should be only one record returned from a location query",
                    locationCursor.moveToNext());

            // add the location again
            long newLocationId = fwt.addLocation(ADD_LOCATION_SETTING, ADD_LOCATION_CITY,
                    ADD_LOCATION_LAT, ADD_LOCATION_LON);

            assertEquals("Error: inserting a location again should return the same ID",
                    locationId, newLocationId);
            locationCursor.close();
        }
        // reset our state back to normal
        InstrumentationRegistry.getTargetContext()
                .getContentResolver()
                .delete(WeatherContract.LocationEntry.CONTENT_URI,
                WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + " = ?",
                new String[]{ADD_LOCATION_SETTING});

        InstrumentationRegistry.getTargetContext()
                .getContentResolver()
                .acquireContentProviderClient(WeatherContract.LocationEntry.CONTENT_URI)
                .getLocalContentProvider()
                .shutdown();
    }
}

If I comment out this test, the TestProvider class passes.  If I don't, all of the TestProvider tests fail with the same error:

I/TestRunner: android.database.sqlite.SQLiteReadOnlyDatabaseException:
  attempt to write a readonly database (code 1032)

Can anyone help me figure out what is going on with my tests? Why is my database magically becoming read-only?  I have googled around with no luck.

A: To test a ContentProvider you should create a test that extends ProviderTestCase2, add the @RunWith(AndroidJUnit4.class) annotation at the beginning of the test class definition, specify the test runner as AndroidJUnitRunner and annotate every test with @Test.
Then, inject the Context
@Override
protected void setUp() throws Exception {
    setContext(InstrumentationRegistry.getTargetContext());
    super.setUp();
}

and run your tests from Studio.
You can learn more in this lesson.


text:
Q: byobu - remove double bar I love to use the byobu tool to manage multiple ssh sessions. It works extremely well in Ubuntu, but when I manually install it on Amazon Linux (and other distros) it often comes up with two bars rather than a single one as demonstrated in the screenshot below (selected in red):

How can I make it a single bar like the terminal below in Ubuntu?

A: I found that the best solution was to run the following two commands:
sudo yum install tmux -y
byobu-select-backend

Then select the tmux backend instead of screen. This achieves the desired effect.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Appium Test Connection Refused I'm trying to run this simple test on Appium on an android phone that's supposed to open a calculator  application but I keep getting errors.
This is the code I've written :
package appiumTests;

import java.net.MalformedURLException;
import java.net.URL;

import org.openqa.selenium.remote.DesiredCapabilities;

import io.appium.java_client.AppiumDriver;
import io.appium.java_client.MobileElement;

public class CalculatorTest {

static AppiumDriver<MobileElement> driver;

public static void main(String args[]) {

    try {
        openCalculator();
    } catch (Exception e) {

        System.out.println(e.getCause());
        System.out.println(e.getMessage());
        e.printStackTrace();
    }

}

public static void openCalculator() throws Exception {

    DesiredCapabilities cap = new DesiredCapabilities();

    cap.setCapability("devicename", "Galaxy A51");
    cap.setCapability("udid", "R58N4211WGA");
    cap.setCapability("platformName", "Android");
    cap.setCapability("platformVersion", "10");
    cap.setCapability("appPackage", "com.google.android.calculator");
    cap.setCapability("appActivities", "com.android.calculator2.Calculator");

    URL url = new URL("http://127.0.0.1:4723/wd/hub");
    driver = new AppiumDriver<MobileElement>(url, cap);

    System.out.println("APPLICATION STARTED...");

}

}
And these are the errors I'm getting:

A: *

*Make sure your appium server is started with default port (4723)

*udid/deviceName use either of them , preferably not both

*Capability is written wrongb replace with correct one already mentioned one

appActivities
appActivity


text:
Q: Solving the diffusion equation by separation of variables and a series solution I am utterly confused by the following question:

When you use separation of variables, you get
$U=X(x)T(t)$
$\frac{T'}{T}=\nu \frac{X''}{X}$
This solves nicely to an exponential solution for T: $T(t)=C_\lambda e^{\lambda t}$ and using the suggested series solution for X:
$X''-\frac{\lambda}{\nu}X =0$
$\Sigma_{n=0}^\infty (a_{n+2}(n+1)(n+2)-a_n)x^n = 0$
which gives the form for the coefficients
$a_{2n+1}=\frac{(\lambda/\nu)^n a_1}{(2n+1)!}$
$a_{2n}=\frac{(\lambda/\nu)^n a_0}{(2n)!}$
When $\lambda=0$, you get $T=const$ and $X=bx+c$
The full solution is therefore (where I assume $\lambda$ takes on discrete values not yet found
$U(x,t)=bx+c + \Sigma_{\lambda \neq 0} e^{\lambda t}\Sigma_{n=0}^\infty \frac{(\lambda/\nu)^n a_0 x^{2n}}{(2n)!}+\frac{(\lambda/\nu)^n a_1 x^{2n+1}}{(2n+1)!}$
So from this I am very confused. It is impossible, if this form is correct, to have a power of $x^2$ in the initial condition without also having all even powers of x.
Would appreciate a hint, or if someone can see one of my assumptions/steps is incorrect.

A: You've tried to do an eigenvalue expansion but you haven't found the possible eigenvalues! The method goes like this: Suppose that $$T'/T = \nu X''/X = \lambda$$
then what can we deduce about $\lambda$? You should observe that the series solution you've obtained is just $X(x) = a_{0}\cos(\omega x) + a_{1}\sin(\omega x)$, where $\omega^{2} = \lambda / \nu$. Well, one of our boundary conditions is $U(0,t) = 0$ so that surely forces $a_{0}=0$. Then we have to have $U(L,t) = 0$ too. But arbitrary choices of $\lambda$ won't make this happen! You get a constraint on the eigenvalues here, and the general solution will be a linear combination of all possible eigensolutions. This gives you enough freedom to express initial conditions like your given one (but cross that bridge when you come to it).


text:
Q: django-registration create_user() unexpected keyword I am trying to create a custom profile to add additional fields to django-registration. Here is the code I have so far --
in models.py
from django.db import models
from django.contrib.auth.models import User

class Profile(models.Model):
    user = models.ForeignKey(User, unique=True)
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    email = models.CharField(max_length=50)
    password = models.CharField(max_length=50)

and in settings.py
AUTH_PROFILE_MODULE = 'myproject.Profile'
However, I am getting the following error when I try to use create_user(). Here is what happens when I type it into the interpreter --
>>> from django.contrib.auth.models import User
>>> User.objects.create_user(first_name='tom',last_name='smith',email='ts@gmail.com',password='hello')
Traceback (most recent call last):
  File "<console>", line 1, in <module>
TypeError: create_user() got an unexpected keyword argument 'first_name'

What am I missing in order for create_user() to recognize these new columns? Thank you.

A: There are a number of things you're doing wrong here
Firstly, these aren't fields on the User model, they're on the Profile model. So it shouldn't be surprising that the User manager method doesn't recognise them. You'll need to define a User object in the normal way with create_user, then define the Profile instance using that user.
Secondly, create_user doesn't take all the field names as keyword arguments - it only takes username, email and password. Again, you'll need to set the other fields yourself afterwards.
However, I don't understand at all why you've defined these particular fields. They are all available in the built-in User model. In particular, you should definitely not be defining your own password field, unless you also write some code to store the password as a hash rather than as plain text.

A: username, first_name, last_name, email, password = kwargs['username'], kwargs['first_name'], kwargs['last_name'], kwargs['email'], kwargs['password1']
        user = User(username=username, email=email, first_name=first_name, last_name=last_name)
        user.set_password(password)
        user.save()

that's the solution


text:
Q: Unable to get text in firefox browser but working in IE I need to get the text from text Area, I fetching the text using .getText(), it is working in IE but not in Firefox.
Coudld anyone please help me?
I need to do cross browser test execution. Most of the test are failing bcoz of this problem.
Thanks in advance.

A: On Firefox & Chrome, textarea content can be access with
.getAttribute("value")

But I don't know what's happen on IE with this solution.
Hope that helps.


text:
Q: 403 Error: disallowed_useragent I am new to mobile application development, I am developing an ios app. In which I am using google drive to get document files into my app from google account.I did that task and worked fine.But now it is not working now when I try to authenticate it shows 403 Error: disallowed_useragent in my app . I googled regarding that but somethig confusing, I read this  stack overflow question  from that I found google drive has updated,now I donnot know whether I want redo my task or have to update task for signin only to complete it, kindly any one suggest me regarding that
Thanks in advence

A: There is a workaround for this issue after the recent change in Google OAuth policies.
After integrating the Google Sign and enabling Google Drive API, I was able to work with Google Drive API to fetch all drive data. We just have to set the authorizer for GTLServiceDrive which is obtained after Google sign-in.
service.authorizer = user.authentication.fetcherAuthorizer()
Here is the code snippets of Google GIDSignIn, followed by fetching calendar events.
  import GoogleAPIClient
    import GTMOAuth2
    import UIKit
    import GoogleSignIn

    class ViewController: UIViewController, GIDSignInUIDelegate, GIDSignInDelegate {

      private let kApiKey = "AIzaXXXXXXXXXXXXXXXXXXXXXXX"

      // If modifying these scopes, delete your previously saved credentials by
      // resetting the iOS simulator or uninstall the app.
      private let scopes = [kGTLAuthScopeDriveMetadataReadonly]
      private let service = GTLServiceDrive()

      override func viewDidLoad() {
          super.viewDidLoad()

          service.apiKey = kApiKey

          GIDSignIn.sharedInstance().uiDelegate = self
          GIDSignIn.sharedInstance().scopes = scopes
          GIDSignIn.sharedInstance().signIn()
          GIDSignIn.sharedInstance().delegate = self
      }

      func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {

          if user != nil {
               print("\(user)")
               service.authorizer = user.authentication.fetcherAuthorizer()
               loadDriveFiles()
          }
      }

     // Construct a query and get a list of upcoming events from the user calendar
       func loadDriveFiles() {
            //Googly Drive fetch Query
       }

   }

A: After Following Google drive API Quick start, Add these 3 lines of code in   AppDelegate.m  didFinishLaunchingWithOptions as Shown below.. then it works fine ...
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

     NSString *userAgent = @"Mozilla/5.0 (iPhone; CPU iPhone OS 10_3 like Mac OS X) AppleWebKit/603.1.23 (KHTML, like Gecko) Version/10.0 Mobile/14E5239e Safari/602";

     // set default user agent

     NSDictionary *dictionary = [[NSDictionary alloc]initWithObjectsAndKeys:userAgent,@"UserAgent", nil];
     [[NSUserDefaults standardUserDefaults] registerDefaults:(dictionary)];

    return YES;
}

A: Google is changing its Oauth policies, with this it is intended that no native web views initiate Oauth flows, I am working with an iOS app too and having the same problem, you should probably wait for them to update the SDKs and documentation or find an alternate way of authenticating to use the users information.

A: An alternative way is to use the 3rd party CloudRail SDK which can use an external browser for the authentication. This blog post covers exactly the issue you've mentioned.


text:
Q: Can't load mock data while mounting component I have a component that should render a list of mock items. The initial value is an empty array, and I want to load mock data during component render. But it doesn't work correctly - list in component is empty when I try to check it out by printing in console, but Redux Devtools shows that it is not. What am I doing wrong?
Component
import React, { Component } from 'react';
import TagsBlock from './TagsBlock';
import ActionButton from './ActionButton';
import { connect } from 'react-redux';
import { actionLoadCoctails, actionToggleDetail } from '../actions/actionCreators';

class ResultsCoctails extends Component {
    componentDidMount() {
        this.props.actionLoadCoctails();
    }

    list = this.props.loadCoctails.map(({ img, name, tags}, key) => {
        const showDetail = (e) => {
            e.preventDefault();
            this.props.actionToggleDetail();
        }

        return (
            <div
                className="item"
                key={`coctail-${key}`}
            >
                 showDetail(e)}
                >

{name}

                        <TagsBlock tags={tags}></TagsBlock>

        )
    });

    render() {
        return (

                    {this.list}

                <ActionButton txt="morе"></ActionButton>

        )
    }
}

export default connect(state => ({
    loadCoctails: state.loadCoctails
}), { actionLoadCoctails, actionToggleDetail })(ResultsCoctails);

Reducer
import { LOAD_COCTAILS } from '../constants';

const INIT_COCTAILS = [
    {
        img: 'some url',
        name: 'Cocktail Mary',
        tags: ['one', 'two', 'three'],
    },
    {
        img: 'some url',
        name: 'White Russian',
        tags: ['one', 'two', 'three'],
    },
    {
        img: 'some url',
        name: 'Cocktail Mary',
        tags: ['one', 'two', 'three'],
    },
    {
        img: 'some url',
        name: 'White Russian',
        tags: ['one', 'two', 'three'],
    },
    {
        img: 'some url',
        name: 'Cocktail Mary',
        tags: ['one', 'two', 'three'],
    }
];

export const loadCoctails = (state = [], { type }) => {
    switch(type) {
        case LOAD_COCTAILS:
            return {
                ...state, ...INIT_COCTAILS
            }

        default:
            return state;
    }
}

ActionCreator
import {
    LOAD_COCTAILS,
    TOGGLE_DETAIL,
    LOAD_DETAIL
} from '../constants';

export const actionLoadCoctails = () => {
    return {
        type: LOAD_COCTAILS
    }
}

export const actionToggleDetail = () => {
    return {
        type: TOGGLE_DETAIL
    }
};

export const actionLoadDetail = (img, name, tags, deg, txt) => {
    return {
        type: LOAD_DETAIL,
        img,
        name,
        tags,
        deg,
        txt
    }
};

A: The problem is that the map() function can't work with objects - so, we should make an array and do map() with it:
const listArray = Object.values(this.props.loadCoctails);
        const list = listArray.map(({ img, name, tags}, key) => {
        .....


text:
Q: Unable to reset R rownames, rownames(df) returns NULL I am using the ukcars data set in the expsmooth package. I am trying to execute the following code:
decomp <- stl(ukcars, s.window="periodic")
lastyear <- rep(decomp$time.series[110:113,"seasonal"],2)
fc <- fit$mean + lastyear
plot(ukcars,xlim=c(1980,2007))

but I get the error
lastyear <- rep(decomp$time.series[110:113,"seasonal"],2)
Error in `[.default`(decomp$time.series, 110:113, "seasonal") :
subscript out of bounds

This was easy to find out why this is happening, the row index isn't numeric.
df = decomp$time.series
df
      seasonal    trend   remainder
1997 Q1  29.461732 409.5449  -2.7816187
1997 Q2  12.481745 418.2274  10.7778183
1997 Q3 -38.894178 427.0137 -18.5534968
1997 Q4  -3.049312 434.5440  19.2282932

I should be able to fix this taking the current row index and setting it to a new column in the df and resetting the rownames. But I am unable to do this. rownames(df) returns NULL and when doing rownames(df) = 1:nrow(df) I get
Error in `[.default`(df, 110:113, "seasonal") : subscript out of bounds

I also tried ncol(df) but that returns 3
EDIT: including dput(df)
dput(df)
structure(c(29.4617321114283, 12.481744937995, -38.8941781754736,
-3.04931217790218, 29.4617321114283, 12.481744937995, -38.8941781754736,
-3.04931217790218, 29.4617321114283, 12.481744937995, -38.8941781754736,
-3.04931217790218, 29.4617321114283, 12.481744937995, -38.8941781754736,
-3.04931217790218, 29.4617321114283, 12.481744937995, -38.8941781754736,
-3.04931217790218, 29.4617321114283, 12.481744937995, -38.8941781754736,
-3.04931217790218, 29.4617321114283, 12.481744937995, -38.8941781754736,
-3.04931217790218, 29.4617321114283, 12.481744937995, -38.8941781754736,
-3.04931217790218, 29.4617321114283, 409.544886542326, 418.227436805885,
427.01367497542, 434.544018928925, 442.651085971855, 442.447639001895,
437.267648318706, 432.966177328059, 431.539698434268, 439.341038640529,
450.91900577231, 455.122749175224, 444.587943439341, 421.3536533291,
395.452137518301, 375.326317915304, 367.770200274677, 369.335086887743,
380.278749855951, 393.715056976157, 403.779846429226, 409.053577715943,
404.884341815207, 404.446280975672, 407.109838578845, 412.446556196033,
418.085913244093, 418.859041902176, 416.45346591907, 414.103454261138,
409.700294883422, 405.663143500826, 401.068578490248, -2.78161865375392,
10.7778182561204, -18.5534967999465, 19.2282932489768, -9.67081808328351,
13.3026160601095, 5.26252985676808, -15.9688651501567, -0.505430545696072,
-2.89078357852424, -4.23782759683684, 17.3345630026784, 20.2613244492306,
-0.595398267095391, -21.4519593428274, 6.51799426259851, -10.1319323861056,
-9.42183182573785, -5.59457168047692, 6.41425520174482, 16.5134214593455,
-19.2833226539381, 25.8568363602669, -15.5069687977694, -12.2465706902731,
8.35169886597168, 12.0212649313809, -7.06972972427383, -0.45719803049866,
1.61680080086745, 8.24188329205163, -8.57183132292397, 2.26568939832384
), .Dim = c(33L, 3L), .Dimnames = list(c("1", "2", "3", "4",
"5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15",
"16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26",
"27", "28", "29", "30", "31", "32", "33"), c("seasonal", "trend",
"remainder")), .Tsp = c(1997, 2005, 4), class = c("mts", "ts",
"matrix"))


text:
Q: JQuery/Javascript, how do I grab the data-url through multiple 'same' div's?

    <div class="thing id12" data-url="www.aaax.com"

    <div class="thing id23" data-url="www.bcbc.com"

    <div class="thing id34" data-url="www.eeed.com"

    <div class="thing id45" data-url="www.djhn.com"

     .
     .
     .
     .
    <div class="thing id92295" data-url="www.zzzzhn.com"

How would I go about getting the data-url of each of the div thing classes under siteTable?

A: Get all the elements which have the attribute using has attribute selector and iterate over them using each() method.

$('#siteTable div[data-url]').each(function() {
  console.log($(this).data('url'))
  // or
  // console.log(this.dataset.url)
})

  . . . .

A: You can get array of url's using map() and get() methods.

var urls = $('#siteTable > div.thing').map(function() {
  return $(this).data('url')
}).get()

console.log(urls)

A: ES6 one-liner:
Array.from(document.querySelectorAll('#siteTable > .thing')).map(div => div.getAttribute('data-url'))

var urls =
Array.from(document.querySelectorAll('#siteTable > .thing')).map(div => div.getAttribute('data-url'))
console.log(urls)

jQuery one-liner:
$('#siteTable > .thing').map(function() {return $(this).attr('data-url')}).get()

var urls =
$('#siteTable > .thing').map(function() {return $(this).attr('data-url')}).get()
console.log(urls)

A: $("#siteTable .thing").each(function() {
    console.log($(this).attr("data-url");
});

Or in jQuery 1.4.3 or later:
$("#siteTable .thing").each(function() {
    console.log($(this).data("url");
});

A: You can get the childnodes of the div with id siteTable and then for each child get the data-url attribute.


text:
Q: Сетка символов из списка списков в Python (задача списков из книги al sweigart) Есть простая задача из книги "Автоматизация рутинных задач с помощью Python":

Я пытался реализовать решения так:
        ['.', 'O', 'O', '.', '.', '.'],
        ['O', 'O', 'O', 'O', '.', '.'],
        ['O', 'O', 'O', 'O', 'O', '.'],
        ['.', 'O', 'O', 'O', 'O', 'O'],
        ['O', 'O', 'O', 'O', 'O', '.'],
        ['O', 'O', 'O', 'O', '.', '.'],
        ['.', 'O', 'O', '.', '.', '.'],
        ['.', '.', '.', '.', '.', '.']]

for i in range(6):
    print(grid[0][i])             #сначала выбираем строку где хотим писать
    for b in range(0,9):
        # каждый раз в одной строке по 8 раз проходимся каждым значением
        print(grid[b][i], end="")

Некорректен ход выполнения итераций. Сначала печатается 1 символ из "i" строки и только потом идёт вывод всей "i" строки
Но я понимаю, что это некорректный код. В моём представлении надо
как-то результат вывода 2-ого цикла вставить в аргументы print 1-ого цикла, но мне не хватает опыта и представления как это сделать.

Правильно-ли я понимаю структуру кода для решения задачи?
А если правильно, как вставить результат print из 2-ого цикла в аргументы print 1-ого?

A: grid = [['.', '.', '.', '.', '.', '.'],
        ['.', 'O', 'O', '.', '.', '.'],
        ['O', 'O', 'O', 'O', '.', '.'],
        ['O', 'O', 'O', 'O', 'O', '.'],
        ['.', 'O', 'O', 'O', 'O', 'O'],
        ['O', 'O', 'O', 'O', 'O', '.'],
        ['O', 'O', 'O', 'O', '.', '.'],
        ['.', 'O', 'O', '.', '.', '.'],
        ['.', '.', '.', '.', '.', '.']]

for i in range(6):
    for j in range(9):
        print(grid[j][i], end="")
    print()

Вариант с одним циклом:
for i in zip(*grid):
    print(*i, sep = '')

*

*sep задаёт разделитель, который будет вставлен между выводимыми значениями.

*zip объединяет в кортежи элементы из последовательностей переданных в качестве аргументов


text:
Q: Chartboost on iOS: Not able to stop session When you start Chartboost session with:
[chartBoostInstance startSession]

in the appDelegate,the ads start showing.
How do I stop the session if I implement an in-app purchase that removes the ad?
Lejla

A: This link  here claims that-

Use this Chartboost SDK delegate method to prevent interstitials until the second startSession:

- (BOOL)shouldRequestInterstitialsInFirstSession {
        return NO;
    }

A: [cb startSession]; only  Notify the beginning of a user session.not show the adds.you show ads by showInterstitial method
[cb showInterstitial];

so when user made in app purchase then set bool key isPurchase YES in your NSUserDefaults
and check when show ads
if(![userDefaults boolForKey:@"isPurchase"])
        {
             NSLog(@"Enter add start ");

           [[Chartboost sharedChartboost]  showInterstitial];
        }
        [userDefaults synchronize];

    }


text:
Q: MySQL is creating new threads while connection is open I have new MySQL 5.6 installation on Ubuntu 14.04
The problem is that from time to time, while connection to the database is still open, new thread is attached to the connection.
I have an open session and perform select connection_id();
After about 5 min, I am getting new ID.
In the SHOW PROCESSLIST I still see the old connection ID and the new one.
All temporary tables and variables are lost...
I have the same database running on Amazon RDS and have no such issue, when doing the same tests. I have compared all variables and found no significant differences


text:
Q: Can Change the Record Title? Is there a way to change the title of the New record form during onload? Like the example below:

Instead of "New Customer", I want to display "Internal Customer". and it can be changed to another title depending on where the creation was triggered.
Thanks,
dalday

A: No. There is no supported way of changing this for new, unsaved records.
The only supported way is to set the value of the primary field and save the record.

A: No supported way of updating the form title. Form title is usually set with the primary field on the entity.
Unsupported solution:
Updating the heading html element of the form title element updates the form title. But this needs to be done after a certain time out to allow turbo forms to update the form title.
window.setTimeout(function () {
    var formTitle = jQuery("#FormTitle", window.parent.document);
    if (!formTitle || formTitle.length === 0) return;
    var h1Element = formTitle.find('h1');
    if (h1Element || h1Element.length === 0) {
        h1Element.html('Foo Bar');
    }
}, 300);

A: I do not know of any supported way to do this.
   If you are using CRM 2015 with Update 1, then manipulating the html DOM is also not advisable because of the new rendering engine. You can still do so if you really wish to by setting the use Legacy Form to Yes under the CRM System Settings .

A: try this on the Form Load event:
if(Xrm.Page.ui.getFormType()==1)
{
  Xrm.Page.getAttribute("primaryField").setValue('Internal Customer');
}


text:
Q: When listing just a last name would it be "Name, Jr." or "Name Jr"? When listing names by just a last name, which is correct:

*

*Surname, Jr.

*Surname Jr.
I'd like to know if the comma is required in this context or not.

A: This is a bit of a general reference question, but I'll go ahead an answer it here, because the "right" answer seems to be in a state of flux. From Chicago Manual of Style Online:

EDIT: If you are only listing by last name, I think you would omit the suffix altogether.  After all, John Smith, Sr., and John Smith, Jr., and John Smith III all have the same last name: Smith.  John David Jones, the son of John Daniel Jones, is not John Jones, Jr., so both of them would be listed as Jones; I think the Smiths would be listed the same way, although I don't have an authoritative reference to base that on.

A: Your question make no sense. If there are 3 people to be listed then you are proposing:

*

*John Doe Jr would be listed as Doe Jr.

*Jim Doe would be listed as Doe

*Jason Doe Sr. would be Doe Sr.


text:
Q: org.hibernate.ejb.Ejb3Configuration deprecated in hibernate In my web application, I am using Spring-Data and JPA/Hibernate.My senario is I have to create separate schema company wise.so I am taking username,password and companycode while login .Taking company code will help to find out scheme for that company.My database schema will change according to user logged in so in order to do that I have written hibernate interceptor as describe by http://blog.krecan.net/2009/01/24/spring-managed-hibernate-interceptor-in-jpa but since it is using org.hibernate.ejb.Ejb3Configuration which is going to be deprecated so can anyone tell me other alternative way ?

A:
org.hibernate.cfg.Configuration has been deprecated in this release
  and org.hibernate.cfg.AnnotationConfiguration has been deprecated for
  some time now. Both will get removed before 4.0.0 goes Final. We are
  still planning exactly what the replacement for
  org.hibernate.ejb.Ejb3Configuration will look like, but it too has
  been deprecated in the meantime

(the recommended way to build an EntityManagerFactory has always been via javax.persistence.Persistence anyway).
I am referring this blog post


text:
Q: How to use a variable in .html() in an .each() loop when handling Ajax JSON data? I'm not even sure if this is possible...
I'm using the following jquery code to handle some AJAX JSON data, and it works fine...
       data = jQuery.parseJSON(data);

    $('textarea#bec_term_id').html(data.bec_term_newlines_term_id);
    $('textarea#bec_name').html(data.bec_term_newlines_name);
    $('textarea#bec_slug').html(data.bec_term_newlines_slug);
    $('textarea#bec_description').html(data.bec_term_newlines_description);

But I want to dynamically create the above (Reason? because it's just a shortened version of the full code which has an unknown number of possible additional rows).
The method I'm trying to use is:
    data = jQuery.parseJSON(data);

    var columnslist  = [  'term_id', 'name', 'slug', 'description'];  // plus others

    $.each(columnslist, function(index, colname) {
          $('textarea#bec_' + colname ).html(data.'bec_term_newlines_' + colname);
    });

But it doesn't work.
It's this last part (marked') of the  .html(data. ) that is causing the difficulty.
Does anyone know how, if at all, a variable can be used in such a context? And if not, is there any other way to achieve the same end?

A: Use [] to pass a var
$('textarea#bec_' + colname ).html(data['bec_term_newlines_' + colname]);

A: Use square bracket notation
$('textarea#bec_' + colname ).html(data['bec_term_newlines_' + colname]);

A: You can't use strings for accessors like you are doing in JavaScript, but you can use bracket notation:
.html(data['bec_term_newlines_' + colname]);

A: You may also be able interested in the dataType setting of $.ajax.
From the api documentation:

dataType (default: Intelligent Guess (xml, json, script, or html))
Type: String
The type of data that you're expecting back from the server. If none
  is specified, jQuery will try to infer it based on the MIME type of
  the response (an XML MIME type will yield XML, in 1.4 JSON will yield
  a JavaScript object, in 1.4 script will execute the script, and
  anything else will be returned as a string).

You could probably set it to 'json' to avoid that data = jQuery.parseJSON(data); line.


text:
Q: "theta characteristics" on general motives? Yesterday I read in some texts on theta characteristics of algebraic curves, which are structures on their Jacobians... Do you know if someone has thought if such, but more general, things can exist on motives?

A: The existence of theta characteristics on a curve is a refinement of the splitting of its motive. The reference to this is Oliver Ronding's theta characteristics and stable homotopy type paper. The point is that the existence of a theta characteristic on a curve (with a rational point) implies a splitting in the motivic stable  homotopy category $SH$: $X \simeq S^{0,0} \vee J(X) \vee S^{2,1}$
This realizes to the splitting in category of motives, $M(X) \simeq \mathbb{Z} \oplus Jac(X) \oplus \mathbb{Z}(1)[2]$ (which always happens since the motive of an algebraic variety of dimension $d$ with a rational point splits into $\mathbb{Z} \oplus Pic(X) \oplus ?? \oplus Alb(X) \oplus \mathbb{Z}(d)[2d]$). But the splitting in the $SH$ is much finer - for example it implies splitting as a module over the motivic Steenrod algebra.
My guess is that a theta characteristic on a motive should be a structure on its stable motivic homotopy type, as opposed to its motive and it should lead to a splitting of the top cell. Hints of this is given in the Rondings paper: he shows that all you need for this refined splitting is that the Spanier-Whitehead dual of $X$ is of a certain shape (Corollary 5.2).


text:
Q: Django - Switch language setting for template rendering
Possible Duplicate:
Django switching, for a block of code, switch the language so translations are done in one language

Is there an easy way to get Django to switch language for a single template rendering operation?
In my case the user may trigger an event that will require to message a person that is not speaking the same language.
For instance - user is English speaker but invokes an action that messages a Spanish speaking person - thus I need to generate the outgoing content in Spanish language.
I am aware that it is possible by faking the Request and using RequestContext, however I would prefer a shorter/cleaner solution.

A: Are you looking for something like the following:
from django.utils import translation
language_code = 'xx'
template_body = Template(some_text_var)
translation.activate(language_code)
r = template_body.render(context)
translation.deactivate()

For better code reuse, you can refactor this as a context manager.


text:
Q: Entity Framework Core - storing/querying multilingual records in the database efficiently I'm building an application that must support more than one language.
Therefore, some of the records in my database need to have multiple versions for each language.
I will first explain how I currently achieve this: consider an entity called Region which represents a geographical location and simply has a name.
I would design my entities like this:
public class Region
{
    public int Id { get; set; }

    public List<RegionLanguage> Languages { get;set; }
}

public class RegionLanguage
{
    public Region Region { get;set; } // Parent record this language applies to
    public string CultureCode { get; set; } // Will store culture code such as en-US or fr-CA

    // This column/property will be in the language specified by Culturecode
    [StringLength(255)]
    public string Name { get;set; }
}

From a database perspective, this works great because its infinitely scalable to any number of records. However, due to the way Entity Framework Core works, it becomes less scalable.
Using the above structure, I can query a Region and generate a view model based on specific culture information:
var region = _context.Regions.Where(e => e.Id == 34)
                     .Include(e => e.Languages)
                     .FirstOrDefault();

var viewModel = new RegionViewModel
                    {
                         Name = region.Languages.FirstOrDefault(e => e.CultureCode == "en-US")?.Name // en-US would be dynamic based on the user's current language preference
                    }

You can see this becomes inefficient since I have to include ALL language records for the entity I'm fetching, when I actually only need one and then search for the correct language in memory. Of course this becomes even worse when I need to fetch a list of Regions which then has to return a large amount of unnecessary data.
Of course, this is possible using SQL directly simply by adding an extra clause on the join statement:
select *
from Regions
left join RegionLanguage on (RegionLanguage.Region = Regions.Id and RegionLanguage.CultureCode = 'en-US')

However, to my understanding, this is not possible to do natively from Entity Framework Core without using a RawQuery (EF: Include with where clause)
So that begs the question: is there a better way to achieve multilingual records in the database using EF Core? Or should I just continue with my approach and hope that EF Core implements Include filtering by the time my application actually needs it (I'll admit I might be optimizing slightly prematurely, but I'm genuinely curious if there is a better way to achieve this).

A: You can use projection.
var languageRegion = await _context.Regions
.Select(p => new Region
{
     Languages = p.Languages.FirstOrDefault(e => e.CultureCode == "en-US")
}.FirstOrDefaultAsync(e => e.Id == 34);

If regions and languages are not changing frequently you can use caching.

A: You could use a Global Query Filter
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<RegionLanguage>(builder =>
    {
        builder.HasQueryFilter(rl => rl.CultureCode == "en-US");
    });
}


text:
Q: How do I fix "before you can record we need access to your documents folder" in Win 10 Voice Recorder? It looks like I have full control of my Documents folder, so I can't figure out why Voice Recorder wouldn't be able to write to it:

I tried "Reset" option in control panel for this program (seems like I can't uninstall it, that option is disabled).

A: I referenced this reddit thread because A) it's relevant, and B) the suggestions make sense.
Your security looks fine, but for the sake of humoring the OS, change the owner of Documents to "Everyone, and add a usergroup also named "Everyone" with full control.
Since the logical problems with voice recorder not being able to write to documents are solved, I would go to guess that there's a problem with windows' own system files.
Open up command prompt, run these commands, in order, but stop after one throws an error. (Record their output please)

*

*sfc /scannow

*Dism /online /cleanup-image /restorehealth


text:
Q: A few problems with a sentence (a tale from circa 1930) Reading an The Epiphany of Death by Clark Ashton Smith, I have a problem with the following sentences (because of the context, I pasted also the preceding sentence):

My memory is not what it was, and there are certain lacunae for which
my readers must contrive to forgive me. The only wonder is, that my
powers of recollection have survived at all, beneath the hideous
burden they have had to bear; for, in a more than metaphoric sense, I
have been as one condemned to carry with him, at all times and in all
places, the loathsome incubi of things long dead and corrupt.

The first thing I am not sure of is the "I have been as one condemned". Can the "as" be omitted?
My other problem is "carry with" - it does not seem to be the usual usage, does still mean "carry him with me", as in "still present whenever I go"?
But who is "him"? I thought it refers to the incubus, but as there is the plural, incubi, I do not think so.

A: As one condemned = like a person condemned. Him refers to this metaphorical person, condemned always to carry painful memories with him.

A: Let's look at the context:

in a more than metaphoric sense, I have been as one condemned to carry with him the loathsome incubi of things long dead and corrupt.

(for simplicity I've omitted the parenthetic statement "at all times and in all places")
The prefix for the statement in question is that it is more than a metaphor. So it is a metaphor, but perhaps with some elements having a literal parallel.
A simile, which is a type of metaphor, always uses "as" or "like" when drawing a comparison. The writer isn't saying he has literally been condemned to carry dead and corrupt things, but that he is like (or "as") a man who has. The use of the fantasy creatures "incubi" to describe unpleasant things makes it more obviously metaphorical.
Without the wider context I am guessing, but perhaps the literal aspects of this metaphor (what makes it more than metaphorical) relate to him actually carrying things?

A: Good on you for including the context! It turns out to be important to aid in our understanding of this complex construction. However, with a bit of attention to detail, understanding this is not that difficult.
First, in the opening sentence, consider that the author is asking us, the readers, for our attention and understanding, and setting up what is to follow. Then, with the phrase "in a more than metaphoric sense", the author is alerting us that some comparison is about to happen (or has already happened). And, indeed, that is what we immediately find, starting with "as one", where one is used as a gender-neutral pronoun, which is the subject of the following phrase (a metaphor, or simile)1. So let's look at that phrase by itself:

As one condemned to carry with him, at all times and in all places, the loathsome incubi of things long dead and corrupt.

Since everything in that phrase defines and modifies the subject of the phrase (i.e. the one, or person), the meaning of the following phrase should now be clear. This person is condemned, but not generically so. This person is "condemned to carry with him" incubi (Latin plural of incubus). A bit like Prometheus, the man is condemned to a never-ending task. And so, the author is comparing himself, or more accurately his 'powers of recollection' with their 'hideous burden', to a man condemned to a never-ending task of carrying with him pain, evil, and horror in the form of nightmares2 of, or demons consisting of, dead and corrupt things.
1Somewhat archaically, the author uses him to refer back to one later in the phrase. Gender neutrality was less of a "thing" historically, and using one, a gender-neutral pronoun, was more common, with usage falling off in the 20th century. By the latter half of the 20th century, such usage was considered effete. However, with gender-neutrality gaining importance in the beginning of the 21st century, usage of gender-neutral pronouns has increased.
2Since this is an older bit of writing, going with a more archaic sense of incubus (nightmares) makes more sense, if one is unfamiliar with the word.


text:
Q: JQuery Sortable that scrolls I have two jquery sortables that connect to each other (code below).
$('#da_favourites_sortable').sortable({
    connectWith:  '#da_available_sortable',
    handle:   'img.da_icon_handle',
    revert:  true
});

$('#da_available_sortable').sortable({
    connectWith:  '#da_favourites_sortable',
    handle:   'img.da_icon_handle',
    revert:  true
});

What I would like to do is make one of them a scrolling panel (#da_available_sortable) so that I can have multiple "pages" of sortable element that I can move between the panels.
I can't seem to find away to do this that doesn't cause me to have to split the "available" panel into multiple li's. This is obviously not going to work when I want to drag elements into the "multiple page" sortable as each li would end up having to be a separate sortable.
I would like the #da_available_sortable sortable to show 10 elements at a time as two rows of five.
Has anybody done this before that can show me the way forward?
Thanks

A: It's quite hard to understand what you're trying to achieve. Are you looking for something like this?
http://jsbin.com/ekinog/8
In head:

In body:

Lorem

Ipsum

Dolor

Sit

Amet

Consectetur

Adipiscing

Elit


text:
Q: How can I sum a group of a custom calculated field in SQL? I have many shopper records who have a unique ID, there will be instances where a shopper with the same ID exists and I would like to sum up their shoppable_rated score and only return 1 result of the total sum of shoppable_rated for those IDs, so there will be no duplicate rows for the ID and their total score will be added up. Please can you advise how I would change my query? I got a little stuck trying to use HAVING and couldn't figure it out.
Many thanks!
SELECT
    id,
    shoppable,
    day,
    case when shoppable in ('Good','Very Good','Amazing') then 1 else 0 end as shoppable_rated
FROM
    shoppers
WHERE
    shoppable != 'Unknown'
GROUP BY
    id
ORDER BY
    shoppable_rated DESC;

Example of my data:
id, shoppable, day, shoppable_rated
1, Good, 26, 1
2, Very Good, 14, 1
3, Not Great, 3, 0
1, Bad, 16, 0
3, Amazing, 30, 1

A: First, remove all the unaggregated columns that are not needed in the result set.
Second, use an aggregation function:
SELECT id,
       SUM(case when shoppable in ('Good','Very Good','Amazing') then 1 else 0 end) as shoppable_rated
FROM shoppers
WHERE shoppable <> 'Unknown'
GROUP BY id
ORDER BY shoppable_rated DESC;

If you need the data by id and day, then include both columns in both the SELECT and the GROUP BY:
SELECT id, day,
       SUM(case when shoppable in ('Good','Very Good','Amazing') then 1 else 0 end) as shoppable_rated
FROM shoppers
WHERE shoppable <> 'Unknown'
GROUP BY id, day
ORDER BY shoppable_rated DESC;


text:
Q: Sharepoint 2013 - Generate URL to take you to specific VIEW I have a sharepoint list for which (using infopath) I have developed two form "views", one for standard user access, and one that has more fields/info, for one of the workflow process role admins.
For certain automated workflow emails, I would like to have a link that takes them directly to the list item "in the selected form view" (either general user, or the admin form).
How might I construct such a URL for insertion into emails, depending upon recipients role in the workflow?
Thanks for any help!

A: Infopath supports query strings where the form is hosted on a page via an infopath web part. See this blog post for details, but the summary is that you'll have the infopath web part connected to a query string filter web part. You'll then need a rule to go to the appropriate screen based on the incoming value.

A: Not sure my comment showed up that well, above.  Here is the construction to build the URL to go to a specific (infopath generated) form, and open the form, with the specific list line item:
https://my.sharepoint.com/teams/mysite/mysubsite/Lists/mylist%20name/EditForm.aspx?DefaultView=Contract_Finalization&ID=34
Of course, I have to insert the ID.  Contract_Finalization is the name of my form


text:
Q: How to make a grid that will acomodate my JTable and the rest of my components? I create this JTable that should be next to my other component of my panel, but after setting it's size and its position it only reduce the size of the actual list but not where is contained, ditto for the Label, which doesn't have to be that big.
  public void addComponentToPane(Container pane) {
    TabEst est = new TabEst();
    JTabbedPane tabbedPane = new JTabbedPane();

JTable tabla = new JTable(data, columnas);
tabla.setSize(100, 200);
tabla.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
tabla.setDragEnabled(false);
tabla.setBounds(15, 15, 15, 15);

    JLabel listado = new JLabel("Listado Oficial");

    listado.setLocation(5, 10);
    JPanel card1 = new JPanel() {
        //Dimensions of the Panel
        @Override
        public Dimension getPreferredSize() {
            Dimension size = super.getPreferredSize();
            size.width += 250;
            return size;
        }
    };
    card1.setLayout(new GridLayout(2, 2));
    card1.setBorder(BorderFactory.createEmptyBorder(100, 100, 100, 100));
    card1.add(listado, BorderLayout.NORTH);
    card1.add(new JScrollPane(tabla), BorderLayout.WEST);
    est.addComponentToPane(card1);

Here's what it looks like now.

Here's how I'd like it to look.


text:
Q: MP4 container parsing: What is 'Alias Data Handler' for? I have an mp4 file which I am parsing with this demuxer lib. I stumbled upon a bug when trying to identify a track type. MP4 container keeps this info in hdlr box. In the docs and in the lib there are only two options 'vide' or 'soun',but in this case I am getting 'alis'.
While debugging the lib to see how I get this value I noticed that the parser hits 'hdlr' twice: first time setting 'vide' for the only video track in the file, and second time overwriting with 'alis'.
I have loaded the video into MP4 Explorer GUI app and here is what I see:

Indeed,there is second hdlr box there,which doesn't exist in other mp4 files I tried to parse. My questions are:

*

*What is this token for?

*When is it inserted into mp4?

*Can I just discard 'alis' when encountering one during the parsing?

A: From some research...
(1) What is this token for?
The alis atom is for listing a file alias (or shortcut) to an external resource/URL (eg: a stored file).
(2) When is it inserted into mp4?
An alias atom is usually found in QuickTime MOV files (though it's not illegal to be placed inside an MP4). This "file alias" is something QuickTime player would have responded to (such as for example launching a web page URL during playback).
This other Answer shows a link with a guidance on the data structure of this atom.
(3) Can I just discard alis when encountering one during the (miniMP4) parsing?
There's no other choice, the miniMP4 library does not even have code for handling alis data.
Yes you can safely skip it. It is not mandatory for playback.
PS:
I wonder if your MP4 is possibly a renamed MOV file?
(Both formats use same structure, but sometimes there is MP4-specific contents).


text:
Q: How to run a shell script on every request? I want to run a shell script every time my nginx server receives any HTTP request. Any simple ways to do this?

A: You can execute a shell script via Lua code from the nginx.conf file to achieve this. You need to have the HttpLuaModule to be able to do this.
Here's an example to do this.
location /my-website {
  content_by_lua_block {
    os.execute("/bin/myShellScript.sh")
  }
}

A: I found the following information online at this address: https://www.ruby-forum.com/topic/2960191
This does expect that you have fcgiwrap installed on the machine. It is really as simple as:
sudo apt-get install fcgiwrap

Example script (Must be executable)
#!/bin/sh
# -*- coding: utf-8 -*-
NAME=`"cpuinfo"`
echo "Content-type:text/html\r\n"
echo ""
echo "<title>$NAME</title>"
echo '<meta name="description" content="'$NAME'">'
echo '<meta name="keywords" content="'$NAME'">'
echo '<meta http-equiv="Content-type"
content="text/html;charset=UTF-8">'
echo '<meta name="ROBOTS" content="noindex">'
echo "
"
date
echo "\nuname -a"
uname -a
echo "\ncpuinfo"
cat /proc/cpuinfo
echo "
"

Also using this as an include file, not restricted to only shell
scripts.
location ~ (\.cgi|\.py|\.sh|\.pl|\.lua)$ {
    gzip off;
    root /var/www/$server_name;
    autoindex on;
    fastcgi_pass unix:/var/run/fcgiwrap.socket;
    include /etc/nginx/fastcgi_params;
    fastcgi_param DOCUMENT_ROOT /var/www/$server_name;
    fastcgi_param SCRIPT_FILENAME /var/www/$server_name$fastcgi_script_name;
}

I found it extremely helpful for what I am working on, I hope it help you out with your RaspberryPI project.

A: *

*Install OpenResty (OpenResty is just an enhanced version of Nginx by means of addon modules ) Refer https://openresty.org/en/getting-started.html  for this

*Configure aws cli on the instance

*Write a shell script which download a file from specified S3 bucket

*Do the required changes in nginx.conf file

*Restart the nginx server

I have tested the http request using curl and file gets download in /tmp directory of respective instance:
curl -I http://localhost:8080/

OutPut:
curl -I http://localhost:8080/
HTTP/1.1 200 OK
Server: openresty/1.13.6.2
Date: Tue, 14 Aug 2018 07:34:49 GMT
Content-Type: text/plain
Connection: keep-alive

Content of nginx.conf file:
worker_processes  1;
error_log logs/error.log;
events {
    worker_connections 1024;
}
http {
    server {
        listen 8080;
        location / {
           default_type text/html;
           content_by_lua '
                ngx.say("
hello, world
")
           ';
        }

        location / {
            content_by_lua_block{
            os.execute("sh /tmp/s3.sh")
            }
        }

    }
}

A: If you prefer full control in Python:

*

*Create /opt/httpbot.py:

#!/usr/bin/env python3
from http.server import HTTPServer, BaseHTTPRequestHandler
import subprocess

class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        self._handle()

    def do_POST(self):
        self._handle()

    def _handle(self):
        try:
            self.log_message("command: %s", self.path)
            if self.path == '/foo':
                subprocess.run(
                    "cd /opt/bar && GIT_SSH_COMMAND='ssh -i .ssh/id_rsa' git pull",
                    shell=True,
                )
        finally:
            self.send_response(200)
            self.send_header("content-type", "application/json")
            self.end_headers()
            self.wfile.write('{"ok": true}\r\n'.encode())

if __name__ == "__main__":
    HTTPServer(("127.0.0.1", 4242), Handler).serve_forever()

*

*No concurrency/parallelism here, so httpbot runs one command at a time, no conflicts.

*Run apt install supervisor

*Create /etc/supervisor/conf.d/httpbot.conf:

[program:httpbot]
environment=PYTHONUNBUFFERED="TRUE"
directory=/opt
command=/opt/httpbot.py
autorestart=true
redirect_stderr=true
stdout_logfile=/var/log/httpbot.log
stdout_logfile_maxbytes=1MB
stdout_logfile_backups=10

*

*Add to your nginx server:

    location /foo {
        proxy_pass http://127.0.0.1:4242/foo;
    }

*

*Run:

chmod u+x /opt/httpbot.py

service supervisor status
# If stopped:
service supervisor start

supervisorctl status
# If httpbot is not running:
supervisorctl update

curl https://example.com/foo
# Should return {"ok": true}

tail /var/log/httpbot.log
# Should show `command: /foo` and the output of shell script

A: You can also use the nginx mirror module and poxy_pass it to a web script that runs whatever, in my case I just added this to my main site location {...
mirror /mirror;
mirror_request_body off;

and then a new location called mirror that I had run a php script that executed whatever...
location = /mirror {
    internal;
    proxy_pass http://localhost/run_script.php;
    proxy_pass_request_body off;
    proxy_set_header Content-Length "";
    proxy_set_header X-Original-URI $request_uri;
}

https://nginx.org/en/docs/http/ngx_http_mirror_module.html

A: You can use nginx's perl module which is usually part of a repo and can be easily installed. Sample to call system curl command:
   location /mint {
       perl '
            sub {
               my $r = shift;
               $r->send_http_header("text/html");
               $r->print(`curl -X POST --data \'{"method":"evm_mine"}\' localhost:7545`);
               return OK;
            }
       ';
}


text:
Q: PostgreSQL unique index for a specific set of values Let's say there is a table AVATARS and among other columns it has user_id (foreign key to users table) and state where state can be any value from 0 to 6. I want to create a constraint so that user can have only 2 avatars, where one has state = 0 and the other has any state != 0. I wonder if it's possible to implement with a unique index? Or I am gonna have to add some boolean column?

A: You could use a unique index with an expression:
CREATE UNIQUE INDEX avatars_userid_state_0_idx ON avatars(user_id,(state<>0));

(or state = 0, the end result is the same).

A: You can do this using filtered unique indexes.
For one value with state = 0:
create unique index unq_avatars_user_state0
    on avatars(user_id, state)
    where state = 0;

For one value with state <> 0:
create unique index unq_avatars_user_state0
    on avatars(user_id, state)
    where state <> 0;

Note:  these do not guarantee that such values exist, just that there is at most one of each them.


text:
Q: SQLite Exists Database I want to display all the data from my database created in DB Browser, but I get these errors. I cannot find a solution. Please help me, this is very important to my project. Maybe there's a typo mistake.

05-27 13:54:22.584 32610-32610/com.example.andre.nutridian E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.andre.nutridian, PID: 32610
    java.lang.RuntimeException: Unable to resume activity {com.example.andre.nutridian/com.example.andre.nutridian.Main2Activity}: java.lang.ClassCastException: android.widget.LinearLayout cannot be cast to android.support.v7.widget.ActionBarContainer
        at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3353)
        at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3384)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2574)
        at android.app.ActivityThread.access$900(ActivityThread.java:150)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1399)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:168)
        at android.app.ActivityThread.main(ActivityThread.java:5885)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:687)
     Caused by: java.lang.ClassCastException: android.widget.LinearLayout cannot be cast to android.support.v7.widget.ActionBarContainer
        at android.support.v7.app.WindowDecorActionBar.init(WindowDecorActionBar.java:201)
        at android.support.v7.app.WindowDecorActionBar.<init>(WindowDecorActionBar.java:172)
        at android.support.v7.app.AppCompatDelegateImplV9.initWindowDecorActionBar(AppCompatDelegateImplV9.java:182)
        at android.support.v7.app.AppCompatDelegateImplBase.getSupportActionBar(AppCompatDelegateImplBase.java:145)
        at android.support.v7.app.AppCompatDelegateImplV9.onPostResume(AppCompatDelegateImplV9.java:267)
        at android.support.v7.app.AppCompatActivity.onPostResume(AppCompatActivity.java:172)
        at android.app.Activity.performResume(Activity.java:6362)
        at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3336)
        at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3384)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2574)
        at android.app.ActivityThread.access$900(ActivityThread.java:150)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1399)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:168)
        at android.app.ActivityThread.main(ActivityThread.java:5885)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:687)

My classes are DBHelper:

public class DbHelper extends SQLiteOpenHelper {

    private static String DB_PATH="";
    private static String DB_NAME="test.db";
    private SQLiteDatabase mDataBase;
    private Context mContext=null;

    public DbHelper(Context context) {
        super(context, DB_NAME, null, 1);
        if(Build.VERSION.SDK_INT>=16)
            DB_PATH=context.getApplicationInfo().dataDir+"/databases/";
        else
            DB_PATH="/data/data/"+context.getPackageName()+"/databases/";

        mContext=context;
    }

    @Override
    public synchronized void close() {
        if(mDataBase!=null)
            mDataBase.close();
        super.close();
    }

    private boolean checkDataBase() {
        SQLiteDatabase tempDB = null;
        try {
            String path = DB_PATH + DB_NAME;
        tempDB = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READWRITE);

    }catch(Exception ex){}
        if(tempDB!=null)
            tempDB.close();
        return tempDB!=null?true:false;
    }

    public void copyDataBase() {
        try {
            InputStream myInput = mContext.getAssets().open(DB_NAME);
            String outputFileName=DB_PATH+DB_NAME;
            OutputStream myOutput=new FileOutputStream(outputFileName);

            byte [] buffer=new byte[1024];
            int length;
            while((length=myInput.read(buffer))>0){
                myOutput.write(buffer,0,length);
            }

            myOutput.flush();
            myOutput.close();
            myInput.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void openDataBase(){
        String path=DB_PATH+DB_NAME;
        mDataBase=SQLiteDatabase.openDatabase(path,null,SQLiteDatabase.OPEN_READWRITE);
    }

    public void createDataBase(){
        boolean isDBExist=checkDataBase();
        if(isDBExist)
        {

        }

        else{
            this.getReadableDatabase();
            try{
                copyDataBase();
            }catch(Exception ex){}
        }
    }

    public List<Aliment> getAllAlim(){
        List<Aliment> temp=new ArrayList<Aliment>();
        SQLiteDatabase db= this.getWritableDatabase();
        Cursor c;
        try {
            c = db.rawQuery("SELECT * FROM Aliment", null);
            if (c == null) return null;

            c.moveToFirst();
            do {
                Aliment aliment = new Aliment(c.getString(c.getColumnIndex("aliment")), c.getString(c.getColumnIndex("calorii")), c.getString(c.getColumnIndex("cantitate")));
                temp.add(aliment);
            } while (c.moveToNext());
            c.close();
        }
        catch(Exception e) {
        }
        db.close();
        return temp;

        }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {

    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }
}

The MainActivity is:

public class Main2Activity extends AppCompatActivity {

    List<Aliment> lstAlim=new ArrayList<Aliment>();
    DbHelper dbHelper;
    Button btnAfiseazaLista;
    LinearLayout container;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        btnAfiseazaLista=(Button) findViewById(R.id.btnAfiseazaLista);
        container=(LinearLayout)findViewById(R.id.container);

        dbHelper=new DbHelper(getApplicationContext());
        dbHelper.createDataBase();

        btnAfiseazaLista.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                lstAlim=dbHelper.getAllAlim();
                for(Aliment aliment:lstAlim){
                    LayoutInflater inflater=(LayoutInflater)getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    View addView=inflater.inflate(R.layout.row,null);
                    TextView txtAliment=(TextView)addView.findViewById(R.id.txtAliment);
                    TextView txtCalorii=(TextView)addView.findViewById(R.id.txtCalorii);
                    TextView txtCantitate=(TextView)addView.findViewById(R.id.txtCantitate);

                    txtAliment.setText(aliment.getAliment());
                    txtCalorii.setText(aliment.getCalorii());
                    txtCantitate.setText(aliment.getCantitate());

                    container.addView(addView);
                }
            }
        });
    }
}

These 2 are the classes I use, the Logcat says in these 2 classes are the problems. I am new to this and I need a little guidance to resolve my errors. Please help me in any way. Thank you in advance

A: The issue has nothing to do with your SQLite Database.
Caused by: java.lang.ClassCastException: android.widget.LinearLayout cannot be cast to android.support.v7.widget.ActionBarContainer

The issue is that you are declaring a LinearLayout but it's not a LinearLayout.
Make sure that R.id.container is actually a LinearLayout In your xml layout.
Try changing:
container=(LinearLayout)findViewById(R.id.container);

To:
container=(LinearLayout)findViewById(R.id.action_bar_container);


text:
Q: What happens to file timestamps when performing git merge When I do a git merge, is it standard behavior that git sets a new timestamp on all merged files? So the original timestamp of a file only exists on the original branch where the file was modified/created?

A: As phd mentioned in a comment, Git (mostly) does not use or care about timestamps on files.
Git does keep a timestamp per commit.  More precisely, it keeps two: an author timestamp and a committer timestamp.  But this has no effect on the file timestamps at all.  Instead, Git leaves those up to the underlying operating system.  If Git must update a file, it simply does so—writes to the file—and lets the OS change the file's modifcation-timestamp to "now" as a side effect.  If Git must read a file, it simply does so, and lets the OS change the file's access-timestamp to "now" as a side effect.  The timestamp most people mostly care about is the modification time.1
Hence, git merge touches a file in the work-tree, updating its time-stamp to "now", if and only if it needs to write on the file as a result of the merge.  So the question really boils down to "why did Git need to write on the file in order to merge it?"  The answer to that appears in your comments: the modification is because of altered line endings.
Merge works by finding a common merge base commit.  This merge base commit is where the history from your current (HEAD) commit joins up with the history from the commit you are merging.  Git then runs two git diffs, one from the merge base to your commit—this finds out "what you changed" for --ours—and one from the merge base to the other commit, to find out what they changed for --theirs.  The merge action, the verb form of "to merge", then consists of combining these two sets of changes.2
If one set of changes is "change line endings", and this touches at least one line in every file, it makes sense that every file would be altered by the merge process.  But note that Git can modify line endings on its own, through core.autocrlf and/or .gitattributes settings.  The git merge code has a special case inside it, controlled by the merge.renormalize configuration setting, or by the -X renormalize or -X no-renormalize command-line options.  Full use of this is beyond the scope of this answer, but the point of the renormalize flag is specifically to allow this kind of merge to work without having to touch every line.

1There are up to four total time-stamps per file, depending on the OS and file system: the "access time", called st_atime in a struct stat; the "modification time", st_mtime; a "change" time, st_ctime, and a "birth" time—the time the file was created—called st_birthtime or st_birthtimespec.  The modification time and change time are similar, but not the same: for instance, changing the mode of a file, to add or remove the execute bit, changes the st_ctime but not the st_mtime.  This mode-change is a change to information about the file that does not change the contents of the file.  Most OSes also let users set the access and modification times arbitrarily, using a utime or utimes family of system calls; updating these times sets the ctime to "now".
2Eventually, after the combining, Git normally goes on to make a merge commit—the adjective or even noun form of "merge", since "a merge commit" is often abbreviated to just "a merge".  A merge, or a merge commit, is a commit with a forked history: it points back not just to the earlier HEAD commit, but also to their commit, the one that was the source of --theirs, during the merge.  This merge commit serves to join up the two histories, and hence affects every future merge, since the two histories now join up at that point, rather than at some earlier point.  In other words, this merge-as-a-noun creates a new merge base for future merges.


text:
Q: Continued fraction approximation Let $\theta\in\Bbb{R}_{\gt0}$.
A) Prove that the convergents for the continued fraction expansion of $\theta$ give us better and better rational approximations to $\theta$.
B) Suppose $\theta\notin \Bbb{Q}$. Prove that the convergents $a_n/b_n$ from the continued fraction expansion of $\theta$ form an alternating series of better and better rational approximations to $\theta$: $$\frac{a_1}{b_1}\lt\frac{a_3}{b_3}\lt...\lt\theta\lt...\lt\frac{a_4}{b_4}\lt\frac{a_2}{b_2}$$
I feel if I could do A then B probably follows somehow, and logically it makes sense, but no idea how to prove either!


text:
Q: How to measure distance covered across patches in NetLogo I have a model setup in NetLogo where the simulation space is a GIS map with a 20 km radius that I constructed.
The max xcor and ycor are set to 20 and min xcor and ycor -20. This gives a torus of 41 x 41.
I have my agents at the centre of the map at patch 0 0 and want the maximum distance they can cover as the 20 km i.e. the extent of the GIS map.
ask turtles [
set heading 360
fd 1 ]

Am I right in saying if I iterate this code 20 times they'll be at the centre of the last patch (xcor 0 ycor 20) which isn't quite 20 km?
If that's right, how do I code it up so the agents move the appropriate distance. I feel like I'm trying to square a circle here.
I should say I can add the following line to get a patch scale that comes out at about 975.6
set patch-scale (item 1 gis:world-envelope - item 0 gis:world-envelope ) / world-width

If I multiply the patch scale by the world width I get 40000 which looks right given the radius of the circle is 20 km.
Thanks

A: globals [km]

to test
  ca
  let extent 40 ;desired world-width, in kilometers
  set km (world-width / extent)
  crt 1 [set heading 360]
  ask turtle 0 [fd (20 * km)]
end


text:
Q: ExodusException: write not in progress I'm having a bit of trouble with Xodus VFS, and the application is throwing this error:
jetbrains.exodus.ExodusException: write not in progress
    at jetbrains.exodus.log.Log.ensureWriter(Log.kt:700)
    at jetbrains.exodus.log.Log.writeContinuously(Log.kt:827)
    at jetbrains.exodus.log.Log.write(Log.kt:519)
    at jetbrains.exodus.tree.patricia.MutableNode.save(MutableNode.java:324)
    at jetbrains.exodus.tree.patricia.PatriciaTreeMutable.save(PatriciaTreeMutable.java:258)
    at jetbrains.exodus.env.MetaTreeImpl.saveTree(MetaTreeImpl.java:167)
    at jetbrains.exodus.env.ReadWriteTransaction.doCommit(ReadWriteTransaction.java:248)
    at jetbrains.exodus.env.EnvironmentImpl.flushTransaction(EnvironmentImpl.java:662)
    at jetbrains.exodus.env.ReadWriteTransaction.flush(ReadWriteTransaction.java:109)
    at jetbrains.exodus.env.EnvironmentImpl.executeInTransaction(EnvironmentImpl.java:1039)
    at jetbrains.exodus.env.EnvironmentImpl.executeInTransaction(EnvironmentImpl.java:261)
    at com.backend.repository.jee.JeeXodusVFSRepository.put(JeeXodusVFSRepository.java:97)

Here's the complete code:
public com.backend.model.File put(
      String appId, String namespace, String name, InputStream is) {
    final com.backend.model.File[] createdFile = {null};
    final Environment env = manager.getEnvironment(xodusRoot, appId);
    final VirtualFileSystem vfs = manager.getVirtualFileSystem(env);
    env.executeInTransaction(
        new TransactionalExecutable() {
          @Override
          public void execute(@NotNull final Transaction txn) {
            final File file = vfs.openFile(txn, name, true);
            DataOutputStream output = new DataOutputStream(vfs.writeFile(txn, file));
            try {
              output.write(ByteStreams.toByteArray(is));
            } catch (IOException e) {
              e.printStackTrace();
            }
            createdFile[0] = new com.backend.model.File();
            createdFile[0].setDescriptor(file.getDescriptor());
            createdFile[0].setName(name);
            createdFile[0].setCreated(file.getCreated());
            createdFile[0].setModified(file.getLastModified());
          }
        });
    // vfs.shutdown();
    // env.close();
    return createdFile[0];
  }

What could be wrong in the code?
UPDATE
@Override
  public Environment getEnvironment(String xodusRoot, String instance) {
    Environment environment = environmentMap.get(xodusRoot + instance);
    if (environment == null) {
      EnvironmentConfig config = new EnvironmentConfig();
      //config.setLogDataReaderWriterProvider("jetbrains.exodus.log.replication.S3DataReaderWriterProvider");
      //config.setLogCacheShared(false);
      Environment env = Environments.newInstance(xodusRoot + instance, config);
      environmentMap.put(xodusRoot + instance, env);
    }
    Environment e = environmentMap.get(xodusRoot + instance);
    return e;
  }


text:
Q: How to pass one data array per model input in multimodal deep autoencoder? i'm working on a deep multimodal autoencoder for dimensionality reduction and i'm following this code (https://wizardforcel.gitbooks.io/deep-learning-keras-tensorflow/8.2%20Multi-Modal%20Networks.html)
from keras.layers import Dense, Input
from keras.models import Model
from keras.layers.merge import concatenate

left_input = Input(shape=(784, ), name='left_input')
left_branch = Dense(32, input_dim=784, name='left_branch')(left_input)

right_input = Input(shape=(784,), name='right_input')
right_branch = Dense(32, input_dim=784, name='right_branch')(right_input)

x = concatenate([left_branch, right_branch])
predictions = Dense(10, activation='softmax', name='main_output')(x)

model = Model(inputs=[left_input, right_input], outputs=predictions)
model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])
model.fit([input_data_1, input_data_2], targets)

What i would like to know is how to reconstruct the original data? and what are the input_data_1 and input_data_2 passed in model.fit? and how to pass one data array per model input?


text:
Q: GeoCoding using JSON.NET and the NuGet Googlemapsapi library I'm playing around with the Google Maps .NET API available from NuGet, and have gotten stuck on the Geocoding part where queries come in.
In the following code, I'm trying to pass an address to the API and return a Location with the matching latitude and longitude
public Location GeoCode(string address)
{
    GoogleMapsApi.Entities.Geocoding.Request.GeocodingRequest geoRequest = new GeocodingRequest();

    geoRequest.Address = address;

    GoogleMapsApi.Entities.Geocoding.Response.GeocodingResponse geoResponse = GoogleMapsApi.GoogleMaps.Geocode.Query(geoRequest);

    GoogleMapsApi.Entities.Geocoding.Response.Result geoResult = geoResponse.Results.OfType<?> (?)

    return geoResult.Geometry.Location;
}

I realize this is very specific, and I'm happy to expand on the question for a more general application, if someone will enlighten me

A: GeocodingResponse.Results is an IEnumerable<Result>.  So you just need to do .First() to get the first Result from it.
 var geoResult = geoResponse.Results.First();

Note that this will throw an exception if there is no first result.  You will need to handle this case in your code.


text:
Q: How can I manage promise and map objects? I am working on a project in which data in my database is something like this:

I'm not getting what wrong am I doing! here is my
FetchList.js
import { useState } from "react";

const FetchList = async()=>{

    const[data, setData] =  useState()
    const response = await fetch('https://__firebase__url__');

    if (!response.ok) {
        throw new Error("Something went wrong");
      }

      let responseData = await response.json();
      const loadedHospitals = [];
      for (const key in responseData){
        loadedHospitals.push({
          key: responseData[key].key,
          Name: responseData[key].Name,
          Email: responseData[key].Email,
          Contact_no: responseData[key].Contact_no,
          img: responseData[key].img,
        });
      }
      setData(loadedHospitals);
      const hospitals = data.map(hospital => {
        console.log(hospital);
       });
return data;
}
export default  FetchList;

I want to pass the entire result in an array to ListHospital.js and then map it with Card component.
import Card from "../UI/Card";
import FetchList from "./FetchList";
import { useState, useEffect } from "react";

const ListHospitals = () => {
    const [data, setData] = useState();

    useEffect(() => {
        FetchList().then(data => setData(data));
    }, []);

    return data.map((item)=><Card>{item}</Card>);
}

export default ListHospitals;

Error:

TypeError: Cannot read properties of undefined (reading 'map')

A: I think you need to write  const [data, setData] = useState(); as  const [data, setData] = useState([]); first. as fetch list is an async function so it will take some time to fetch your data hence it is giving you an error. You can only use map on arrays and during the initial render the data variable is undefined.

A: Fetching query at the higher level like App.js solved my problem.
Like :-
function App() {
  const [ data, setData ] = useState([]);

  const fetching = async () => {
    const response = await fetch("_____url___");
    const responseData = await response.json();
    let loadedItem = [];
    for (const key in responseData) {
        loadedItem.push(responseData[key]);
    }
    console.log(loadedItem);
}
fetching();
  return (
    <>

Hey

    </>
  );
}

export default App;


text:
Q: Velocity of a viscous fluid through a tube When a viscous liquid flows through a tube in a laminar flow, why is its velocity highest at the center?
I understand the concept of shear viscosity and why the liquid in contact with moving plate has highest velocity. That's because of viscosity itself. But, I cannot understand how it explains liquid flow in a tube or whether it explains at all.

A:
When a viscous liquid flows through a tube in a laminar flow,why is its velocity highest at the center?

Because the boundary condition is that it's zero at the walls?  Does that answer your confusion?  It shouldn't seem surprising that the point furthest from the walls (the center) is the highest velocity, considering that the fluid exactly at the wall is at exactly zero velocity.
I believe it's the Hagen-Poiseuille equation that handles the specifics.  With laminar flow, we're talking about equations that are 100% solvable algebraically.  That solution is:
$$
    v = - \frac{1}{4 \eta} \frac{\Delta P}{\Delta x} (R^2 - r^2) $$
This equation uses $r$ for distance from the center.  When that is zero, you're at the center-line, and that above expression has the highest value.  You can go look up the exact steps for how to get this expression from the fluid momentum equation itself, which is more-or-less a statement of the definition of viscosity.


text:
Q: Reference a value objects parent entity object in RavenDb I've been playing with RavenDB recently and there is something that is annoying me a little.
I have an entity object with a series of value objects, e.g.
class Foo
{
   IList<Bar> Bars { get; set; }
}

There are a number of times when I want to pass an object of type Bar into a method/class but at some point want to reference back to the parent entity. In the world of NHibernate that's really easy if I configure it with a 1..* relationship, e.g.
class Bar
{
   Foo Foo { get; set; }
}

However RavenDb doesn't really like that which results in me having to create methods like:
void DoSomething(Foo foo, Bar bar)
{
   Console.WriteLine(foo);
   Console.WriteLine(bar);
}

rather than
void DoSomething(Bar bar)
{
   Console.WriteLine(bar.Foo);
   Console.WriteLine(bar);
}

Is there any way to achieve this with RavenDb?
I realise that RavenDb (And document databases in general) promote a different way of thinking about dealing with entities, if this is just a case of me being spending too long in the relational/normalised world could anyone explain how I should be structuring my code in a more document db way?

A: You can certainly do that:
class Bar
{
   Foo Foo { get; set; }
}

You just need to ensure that you set:
documentStore.Conventions.CustomizeJsonSerializer =
      serializer => serializer.ReferenceLoopHandling = ReferenceLoopHandling.Serialize;