text:
Q: Contradicting a definition of a norm of a subcape of a convex set Task
Show that
$$\rho(x) = (\sqrt{|\xi_{1}|}+\sqrt{|\xi_{2}|})^2$$
does not define a norm on the vector space of all ordered pairs
$x = (\xi_1> \xi_2)$, ... of real numbers
Attempt
First lets say that $X$ is vector space
My Idea is that we could have convex set
$$M = \{x \in X | \lVert x\rVert \leq 1 \} \subset A \subset X$$
We can show that A is a convex set by simply
Let $x_{1}, x_{2} \in B(0;1)$
$$\lVert \lambda x_{1} + (1-\lambda) x_{2} \rVert \leq \lvert \lambda \rvert \lVert x_{1} \rVert + \lvert 1-\lambda \rvert \lVert x_{2} \rVert$$
And from here we could check that the statement is valid for the max value $x=1$
$$\lvert \lambda \rvert \lVert x_{1} \rVert + \lvert 1-\lambda \rvert \lVert x_{2} \rVert \leq \lambda + 1-\lambda = 1$$
Question:
We prove that the statement is correct because it's valid even in it's limit conditions?
Real task
We could assign
$$P = \{ x \in X | \rho (x) = 1 \} \subset B(0;1)$$
Now we have a subspace of a norm convex vector space, we should disapprove some of it's norm axioms, the 1st 2 are obviously true:
$$\lVert x \rVert \geq 0$$
$$\lVert x \rVert =  0 \iff x = (0,0)$$
Got stuck in
Maybe, I have to contradict something in the other 2 axioms but don't see how. It's obvious that $P$ is not a convex set.
Question: Can you explain me how could I prove this statement?
Answer:
Let $\alpha=0.5$
$$\lVert (1,0)\rVert=\lVert (0,-1)\rVert=1$$
$$∥λx_1+(1−λ)x_2∥= \lvert 0.5 \rvert \lVert [(1, 0) + (0, -1)] \rVert = 0.5 \lVert [(1, -1)] \rVert = 2 ≤|λ|∥x_1∥+|1−λ|∥x_2∥ = 1$$

A: Note that the unit ball defined by $\rho$ is not convex. Indeed $\rho((1,0)) = \rho((0,-1)) =1$, but $$\rho(\frac 12 (1,0)+\frac 12  (0,-1)) = 2>1$$
Hence $\rho$ is not a norm.


text:
Q: Is production completely lost when losing a wonder race? A central theme in Civilization is the race to build wonders. World wonders can only be built by one civilization.
In previous Civilization games and civ-like games there were various consolation prizes for beginning to build a wonder and someone beating you to it.  I think in Civ 5, half of the extra production was converted to money. In some previous games I think the production could be used on other buildings.
In Civ 6, though, it's not clear if a player receives any benefit from starting to build a wonder and failing to complete it before another civ does.
Is there any consolation price, like extra gold, when losing a wonder race?

A: The other answers are no longer correct, as of Gathering Storm (and possibly before).
When failing to complete a wonder in time, you will now receive a notification; it will indicate exactly how much production was "awarded" to the city in question:

"You were not able to complete the world wonder Statue of Liberty in time. However 918 Production has been salvaged from the attempt and was awarded to the city of Texcoco.

The next production you select in the city will be reduced in price by the value of the wonder; and given how expensive wonders are, it is likely to become "free." (Notably, no production can take less than one turn; so it's hugely wasteful to select a cheap unit or something immediately after being refunded for a Wonder; the best options are probably other wonders, high-tech buildings, or Armies/Armadas.)
For instance, after clicking the notification above, here's the production interface in the named city:

Note my city's production, ~90/turn; and the cost of the Helicopter Corps, 1350, taking only 3 turns to produce.

A: I've noticed production carrying over when losing a wonder race.  I don't think 100% of the hammers carry over, but I've noticed that a building that would have taken 3-4 turns took 1 turn after losing a wonder race.

A: Every single thread, whether it be a steam, 2K, or reddit discussion all point to 1 of 2 things in the end regarding this topic.
1st is what Raven Dreamer mentioned, you do in fact have a road built underneath the wonder tile.
2nd is that you get nothing back from losing out on a wonder, no gold, no hammers, nada. Since there is already more of a challenge getting wonders, because of location/tile requirements to place them, there are not as many wonder races as before. That makes some sense as there is actually less risk at going for wonders, albeit no reward if you are beaten out.
You can see wonders being built in other nations if you look around at their tiles. And if you have a high enough diplomatic visibility level with other nations you will be notified when they begin clearing lands for new wonders.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there any way to message on whatsapp without opening the application I've been searching for the solution to send the message on whatsapp from the Application or via REST-APIs without opening it.
As I have mentioned below the code will validate for the Whatsapp-type installed in device and then it will send it to user but in this case it launch the whatsapp.
private void launchWhatsapp(String msg) {
        try {
            boolean installed2 = obj.appInstalledOrNot("com.whatsapp.w4b");
            if (installed2) try {

                Intent sendIntent = new Intent("android.intent.action.MAIN");
                sendIntent.setAction(Intent.ACTION_VIEW);
                sendIntent.setPackage("com.whatsapp.w4b");
                String url = "https://api.whatsapp.com/send?" +
                        "phone=" + PhoneNumberUtils.stripSeparators(Cust_Phone_Code + " " + getIntent().getStringExtra("Cust_Mob")) +
                        "&text=" + msg;
                sendIntent.setData(Uri.parse(url));
                if (sendIntent.resolveActivity(this.getPackageManager()) != null) {
                    startActivityForResult(sendIntent, 104);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            else {
                boolean installed = obj.appInstalledOrNot("com.whatsapp");
                if (installed) {
                    Intent sendIntent = new Intent("android.intent.action.MAIN");
                    sendIntent.setAction(Intent.ACTION_VIEW);
                    sendIntent.setPackage("com.whatsapp");
                    String url = "https://api.whatsapp.com/send?" +
                            "phone=" + PhoneNumberUtils.stripSeparators(Cust_Phone_Code + " " + getIntent().getStringExtra("Cust_Mob")) +
                            "&text=" + msg;
                    sendIntent.setData(Uri.parse(url));
                    if (sendIntent.resolveActivity(this.getPackageManager()) != null) {
                        startActivityForResult(sendIntent, 104);
                    }
                } else {

                    Toast.makeText(InvoiceReport.this, "Whatsapp not available", Toast.LENGTH_SHORT).show();
                }
            }

        } catch (Exception e) {
            //Log.e("Error", "ERROR_OPEN_MESSANGER"+e.toString());
        }
    }

I am expecting if anyone click on the browser on send message then this redirect to whatsapp application.


text:
Q: Comparing time complexities Let's say we have an algorithm that goes through a list of n numbers twice and counts the number of the ones above 50 in one run and the ones below 50 in the other run and stores these in two variables.
If we change it to do the same in one run by incrementing not just one but either of the variables in each step, do we change time complexity of the algorithm? Do we consider the new one faster?
I know it will require less steps but not exactly sure about time complexity notation.
EDIT:
Pseudocode 1:
for (i = 0; i < TOTAL_NUMBERS; i++) {
    if (numbers[i] >= 50) {
        greaterThan50++;
    }
}

for (i = 0; i < TOTAL_NUMBERS; i++) {
     if (numbers[i] < 50) {
        lessThan50++;
    }
}

Pseudocode 2:
for (i = 0; i < TOTAL_NUMBERS; i++) {
    if (numbers[i] >= 50) {
        greaterThan50++;
    }
    else {
        lessThan50++;
    }
}

A: Something is simple if you can obtain the same result but with smallest expression posible. So in this case if you combine the update of the two counters in the same loop the algorithm will need less CPU cycles to be executed. You can also save time in the number validation cause you can just make one if / else statement to do what you need.
A pseudocode could look like this:
for (i = 0; i < TOTAL_NUMBERS; i++) {
    if (numbers[i] >= 50) {
        greaterThan50 ++;
    }
    else {
        lessThan50 ++;
    }
}

If you want to exclude the numbers that are equal 50 you can do something like:
for (int i = 0; i < TOTAL_NUMBERS; i++) {
    if (numbers[i] > 50) {
        greaterThan50 ++;
    }
    else if (numbers[i] < 50) {
        lessThan50 ++;
    }
}

As you might notice in this last example you are doing an extra validation so it will take an extra step, but this algorithm will still be much faster than looping through the list twice (and also simpler since it requires less lines of code and makes the code more readable and easy to understand).
I hope this helps with your question :)

A: Big O notation is a general statement for how a measurement (execution time in your case) changes as input grows.  The first takes twice as long to execute, but both versions execution times grow linearly with regard to input size, so they're both O(n) algorithms.
more reading here: http://en.wikipedia.org/wiki/Big_O_notation


text:
Q: Как в woordpress интегрировать контент из header и footer? Мне надо интегрировать контент, находящийся в шапке и подвале сайта, на ВП.
С интеграцией страниц у меня всё получилось. Выполнял её с помощью Advanced Custom Fields по следующему алгоритму:

*

*файл разметки делал шаблоном,

*в админке создавал Страницу и подключал её к соответствующему шаблону (в разделе "Атрибуты страницы"),

*в ACF создавал поля, подключал их в файле шаблона .php, потом на Странице заполнял эти поля.

Будет ли корректно всё это сделать и на header.php и footer.php? То есть сделать шаблоны из них и т.д.?
Или есть какие-то другие варианты связывания Страницы и .php-файла?
Наверняка вариантов решений много. Что это за варианты? Среди них есть вариант с использованием Advanced Custom Fields?

A: обычно использую настройки темы или customizer для настроек футера и хедера. Можете использовать и ACF, но нужно делать общие настройки для всех страниц.

A: Header и Footer подключаются своими функциями
get_header();
get_footer();

поля из ACF работают везде, но может потребоваться передать в функцию get_field($fieldname,post_id) ID страницы вторым параметром


text:
Q: Inserting ASM.JS code into vanilla javascript Just a simple question, can I include a section of asm.js code in a set of normal javascript, as a function or otherwise, similar to how I can put ASM code into a C program for areas that need special optimization?

A: Yes. Use the
"use asm";

prologue directive on top of the function block (i.e. function or file) that is asm. Full example:
function MyAsmModule() {
    "use asm";
    // module body
}

See http://asmjs.org/spec/latest/#introduction for more information


text:
Q: IF function and nested function Please help with this formula
=if(C27>=16000,16M,if(C27,=16999,16M,if(c27>=17000,17M,if(C27<=17999,17M,if(C27>=18000,18M,if(C27<=18999,18M,if(C27>=19000,19M)))))))

A: =INT(C27/1000)&"M"

You may say I have to fix your formula and spot its obvious syntax error. No, I say you have to do it this way, and you always have to look for some neat, simple and deductive alternative before abandoning to the ugly, error-prone and difficult-to-maintain nested IFs.
And indeed, such alternative exists most of the time.
p.s. by the way why is it M and not K? may be you have a multiplicative unit implicitly in your data, well...

A: You have a type-o near 16999.
Try this:
=if(C27>=16000,16M,if(C27>=16999,16M,if(c27>=17000,17M,if(C27<=17999,17M,if(C27>=18000,18M,if(C27<=18999,18M,if(C27>=19000,19M)))))))

A: =if(C27>=16000,16M,if(C27 ,= 16999,16M,if(c27>=17000,17M,if(C27<=17999,17M,if(C27>=18000,18M,if(C27<=18999,18M,if(C27>=19000,19M)))))))

the character before 16999 shows the wrong syntax, perhaps it's like this
=if(C27>=16000,16M,if(C27<=16999,16M,if(c27>=17000,17M,if(C27<=17999,17M,if(C27>=18000,18M,if(C27<=18999,18M,if(C27>=19000,19M)))))))


text:
Q: Android: Check If Selected Database .db File Is Valid In my app, I can replace current database with another file selected by the user.
I just want a way to check if the file the user selected is a valid database file.
I let the user select a file like this:
    private fun selectDbFile() {
    val intent: Intent
    val selectIntent = Intent(Intent.ACTION_GET_CONTENT).apply {
        addCategory(Intent.CATEGORY_OPENABLE)
        type = "*/*"
    }
    intent = Intent.createChooser(selectIntent, "Choose a file")
    intentLauncher.launch(intent)
}

and the intentLauncher is defined like this:
    private var intentLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
    if (result.resultCode == Activity.RESULT_OK) {
        val data: Intent? = result.data
        val uri = data?.data
        uri?.let{
            UtilityKt.replaceCurrentDb(requireContext(), uri) {
                showSuccessAlert()
            }
        }
    }
}

The method that replaces the old db file with a new one is like this:
    fun replaceCurrentDb(context: Context, newDbUri: Uri?, completion: () -> Unit) {
    newDbUri?.let {  newUri ->
        GlobalScope.launch(Dispatchers.IO) {
            // Do background work
            try {
                val currentDb = context.getDatabasePath(MenuSQLiteHelper.DATABASE_NAME)
                if (currentDb.exists()) {
                    val src = context.contentResolver.openInputStream(newUri)
                    val dst = FileOutputStream(currentDb)
                    val buffer = ByteArray(8 * 1024)
                    src?.copyTo(dst, buffer.size)
                    src?.close()
                    dst.close()
                    // Back to main thread
                    launch(Dispatchers.Main) {
                        completion()
                    }
                }
            }
            catch (e: IOException) {
                Toast.makeText(context, "Operation failed.", Toast.LENGTH_LONG).show()
                Log.e("DOWNLOAD FAIL!!!", " EXCEPTION IS:", e)
            }
        }
    }
}

It works fine only if the user selects a valid .db file, but if he selects, for example, an image, the app crashes because wrong data was written to destination.

A:
I just want a way to check if the file the user selected is a valid database file.

If you mean any SQLite database then you can check the header, the first 16 bytes will be "SQLite format 3\000". Here's an example of a function that checks this:-
private fun isFileSQLiteDatabase(f: File): Boolean {
    val SQLITEFILEHEADER = "SQLite format 3\u0000"
    val fis: InputStream
    if (!f.isFile) return false
    val header = ByteArray(16)
    try {
        fis = FileInputStream(f)
        fis.read(header)
        if (String(header) != SQLITEFILEHEADER) {
            fis.close()
            return false
        } else {
            fis.close()
        }
    } catch (e: IOException) {
        return false
    }
    return true
}

*

*You may wish to have a look at https://sqlite.org/fileformat.html
However, if you want to ensure that it is not ANY SQLite Database, for example one that adheres to a set schema, then you would need to undertake a more in-depth check, such as checking that the tables and or other entities (triggers, indexes, views) are as expected.
For example, the following function, passed an array of the expected entity names by interrogating the schema (i.e. sqlite_master):-
private fun isDBValid(f: File, entityList: Array<String>): Boolean {

    var matchcount = 0
    if (!isFileSQLiteDatabase(f)) return false
    try {
        val db = SQLiteDatabase.openDatabase(f.path, null, SQLiteDatabase.OPEN_READWRITE)
        val csr = db.query("sqlite_master", null, null, null, null, null, null)
        while (csr.moveToNext()) {
            for (s in entityList) {
                if (s.toLowerCase() == csr.getString(csr.getColumnIndex("name")).toLowerCase()) {
                    matchcount++
                    break
                }
            }
        }
        csr.close()
        db.close()
    } catch (e: SQLiteException) {
        return false;
    }
    return matchcount != entityList.size
}

*

*Note that this calls the previous function.


text:
Q: TFS2013 (from Web) Team Room is not highlighting member names When playing around with the TFS 2013 Team Rooms in the web browser I'm not finding that references to member names are highlighting like the documentation shows, are we missing a setting somewhere?
MSDN Example.
When we do @Username we get just the plain text.

A: The above MSDN example is for the Team Room web page. For Visual Studio you have to use the Team Rooms for Visual Studio 2013 extension that is based on Team Rooms API which is not public so don't expect to have the same functionality as in the web page

A: The user that you are directing the comment to is the one that gets to see the highlight.
You will not see the coloured highlight when someone else references you.


text:
Q: Settings bundle for iPhone app Right I am developing an app that has two lots of settings Dev and Live. Is there a way to distinguish which lot of settings should be used based on whether the app is live or still in development or do I have to change the whole settings files before it goes live.
I was unsure on how to put this so if your not sure place just ask.

A: What you want to do is define a Preprocessor Macro based on your build configuration.  So if you have a build configuration called dev and one called live you would define a different value for dev and live.
To implement this go into your apps build settings in Xcode and search for "Preprocessor Macros". Add a macro for each build target.
For dev you could add:
APP_CONFIG=0

And for live you could add:
APP_CONFIG=1

Then in your code you are able to distinguish between dev and live build configurations by a simple if statement:
#if APP_CONFIG == 0
    NSLog(@"This is the dev build.");
#else
    NSLog(@"This is the live build.");
#endif


text:
Q: How to run a Django method in parallel with Celery? I have a method update_prices() on my model I would like to run in parallel with Celery but I can't figure out how to make it works. As you can see there is a problem with the .s() because it complains with 'function' object has no attribute 's'. How can i do that?
This is my code:
@celery.app.task(name='Update')
def update():

    # list of arguments
    exchanges_list = Exchange.objects.filter(status='ok').values_list('name', flat=True)

    # the function that execute the method
    def update_prices(name):
        Exchange.objects.get(name=name).update_prices()

    gp = group([update_prices.s(name) for name in exchanges_list])()

A slightly different approach generates the same error:
gp = group(update_prices.s(name) for ex in exchanges_list)()
gp = group(update_prices.(name).s() for ex in exchanges_list)()
gp = group(Exchange.objects.get(name=name).update_prices().s() for ex in exchanges_list)()

This is very similar to the example in the Celery documention for simple group task:
res = group(add.s(i, i) for i in range(10))()

Thank you

A: I reply to my question because I finally found what was causing the error. The method update_prices(name) needed a dedicated decorator like this and it works like a charm!
@celery.app.task
def update_prices(name):
        Exchange.objects.get(name=name).update_prices()


text:
Q: How to add data to Google calendar programmatically in android? Hi I need to add particulars to Google calendar from my application. Is it possible to add data to Google calendar? I am new to android Help me to solve this.

A: using these apis (GData) you can access all Google services, including Calendar:
http://code.google.com/p/gdata-java-client/wiki/Version2

A: I realize that this is an old thread, but for people that stumble upon it now, please note that Google Data Java Client Library  (or gdata-java-client) is no longer being actively developed.
You should use the Google API Client Library for Java that has full support for Android.
It has Google Calendar Sample applications for Android. (One using ClientLogin using the Android accountmanager, and one using the more secure OAuth for authentication/authorization.
(Google doesn't recommend using ClientLogin as it's considered insecure)

A: if you want another aproach   you can check this
http://www.developer.com/ws/article.php/3850276/Working-with-the-Android-Calendar.htm
keep in mind you need to have a real android device to debug .Emulator doesn't come with calendar so the URI cannot be served

A: till now gdata not available for android.

http://code.google.com/p/android-gdata/

You can add event and calendar in the widget. But it removes the added calendar when sync with the Google account.
Till now no proper solution is available.


text:
Q: Weird result with SURF comparison I'm trying to implement a traffic sign recognizer with OpenCV and SURF method. My problem is that i get random results (sometimes really accurate, sometimes obviously wrong) and i cant undertsand why. Here is how i implemented the comparison :

*

*First i detect contours on my image

*Then on each contour, i use SURF to find out if a traffic sign is inside and which traffic sign

The contour detection works perfectly well : using a gaussain blur and canny edge i manage to find a contour similar to this one :

Then i extract the image corresponding to this contour and i compare this image to traffic signs template image such as these :

The cvExtractSURF returns 189 descriptors for the contour image. Then i use the naiveNearestNeighbor method to find out similarities between my contour image and each template image.
Here are my results :
6/189 for the first template (which is the one i'm expecting to find)
92/189 for the second template (which is obviously very different in every way to the contour image)
I really dont understand these results…
Here is the list of the steps i perform :

*

*Turn the contour image in grayscale

*Turn the template image in grayscale

*Equalize the histogram of the contour image (cvEqualizeHist)

*Resize the template image to make it match the contour image

*Blur the template image (cvSmooth)

*Blur the contour image (cvSmooth)

*Do a cvExtractSURF on the template image

*Do a cvExtractSURF on the contour image

*For each descriptor o the contour image i do a naiveNearestNeighbor

*I store the number of "good" points

To evaluate the similarity between the 2 images i use the ratio :
number of goog points / total number of descriptors
P.S: For information i followed this tutorial : http://www.emgu.com/wiki/index.php/Traffic_Sign_Detection_in_CSharp
And used the find_obj sample of OpenCV to adapt it in C.

A: SURF descriptors are fine for comparing richly textured images... I think there isn't enough texture in traffic signs for them.
When extracting descriptors, first "salient points" are located, in your case for example at the corners of the rectangularly shaped marks on both signs (the rectangle and the letter P), then local properties are collected for them. Like, how does a corner-of-a-rectangle look like, from close up, blurred and grayscale.
Then, these descriptors are matched to the corner-of-a-rectangle-s from the letter P. They aren't all that different... (as we're not taking any shape information into account). Maybe the corners of the letter P are a little bit more close to those of the "no entry" sign. Randomly.
Of course, all of this is just a speculation... the only way to figure out is to debug it thoroughly. Try displaying the images with little circles where the descriptors were found (circle size could depend on the scale the point was found at).  Or put both of the images into one IplImage and draw lines between the matching descriptors. Something like this:
http://www.flickr.com/photos/22191989@N00/268039276
As for how to fix this... what about using the same shape matching method for the inside that you use for detecting the outside contours for the traffic sign? (For example, you could look for P shaped objects once a sign is found.)

A:
To evaluate the similarity between the 2 images i use the ratio :
  number of goog points / total number of descriptors

I think it's a bad metric you need to use metric based on descriptor vectors and you must use spartial information between the points.
This is because SIFT-like features matches just the "same points" but not similar points, maybe you can tweak it by changing matching criteria.Because in opencv matching criteria is get nearest point(by descriptor) and check if there is another descriptor near 0.6 similarity.
the descriptor matching consists in two steps. The first step follows the simple but powerful matching algorithm of David Lowe. More precisely, to see if a descriptor A in the left image matches with some descriptor in the right image or not, we compute first the Euclidean distance d(A, A') between the descriptor A in the left image with all the descriptors A' in right image. If the nearest distance, say d(A, A1'), is smaller than k times the second nearest distance, say d(A, A2'), then A and A1' are considered as matched. We set k=0.6
maybe you can change k, but I think it gives more false positives.


text:
Q: Must specify preferenceTheme in theme for PreferenceFragmentCompat New to android dev, switched over to the dark side from iOS, no hate please.
Question:
I added compile 'com.android.support:preference-v7:27.0.0' to my Gradle. I specified a theme in styles.xml. However, I still get the error message shown below. How to fix this?
java.lang.IllegalStateException: Must specify preferenceTheme in theme

at android.support.v7.preference.PreferenceFragmentCompat.onCreate(PreferenceFragmentCompat.java:211)

References: Stackoverflow answer, Medium article
SettingsFragment
public class SettingsFragment extends PreferenceFragmentCompat {
    private SwitchPreferenceCompat receiveReminders;
    private ListPreference notifyMe;

    @Override
    public void onCreatePreferences(@Nullable Bundle savedInstanceState, String rootKey)
    {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);

        receiveReminders = (SwitchPreferenceCompat) findPreference(R.string.key_receive_reminders);
        notifyMe = (ListPreference) findPreference(R.string.key_notify_me);
    }
}

styles.xml
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="preferenceTheme">@style/PreferenceThemeOverlay</item>
</style>

preferences.xml
 <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
    android:title="@string/settings_category_notifications">
    <SwitchPreferenceCompat
        android:key="@string/key_receive_reminders"
        android:title="@string/settings_receive_reminders"
        android:defaultValue="true"/>
    <ListPreference
        android:key="@string/key_notify_me"
        android:title="@string/settings_notify_me"
        android:summary="%s"
        android:entries="@array/settings_notify_me_titles"
        android:entryValues="@array/settings_notify_me_titles"
        android:defaultValue="@string/notify_me_2_hours"
        android:positiveButtonText="@null"
        android:dependency="@string/key_receive_reminders"/>
</PreferenceCategory>
</PreferenceScreen>

A: Make sure that in your AndroidManifest.xml file you are setting the theme on your app and/or activity or else the preferenceTheme will not be found:
<activity
    android:name=".MainActivity"
    android:theme="@style/AppTheme">
</activity>


text:
Q: how to render select dropdown in view page using php code using codeigniter My problem is I want to view the select dropdown in page views using php code. Here's my code below
my controller code
example in image rendering to view page
$grid->column_orderby(  "Image"
                                ,"<img src=\"uploads/banners/<#br_filename#>\" height=\"60\" alt=\"\" />"
                                ,"bt_filename");

I want the line of code to be the same in this way
 $grid = new DataGrid("", "banner_rotating");
 $grid->column("Select", "<select name='banner'><option value='1'>1</option><option value='2'>2</option><option value='3'>3</option><option value='4'>4</option><option value='5'>5</option></select>");

and my views page code is this way
<?=$output?>

and when I see in the views page. I have noticed that the select dropdown is not rendering properly on a page.
Can someone help me how to figured this thing out? TIA


text:
Q: Prerequisites for Bourbaki spectral theory (French) I am considering reading Bourbaki's text Théories spectrales (Springer, French, 2nd Ed.) and was wondering what the prerequisites are. Currently I am familiar with their texts on the Theory of Sets, General Topology (Chaps 1-4 and 5-10), Topological Vector Spaces, Algebra I (Chaps 1-3), and Integration (Chaps 1-6 and 7-9). Do I also need familiarity with their text on Commutative Algebra?
Thanks.

A: I have the book and have seen no uses/references of/to commutative algebra. The only books which are in substantial use are his books on topology (Topologie Générale), topological vector spaces (Espaces Vectoriels Topologiques), and integration (Intégration). Occasionally (maybe once or twice throughout the book) are there references to the recent text on algebraic topology (Topologie Algébrique) and to his first text on algebra; the references to these books, however, only seem to appear in the exercise. There are a few (maybe 3 at most) references to his (reference) book on differential geometry, and a few references to his text on functions of a real variable.
In summary, the prerequisites are
  (i) General Topology I-IV and V-X,

  (ii) Topological Vector Spaces I-V,

  (iii) Integration I-VI and VII-IX, and

  (iv) (Elementary) Differential Geometry + Complex Analysis,

to read and understand the book, and
  (v) Algebra

to complete some of the more applied exercises.


text:
Q: windows server 2003 feature install is asking for amd64 folder and evntagnt.dll file I wanted to turn on snmp feature on windows 2003 R2 Standard X64 Edition Service Pack 2.
My problem is that turning on that feature requires a cd labeled: Service Pack 2 CD-ROM
I Downloaded it from here: https://www.microsoft.com/en-in/download/details.aspx?id=6905
But feature installation is looking for this folder:
d:\amd64
and it's looking for a file evntagnt.dll
I can't find that file in the iso and neither the folder.
can anyone help?

A: Disclaimer: Windows Server 2003 has been end-of-life and out of support for several years now. You really shouldn't be using it.
I find that file (amd64\evntagnt.dll) available on Disc 1 of the non-Service-Pack-2 CD/DVD. You'll need your original ISOs or CDs or DVDs. The Service Pack 2 ISO that you refer to -- w2k3sp2_3959_usa_x64fre_spcd.iso -- is just the cumulative service pack, so it only includes the changes and updates between the base Windows Server 2003 install and Service Pack 2. If evntagnt.dll was not part of that cumulative change set, it won't be on the ISO.
The filename of the Disc 1 ISO (at least of my copy of it) is BRMSXVOL_EN.ISO. I can't find that available for download from Microsoft, nor can I find any non-SP2 downloads of Windows Server 2003. (This is one of the many reasons to migrate off of unsupported versions.)
If you don't have your original CDs, DVDs, or ISOs, you might be able to find someone with a copy of evntagnt.dll, but I'd be cautious of accepting it from an untrusted source.

A: I have found the needed files here:
 Windows Server 2003 R2 Standard Edition x64 with SP2 Trial (64-bit x64)
disk1: http://download.microsoft.com/download/F/9/D/F9DA93F8-2814-4B9B-A6A1-EA9B6B7E8BD6/X13-05825.img
disk2: http://download.microsoft.com/download/F/9/D/F9DA93F8-2814-4B9B-A6A1-EA9B6B7E8BD6/X13-05774.img


text:
Q: Why is calling this list method returning an inaccessibility error? I've seem to run into an error that I've never run into before:
main.cs(9,48): error CS0122: `EratoPrimes.GeneratePrimes(int)' is inaccessible due to its protection level
main.cs(15,15): (Location of the symbol related to previous error)
Compilation failed: 1 error(s), 0 warnings

exit status 1

Background: I am attempting to implement the Sieve of Eratosthenes in C#. I believe I have the logic down of the algorithm fairly well, and have tested it with a Console.WriteLine() loop over the values (without returning the list of primes).
Here is what I have:
using System;
using System.Collections.Generic;

public class EratoSieve{
    public static void Main(string[] args){
        List<int> desired_primes = EratoPrimes.GeneratePrimes(100);
  }
}

public class EratoPrimes{
    List<int> GeneratePrimes(int limit){
        // set up indexed array of candidates:
        int[,] first_array = new int[limit,2];
        for(int i=0; i<limit; i++){
            first_array[i,0] = i;
            first_array[i,1] = 1;
        }
        first_array[0,1] = 0;
        first_array[1,1] = 0;

        // set up list for primes:
        List<int> primes = new List<int>(){2};

        // begin Sieve:
        for(int a=2; a < limit; a++){
            if(first_array[a,1]==1){
                primes.Add(first_array[a,0]);
                for(int b = a*a; b < limit; b+=a){
                    first_array[b,1]=0;
                }
            }
        }
        /* test to see indexed array:
        for(int k=0; k<limit; k++){
            Console.WriteLine(first_array[k,0]+" "+first_array[k,1]);
        }
        */
        return primes;
    }
}

Now, when I attempt to call the GeneratePrimes method in Main, I'm told that EratoPrimes.GeneratePrimes(int) is inaccessible due to its protection level. Why is this the case, and how can I rectify the program?

A: By default methods without an explicit access modifier are private and thus only accessible within their specified class.
If you want to use it as you have defined, you could consider decorating it with the public access modifier and the static keyword :
public static List<int> GeneratePrimes(int limit){ ... }

This will do the following :

*

*public - The public access modifier will allow your method to be accessed outside of your current EratosPrimes class.

*static -  The static keyword will allow it to not require an instance of the same class and thus call it as you currently are using EratosPrimes.GeneratePrimes(). Without it, you would need to create an instance of your EratosPrimes class and then call the GeneratePrimes() method on that instance (i.e. new EratosPrimes().GeneratePrimes(42);)

A: Because you did'nt provided the access modifier in the method signatures, and by default the method is private in C#, you need to add public modifier if you want to access it from outside of this class, and the way you are calling it you will also need to make it static by adding the static keyword.
So your method signatures will become:
public static List<int> GeneratePrimes(int limit)


text:
Q: Can Google Analytics reports be poisoned? Are Google Analytics reports vulnerable to having false data injected by malicious users?
Could a malicious user edit the Google Analytics javascript that runs on your page in order to put some false data in your reports to mislead you?

A: Yes. It is possible.
JavaScript is a user-editable environment, and Google Analytics does not validate the data.
So, you could just inject JavaScript into the page to send any data you like to peoples' Google Analytics accounts, and there's no "validate" which data is valid and which isn't.
I can pop open DevTools Console on my chrome and just enter in Google Analytics data on any site that uses GA:
_gaq.push(["_trackPageview", "/anything-you-want-to-send"]);

This also applies to people "taking" your Google Analytics snippet to put on your site. Luckily, that type of hostile behavior is filterable, since you can configure Google Analytics to exclude data from foreign hostnames.

A: Good question, even we had implemented this and had never crossed our mind, maybe this will help to fix it. I must try the duplicate profile and understand it more...
https://web.archive.org/web/20120530210930/http://techhacking.com/2011/01/23/google-analytics-referrer-spammers/


text:
Q: Fast C++ Graphics (as in programming time) I've played around with GLUT, but I've also read about SDL and one or two other graphics libraries. All I want to do at this point is 2D work. For what I'm doing right now, pixel by pixel plotting is all I need (say, plot(x,y,color) or something of the sort), but in the future I would appreciate the use of sprites. I've given point plotting a go with GLUT but it's rather non-intuitive coming from a B.A.S.I.C. background.
I work on both Ubuntu and Windows, so solutions for both systems are welcome.

A: SDL is probably a good choice; another option to look at would be Qt (just subclass a QWidget and override its paintEvent() method and do your pixel plotting inside that).  Qt can also provide windowing/infrastructure support for OpenGL graphics if that's your preference.


text:
Q: Parsing html tags with Python I have been given an url and I want to extract the contents of the <BODY> tag from the url.
I'm using Python3. I came across sgmllib but it is not available for Python3.
Can someone please guide me with this? Can I use HTMLParser for this?
Here is what i tried:
import urllib.request
f=urllib.request.urlopen("URL")
s=f.read()

from html.parser import HTMLParser
class MyHTMLParser(HTMLParser):
    def handle_data(self, data):
        print("Encountered   some data:", data)

parser = MyHTMLParser()
parser.feed(s)

this gives me error : TypeError: Can't convert 'bytes' object to str implicitly

A: If you take a look at your s variable its type is byte.
>>> type(s)
<class 'bytes'>

and if you take a look at Parser.feed it requires a string or unicode as an argument.So,do
>>> x = s.decode('utf-8')
>>> type(x)
<class 'str'>
>>> parser.feed(x)

or do x = str(s).

A: To fix the TypeError change line #3 to
s = str(f.read())
The web page you're getting is being returned in the form of bytes, and you need to change the bytes into a string to feed them to the parser.


text:
Q: Pinterest API v3 OAuth is it still working? Is Pinterest API still supported or they dropped the majority of the endpoints ?
The documentation from https://developers.pinterest.com/ lacks any information of OAuth authentication.
I've already checked the old versions of the API so please don't mark the question as duplicate:

How to Get OAuth Access Token for Pinterest?
pinterest api documentation

Many of the endpoints from v2 were removed in v3 and v2 now returns 404.
There's no way to actually generate access token and the trick with iPhone app access token doesn't seem to work anymore.
The tasks I'm looking to accomplish with their API:

*

*authenticate users with OAuth

*upload pics on their boards based on access token

Thanks

A: use below link
https://www.pinterest.com/oauth/?consumer_id=1431594&response_type=token
and see
pinterest api documentation

A: Here is a link to the new V3 documentation: https://developers.pinterest.com/docs/redoc/pinner_app
Assuming your app has been approved, the "User Authorization" section (https://developers.pinterest.com/docs/redoc/pinner_app/#section/User-Authorization) provides details on how to authenticate.


text:
Q: Training my chatbot I am currently working on ChatterBot in Python. And while doing that I got stuck in how to train my model. Since I have a long list of faq's to feed in my bot, so can anyone help me giving a right code on how I can train my model with writing each question and answer manually.

A: I recommend that you look at sequence prediction also known as 'sequence to sequence learning'.   Google's TensorFlow has an implementation of this model called 'seq2seq'.  Suriyadeepan Ram wrote a good article, with code, entitled "Chatbots with Seq2Seq" which should help you get started.


text:
Q: Zope: getting acquired permission of a role on object I thought this must be easy but I really have troubles figuring it out: I'd like to check for an acquired permission of a role on an object.
I don't want to check for the actual user's roles or permissions, I just want to check i.e. if on an object Anonymous has the permission 'Access contents information'. This is easy if the permission is set on the object in question, but proves more difficult when the permission is acquired.
I tried this:
siteRoles = ('Anonymous', 'myRole1', 'myRole2', 'Manager')
permission = 'Access contents information'

rolesDictList = self.rolesOfPermission( permission )

roles = [roleDict['name'] for roleDict in rolesDictList if roleDict['selected']]

for i, role in enumerate(siteRoles):
    if role in roles:
        roleMin = i
        break

return roleMin

This does not work, because it does not give the acquired permissions.
My next idea was to walk through the parents upward until I find some permissions that are not acquired. But this would not really solve the problem, as it would ignore permissions that are set higher up in the hierarchy (ok, I could check for acquired and continue upward). Also there is an oddity: 'Manager' is always selected in rolesOfPermission. Why is this so?
Anyway, I presume there must be a simpler way to do this?

A: Simply use the rolesForPermissionOn() function:
from AccessControl.PermissionRole import rolesForPermissionOn

roles = rolesForPermissionOn(permission, context)

This returns a list of roles that have the specific permission for the given context. It'll walk the acquisition chain as needed.


text:
Q: Call function from another function error C++ I'm trying to get my player1Hand function to work with my deck function so cards can be drawn from the deck and used in each player function. I'm not sure how to call one function from another function because it's saying,
    main.cpp:68:10: error: 'deck' was not declared in this scope
cout << deck[ z ].rank << " of " << deck[ z ].suit << endl;

Full code:
#include <iostream>
#include <cstdlib> //for rand and srand
#include <cstdio>
#include <string>
#include <ctime> // time function for seed value
#include "Card.h"

using namespace std;

#define pause cout << endl; system("pause")

class CardClass {
public:

  struct card

  {
    string rank;//this example uses C++ string notation
    string suit;
    int value;
  };
public:
  void deckFunction ();

private:

};

void CardClass::deckFunction () {
  srand(time(0));

  struct card deck[52];  // An array of cards named deck, size 52

  const string ranks[ ] = { "Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight",
    "Nine", "Ten", "Jack", "Queen", "King" };

  const string suits[ ] = { "Diamonds", "Hearts", "Spades", "Clubs" };

  int k = 0;

  for ( int i = 0; i < 13; i++)
  {
    for ( int j = 0; j < 4; j++)
    {
      deck[ k ].rank = ranks[ i ];
      deck[ k ].suit = suits[ j ];
      k++;
    }
  }

}

void Players::player1hand () {

  CardClass deckFunc;
  deckFunc.deckFunction();
  int p1Chips = 10;
  int pot = 0;
  int player1bet = 0;
  srand(time(0));
  char ans;
  do {
    int z = rand () % 52;

    cout << deck[ z ].rank << " of " << deck[ z ].suit << endl;
    cout << "Place bet: ";
    cin >> player1bet;
    if (player1bet > 0) {
      pot = pot + player1bet;
      p1Chips = p1Chips - player1bet;
      cout << pot << endl;
      cout << p1Chips << endl;

    }
    else {
      cout << "Player 1 folds.";
      cin >> ans;
    }
    cout << "Would you like another card? " << endl;
    cin >> ans;
  } while (ans == 'y');

}

int main()
{
  Players player1;
  player1.player1hand();

  pause;

  return 0;

}

Card.h file (not really used yet):
#include <iostream>
using namespace std;

class Players
{
public:
void player1hand ();
void player2hand ();
void player3hand ();
void player4hand ();
void player5hand ();
void player6hand ();
private:

};

I know some of the functions and class interaction is a bit sloppy right now but I'm just trying to get everything to work. So basically, I need the player class to take a card from the deck class, then allow them to place a bet, then repeat this process. Thanks for the help!

A: You have
struct card deck[52];

This defines deck in function CardClass::deckFunction. This does not make deck visible in Players::player1hand.
You can resolve this by passing deck to player1Hand as an argument.
Change the member functions of Players to include an additional argument.
class Players
{
   public:
      void player1hand (card deck[]);
      void player2hand (card deck[]);
      void player3hand (card deck[]);
      void player4hand (card deck[]);
      void player5hand (card deck[]);
      void player6hand (card deck[]);
   private:
};

Then, update the implementation of the functions. The updated Players::player1hand would look like:
void Players::player1hand (card deck[]) {
   // ... include the body of the function
}

A: Your
struct card deck[52];

is visible only in void CardClass::deckFunction (), and you are trying to access it outside in void Players::player1hand()


text:
Q: Mixed mode assembly is built against version 'v2.0.50727′ C# Enterprise architect add-in I am building an Enterprise Architect add-in using C#. I have to interact with SVN Repository.
I am using VS2010 and SharpSVN as library to interact with SVN Repository. my Add-in work fine when I change it to .NET 3.5. But now I have to interrogate with some another add-in and that other add-in is only compatible with 4.0.
but when I change my add-in code to .NET 4.0 then it give famous error
"Mixed mode assembly is built against version 'v2.0.50727' of the runtime and cannot be loaded in the 4.0 runtime and need some configuration etc"
I have read here different topics about that problem and suggestion is to add app.config file. with the tags
<Configuration>
<startup useLegacyV2RuntimeActivationPolicy="true">
  <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
<runtime>
  <NetFx40_LegacySecurityPolicy enabled="true"/>
</runtime>
</Configuration>

and same like tag this from different posts. I have tried everyone but still the problem remains. I have checked that VS2010 automatically generates the config file with the filename in Debug folder automatically.
Can anyone suggest me the solution? for example my add-in name is MyAddIn so VS2010 generates MyAddIn.dll and MyAddIn.dll.config with the above mentioned tags.
But problem remain there. I am using windows 7 64 Bit.
Any Help will be highly appreciated.

A: The settings in your *.dll.config is useless, and that's why you cannot get what you want. As your dll is loaded by Enterprise Architect, you will have to modify its *.app.config file to include such settings. Usually, that's not possible, as your dll is simply an add-in.
A workaround is to perform a full migration to .NET 4, which not only compiles your dll against .NET 4, but also compile all its dependencies against .NET 4.


text:
Q: Batch dot product with numpy? I need to get the dot product of many vectors with one vector. Example code:
a = np.array([0, 1, 2])

b = np.array([
    [0, 1, 2],
    [4, 5, 6],
    [-1, 0, 1],
    [-3, -2, 1]
])

I would like to get the dot product of each row of b against a. I can iterate:
result = []
for row in b:
    result.append(np.dot(row, a))

print(result)

which gives:
[5, 17, 2, 0]
How can I get this without iterating? Thanks!

A: Use numpy.dot or numpy.matmul without for loop:
import numpy as np

np.matmul(b, a)
# or
np.dot(b, a)

Output:
array([ 5, 17,  2,  0])

A: I will just do @
b@a
Out[108]: array([ 5, 17,  2,  0])

A: can be useful if you need to line by line multiply two arrays of vectors
np.sum(a * b, axis=1)


text: Q: What is the character used by Internet Explorer 10 as the mask in its password inputs? I need to know because I want to check whether the primary font has it.  I am investigating why the browser falls back to the secondary font.  My suspicion is that the primary font does not have the character that the browser uses.


text:
Q: How to generate variables and then assigning an integer to them from a list (python3) divisions = int(input('Divisions: '))
divisible = []

while divisions > 0:
    x = input('Divisble: ')
    divisible.append(x)
    divisions = divisions - 1

Trying to get the 'divisible' list to split into separate integer variables, but the problem i have is that the amount of variables that houses the integers changes. How would I solve this?

A: You could use the built-in reduce function
import functools

l = [2, 3, 4]
n = 24
result = functools.reduce(lambda a, v: a / v, l, n)

print('result: {}'.format(result))

This basically starts with n, divides, by 2, takes the answer and divides by 3, .. for each value in the list l, so the output is 1.
reduce was built in in python 2; now it's in the functools module.
Here's a link to see it running interactively at pythontutor.com


text:
Q: Webpack file-loader (multiple path) I'm using Webpack in a project which is supposed to be recovered by another dev.
In my configuration, I use file-loader to process my .png/jpg/svg files.
{
     test: /\.(png|jpg|gif|svg)$/,
     use: [
          {
               loader: 'file-loader',
               options: {
                    name: '[name].[ext]',
                    outputPath: './assets/images'
               }
          }
     ]
}

The thing is that I'd like to have the same arborescence in my dist/ folder than in my src/ (assets > images > folderName)
> src
  - assets
       - images
            - icons
            - logos
            - ...

For now, every images are in the same assets/images folder.
Using [path] output this structure (which contains the src/ folder):
> dist
     - src
         - assets
             - images
                 - icons
                 - logos
                 - ...

Any idea of how define the root folder only for images assets?
Thanks in advance


text:
Q: What are good cases not to use setReatinInstance(true) in a fragment? Since orientation changes happen fairly quickly one would think that keeping a Fragment in memory during that time would be more efficient than recreating it again.
Since it's kept for a short time only, there seem to be little impact on memory.
What then shall be good reasons NOT to use setRetainInstance(true) for each and every Fragment?

A:
What then shall be good reasons NOT to use setRetainInstance(true) for each and every Fragment?

Google's primary concern is that you'll screw up and have data members in the fragment that refer to the old activity that you do not clean up in post-configuration lifecycle method calls (e.g., onCreateView()). For example, you might hold onto a widget in a data member, where you do not immediately null out or repopulate that data member on a configuration change. If your fragment has a reference back to the old activity, the old activity (and everything it holds onto) cannot be garbage-collected until your fragment gets destroyed. This is one of the reasons why Google does not recommend retaining any fragment with a UI.

A: Firstly maybe check this link: http://android-er.blogspot.com/2013/05/how-setretaininstancetrue-affect.html
Basically you shouldn't always retain the instance of the fragment because fragments are attached to activities. Hence when an activity is re-created (i.e. on configuration change), the fragment needs to be re-associated to the new activity (which leads to extra coding and some extra problems). If you just unnecessarily setRetainInstance(true), you are giving yourself more error checking and coding to do for no reason. By setting the setRetainInstance(true), you will need to deal with a different fragment lifecycle as well because certain methods in the lifecyle are now skipped (i.e. the onCreate() is no longer called after configuration changes). As far as I understand, setRetainInstance(true), won't make it more efficient because you could use onSaveInstance to save any data that you would want to use in the recreation of the same kind of fragment.
I hope this helps.


text:
Q: Making layers untrainable at end of epoch changes loss in next epoch I wrote a custom callback to automatically freeze layers in my multi input/output network in case the corresponding loss falls below a certain threshold.
How it works: After every epoch it checks if the loss of the first weight in self.weights is below the self.loss_thresholds value. If so, it freezes the corresponding layers and makes the underlying layers trainable. After that it sets the models stop_training flag in order to exit the fit function and to recompile the model.
from keras.callbacks import Callback

class WeightLossCallback(Callback):

def __init__(self, loss_weights):
    self.loss_weights = loss_weights
    self.weights = ["akVol","biltarres","riskap1","sraj","zbj"]
    self.loss_thresholds = {"akVol": 0.12, "biltarres": 0.12, "riskap1": 0.14, "sraj": 1.5, "zbj": 14.}
    self.learning_rate = {"akVol": 0.05, "biltarres": 0.05, "riskap1": 0.05, "sraj": 0.01, "zbj": 0.05}
    self.stopTraining=False

def on_train_begin(self, logs={}):
    K.set_value(self.model.optimizer.lr, self.learning_rate[self.weights[0]])

def on_epoch_end(self, epoch, logs={}):

    if epoch < 10:
        return

    def freezeAttAndLayer(weight):
        print("Setting weight " + weight + " to zero.")
        self.weights.remove(weight)
        self.loss_weights[weight] = 0.0
        self.stopTraining=True

        print("Step 2: Freezing corresponding layers.")
        for layer in self.model.layers:
            if weight in layer.name:
                print("Freezing layer " + layer.name + ".")
                layer.trainable=False

    def unfreezeAttAndLayer(weight):
        print("Step 3: Unfreezing corresponding layers.")
        self.loss_weights[nextWeight] = 1000.
        for layer in self.model.layers:
            if weight in layer.name:
                print("Unfreezing layer " + layer.name + ".")
                layer.trainable=True

    # in case of last weight in self.weights list
    if len(self.weights) < 2:
        lastWeight = self.weights[0]
        if logs[lastWeight+"_loss"] >= self.loss_thresholds[lastWeight]:
            return
        else:
            freezeAttAndLayer(lastWeight)
            self.model.stop_training=True
            return

    currentWeight = self.weights[0]
    nextWeight = self.weights[1]
    print("Step 1: Checking weight thresholds for " + currentWeight + " and " + nextWeight + "...")

    if logs[currentWeight+"_loss"] < self.loss_thresholds[currentWeight]:
        freezeAttAndLayer(currentWeight)
        unfreezeAttAndLayer(nextWeight)

    if self.stopTraining:
        self.stopTraining=False
        self.model.stop_training=True
        print(self.loss_weights)
        print(self.weights)

The fit function works as follows:
from keras.callbacks import ModelCheckpoint, ReduceLROnPlateau
ModelCpt = ModelCheckpoint("C:/Users/pan11811/Desktop/ModelCheckpoint/test.h5", monitor="loss",save_best_only=True, save_weights_only=False)
WeightLossCpt = WeightLossCallback(loss_weights)

epochCount=0
while(i<21):
ReduceLRCpt = ReduceLROnPlateau(patience=35, min_delta=0.1, factor=0.6, monitor=WeightLossCpt.weights[0]+"_loss", verbose=1, min_lr=0.001)
model.fit(inputDic, outputDic, epochs=2000+epochCount,batch_size=4000, callbacks=[ReduceLRCpt,ModelCpt,WeightLossCpt], verbose=1)
   model.compile(optimizer=optimizers.Adamax(lr=0.025),loss=losses.mean_squared_error,loss_weights=Weig htLossCpt.loss_weights)
epochCount+=1
if len(WeightLossCpt.weights) == 0:
    print("Training completed.")
    break

print("#######################################")
print("RECOMPILED_MODEL")
print("#######################################")

Here is the training log for freezing the sraj net:
    Epoch 968/2003
    64538/64538 [==============================] - 0s 5us/step - loss: 1489.0058 -    tbaRenormalized_loss: 11.6664 - tbasum_loss: 180.4811 - vtstkj_loss: 0.0000e+00 - sraj_loss: 1.4885 - riskap1_loss: 0.1149 - biltarres_loss: 0.1144 - akVol_loss: 0.1210 - zbj_loss: 60316658.7545 - zb_loss: 18562112.8038 - sra_output_loss: 0.4971 - vtstk_loss: 0.0000e+00
Step 1: Checking weight thresholds for sraj and zbj...
Setting weight sraj to zero.
Step 2: Freezing corresponding layers.
Freezing layer input_sraj.
Freezing layer sraj_0.
Freezing layer sraj_1.
Freezing layer sraj_2.
Freezing layer sraj_3.
Freezing layer sraj_4.
Freezing layer sraj_5.
Freezing layer sraj.
Step 3: Unfreezing corresponding layers.
Unfreezing layer zbj.
{'tbaRenormalized': 0.0, 'tbasum': 0.0, 'sraj': 0.0, 'riskap1': 0.0, 'zb': 0.0, 'biltarres': 0.0, 'akVol': 0.0, 'vtstk': 0.0, 'zbj': 1000.0}
['zbj']

#######################################
RECOMPILED_MODEL
#######################################
Epoch 1/2004
64538/64538 [==============================] - 0s 6us/step - loss: 18151638696.1287 - tbaRenormalized_loss: 11.6664 - tbasum_loss: 180.4811 - vtstkj_loss: 0.0000e+00 - sraj_loss: 2.5473 - riskap1_loss: 0.1149 - biltarres_loss: 0.1144 - akVol_loss: 0.1210 - zbj_loss: 18151638.7103 -    zb_loss: 5467256.6113 - sra_output_loss: 0.9667 - vtstk_loss: 0.0000e+00

The problem here is that right before freezing the layers, sraj loss is below threshold at 1.4885 but after freezing and recompiling the network the loss jumps to 2.5473, but it remains constant.
So my question is, why does this jump occur when I clearly froze all layers?
I appreciate any help!


text:
Q: Tastypie Mongoengine ReferenceField dereference? Trying to build REST interface with tastypie and mongodb.
I have schema
class ObjectsA(Document):
     attr1 = StringField(max_length=12, required=True)
class ObjectsB(Docuemnt):
     attr2 = ReferenceField(ObjectsA,
                        reverse_delete_rule=CASCADE, dbref=False)

After sending a  GET request to ObjectsB i get json object with attr2 as
"attr2": ObjectsA object"
How can I get attr1 in response from request to ObjectsB?

A: I have found solutions. Maybe it's useful to someone.
For me, it was not obvious.
In the description for the resource class, you must describe all of the fields that
have type ReferenceField
for example:
from tastypie_mongoengine import fields

class CustomerResource(resources.MongoEngineResource):
    person = fields.ReferenceField(to=
        'test_project.test_app.api.resources.PersonResource',
         attribute='person', full=True)

    class Meta:
        queryset = documents.Customer.objects.all()
        allowed_methods = ('get', 'post', 'put', 'patch', 'delete')
        authorization = tastypie_authorization.Authorization()


text:
Q: MethodNotAllowedHttpException in laravel I am getting 'Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException' as response when I am trying to check if the validator works. So when after I click the save button. This is my code :
in my view 'addMedia-partial.blade.php'  :
         {{ Form::open() }}

            <input type="text" name="videoUrl" placeholder="enter youtube video url" />
            <input type="text" name="videoTitle" placeholder="enter video title" />
            <input type="text" name="videoDescription" placeholder="enter video description" />

            <input type="submit" value="Save">

        {{ Form::close() }}

in my routes.php :
Route::get('/guide/dashboard/media/add/storeVideo', array('as' => 'guide-video-add','uses' => 'MediaController@getNewVideo'));
Route::post('/guide/dashboard/media/add/storeVideo', array('uses' => 'MediaController@postNewVideo'));

in my controller MediaController.php :
public function postNewVideo()
{

        $rules = array('videoUrl' => 'required', 'videoTitle' => 'required|min:5', 'videoDescription' => 'required|min:20');

        $validator = Validator::make(Input::all(), $rules);

        if ($validator->fails()) {

            //return Redirect::route('guide-media-add')->withErrors($validator);
            //gaat niet omdat dit in een andere controller is ??

            return Redirect::route('guide-video-add')->withErrors($validator);

        }
}

public function getNewVideo()
{
    return View::make('guide.dashboard.dashboard')->nest('child', 'guide.dashboard.addMedia-partial');
}

A: Please check with Firebug which URL and which type of request are you sending.
Secondly please execute php artisan route:list This will show you all the routes and which method they accept.
There must be mismatch between defined and actual requests. You must be sending POST to the route which only accepts GET.


text:
Q: How to define gallery responsive image size in grid All 12 of the li img inside of .gallery displays correctly in codepen.io but when brought into jsfiddle https://jsfiddle.net/n61y2acv/ it breaks and displays past .gallery width. Why does this occur?
.gallery {
 display: grid;
 grid-gap: 0.75rem;
 grid-auto-flow: dense;
 padding: 40px;
 list-style: none;
 background: white;
 width: 100%;
 box-sizing: border-box;
 margin-top: 0;
 margin-bottom: 0;

  li  {
   figure, img {
    width: 100%;
    height: 100%;
    margin: 0;
    border-radius:15px;
    display: block;
    object-fit: cover;
   }
 }
}

A: Give max-width to your image element!

img {
  max-width: 100%;
}


text:
Q: Tips or tools for debugging Spring applications? I am trying to use Spring for the first time in an application. The general issue that comes up repeatedly is how to debug Spring. The framework is configuration heavy so traditional code debugging seems fruitless. I have no real idea how to go about troubleshooting short of turning on the debugging level logs (which are lacking) and scanning through.
Are there any general tips or tools to assist Spring debugging?

A: If you're using Eclipse, then get hold of the Spring IDE (available from the Eclipse Marketplace within the Help menu of Eclipse). This will provide code-completion, bean visualisation, and hot-linking to your config files.

A: I don't think Spring debugging should be any different to any other debugging scenario.
What aspects of Spring are you using ? If you're using dependency injection properly, then I wouldn't anticipate any problems.
However if you're dynamically resolving beans via their name (at runtime, using ApplicationContext.getBean()) then I can see that's going to cause you problems anticipating flow of control etc., and would suggest that you revisit your IoC.
EDIT: It's quite useful to have the Spring source code available. It's well put together and quite readable, and therefore possibly of use when debugging.

A: I generally just use the java debugger in eclipse - it works fine on most classes. Some classes are wrapped at compile/runtime by bytecode changes - for these you generally cannot put breakpoints in methods, however you can set a breakpoint at method entry.
If you have a very specific situation you maybe should elaborate a bit in your question.
I'm generally also ok with the logging levels - what do you think is wrong with them?

A: As of 09/2011 (Version: 2.6.1.RELEASE, Build Id: 201105041000) a real annoyance is the fact that the debugger doesn't stop inside closures, so you have to remember to put a breakpoint inside the ones you want to examine; that is fine as it is "almost" going to a different class which a lot of time doens't matter, but when it does, you have to remember that.


text:
Q: How to decide the countability of 'performance'
Performance

*[uncountable, countable] how well or badly you do something; how well
  or badly something works

  the country's economic performance
He criticized the recent poor performance of the company.
Profits continue to grow, with strong performances in South America
  and the Far East.
Her academic performance has been inconsistent.

Some nouns can be classified as both uncountable and countable. The above is an example taken from the Oxford dictionary.
Without a plural marker or an indefinite article, sometimes it's a bit difficult for me to decide which category a noun like performance belongs with. I'm not sure if the categories could bring nuances to the intended meaning.
Would a native speaker automatically classify them into different noun categories, or never pay attention to such dichotomy?

A: Decide whether you're speaking about one or multiple instances and go with it. That decision is logically prior to choosing the singular or plural noun to express the idea.

The J-class car has renowned performance.
J-class cars have raced in the Grand Prix for fifty years. The
  performances they've turned in have been uniformly excellent.

We accept sentences like the second one above because we understand the speaker is referring to multiple individual performances. That is not to say that you couldn't cast the second sentence in the singular:

J-class cars have raced in the Grand Prix for fifty years. Their
  performance has been excellent.

The abstraction permits a coalescence of the plural into a singular but does not demand it.
P.S. Even nouns which do not normally occur in the plural can be licitly pluralized if the meaning admits a plural.

Woolen sweaters are noted for their warmth.  But there are different kinds of warmth. We can speak of warm colors, warm people, and being warm when getting close in a guessing game. So not all warmths can be measured with a thermometer.

We would understand the speaker to be taking liberties with the word, but that freedom is there to be taken when necessary.

A: Personally, I don't agree on the word "performance" -- as well as many others --
 being classified by dictionaries as countable or uncountable.
According to grammar books, uncountable, or non-count, nouns are those which will not take the indefinite article "a/n" and will take, instead, "some" or some partitive (a piece of, an item of, etc.). That is clearly not the case with "performance":

*

*That has been an outstanding performance.

My impression has always been that dictionaries tend to confuse countable-uncountable with concrete-abstract. It is a fact that abstract nouns, which generally derive from verbs and adjectives, do not usually take the plural form, that is, unless we refer to instances of the concept conveyed by the noun.
P. E. Dant's example in his comment above provides us with an excellent example of this:

In a sentence like "Her performance is superb," the noun could be uncountable (in reference to her job skills, for instance) or countable (in reference to her reading of a part in a theatrical production).

My feeling is that, when we refer to her acting skills in general, we are using the abstract "performance", while the sense of the noun becomes concrete when reference is made to her specific acting on a particular occasion.
When used in a concrete sense, the noun will enable pluralization (different instances of performance), while it will be used in the singular form when used in a more abstract sense.
The fact that dictionaries usually confuse "abstract" with "uncountable" may stem from the considerable overlap between abstract and non-count, as recognized by Quirk on page 246 of his Comprehensive Grammar of the English Language:

My claim is that the fact that an abstract noun is generally used in the singular does not make it uncountable.
In reply to BillJ's objection, please find below how Quirk associates, on page 247 of his book mentioned above, the use of articles with the classification into count and non-count nouns:


text:
Q: Unable to run tmux on OS X So I got brew on my mac and I had tmux installed and running just fine. Then after I refreshed my system every time I try to run tmux i get this error:
"-bash: tmux: command not found"
So since I'm kinda new to linux or unix based systems in general I'm having problems getting it to work. I got "tmux.conf" file in place but that doesn't seem to help.
Any takers on this one?
UPDATE:
per request from the comments.
echo $PATH

gives me
/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/X11/bin

brew command also works


text:
Q: Oracle Query works for 19c but does not work in 11g This query
SELECT (SELECT CERT_NBR
        FROM (
          SELECT XREF.CERT_NBR, XREF.REQUEST_ID , XREF.AUDIT_TS
          FROM B2B_XREF_CERT_QUOTE XREF
          WHERE XREF.REQUEST_ID = REQ.REQUEST_ID
          ORDER BY XREF.AUDIT_TS DESC
       ) WHERE rownum = 1) AS CERT_NBR
FROM B2B_RT_REQUEST REQ,
     B2B_RT_RESPONSE RES
WHERE REQ.REQUEST_ID = RES.REQUEST_ID
AND UPPER(TRIM(REQ.REQUEST_ID)) IN ('RF27117FE')

runs fine on 19c but fails on 11g , can someone tell me what is an alternative way to write the same which will work for 11g.

A: Oracle (and MySQL) do not allow nested correlated subquery references.  You can instead use KEEP:
SELECT (SELECT MAX(CERT_NBR) KEEP (DENSE_RANK FIRST ORDER BY XREF.AUDIT_TS DESC)
        FROM B2B_XREF_CERT_QUOTE XREF
        WHERE XREF.REQUEST_ID = REQ.REQUEST_ID
       ) AS CERT_NBR

You should also learn proper, explicit, standard, readable JOIN syntax.


text:
Q: Return the lines which have no given symbol in Ruby I want to print the lines from a website's content page which do not start with the symbol "#".
def open(url)
  Net::HTTP.get(URI.parse(url))
end

page_content = open('https://virusshare.com/hashes/VirusShare_00000.md5')

line_num=0
page_content.each_line do |lines|
  line_num += 1
  if lines[0] == "#"
    lines.each_line do |line|
      if (line_num==1)
        puts line
      end
    end
  end
end

Expected result:
2d75cc1bf8e57872781f9cd04a529256
00f538c3d410822e241486ca061a57ee
3f066dd1f1da052248aed5abc4a0c6a1
781770fda3bd3236d0ab8274577dddde
................................

It works when I try to print the lines that start with "#":
lines[0] != "#"

But it does not work in the opposite way.

A: You could just use a mix of reject and start_with? :
require 'net/http'
def open(url)
  Net::HTTP.get(URI.parse(url))
end

page_content = open('https://virusshare.com/hashes/VirusShare_00000.md5')

puts page_content.each_line.reject{ |line| line.start_with?('#') }

It outputs :
2d75cc1bf8e57872781f9cd04a529256
00f538c3d410822e241486ca061a57ee
3f066dd1f1da052248aed5abc4a0c6a1
781770fda3bd3236d0ab8274577dddde
86b6c59aa48a69e16d3313d982791398
42914d6d213a20a2684064be5c80ffa9
10699ac57f1cf851ae144ebce42fa587
248338632580f9c018c4d8f8d9c6c408
999eb1840c209aa70a84c5cf64909e5f
12c4201fe1db96a1a1711790b52a3cf9
................................

If you just want the first line :
page_content.each_line.find{ |line| !line.start_with?('#') }

Notes
page_content.each_line do |lines|

lines should be called line. It is just one line.
When you call
lines.each_line do |line|

You iterate over "each" line of just one line, so the loop isn't needed at all.
Your code could be :
require 'net/http'

def open(url)
  Net::HTTP.get(URI.parse(url))
end

page_content = open('https://virusshare.com/hashes/VirusShare_00000.md5')

page_content.each_line do |line|
  puts line if line[0] != "#"
end


text: Q: How can I connect two angular apps with socket io? I am trying to make a chat support system. I have two angular apps running on two different ports. App1(Customer) sends a message to App2(agent). I have trouble connecting the two apps via socket io. I just started learning socket io. So my knowledge is minimal. Any advice is appreciated.


text:
Q: How to redirect the output from my file deletions and directory removals? I want to append the results after I remove the .txt files and the the CIS153 directory from my code.
The problem is that it is not appending the correct results.
I found out how to append the results to a text file I am just not sure where I should place that code for my script.
SETLOCAL ENABLEDELAYEDEXPANSION

SET CURRENT_DIR=%CD%
SET DIR_NAME=%CURRENT_DIR%CIS153
SET COUNTER=1

MKDIR %DIR_NAME% ECHO output.txt

FOR F DELIMS= %%X IN (MyData.txt) DO (
ECHO %%X  CUsersAdministratorDesktopCIS153myFile!COUNTER!.txt
SET A COUNTER=!COUNTER!+1
)

DEL CUsersAdministratorDesktopCIS153.txt | echo
C:\Users\Administrator\Desktop\CIS153 > output.txt

RD S CUsersAdministratorDesktopCIS153 | echo
C:\Users\Administrator\Desktop\CIS153 > output.txt

I expect this code to output in the output.txt file.
" C:\Users\Administrator\Desktop>DEL
C:\Users\Administrator\Desktop\CIS153\*.txt

C:\Users\Administrator\Desktop>RD /S "C:\Users\Administrator\Desktop\CIS153"
C:\Users\Administrator\Desktop\CIS153, Are you sure (Y/N)? "

Instead the output im receiving in the output.txt file is this
"C:\Users\Administrator\Desktop\CIS153
C:\Users\Administrator\Desktop\CIS153"

A: As others have commented, your fundamentals are incorrect.
Here is some reading you can do regarding redirecting output.
If you run a .bat from the command line and redirect the output to a text file then you can replicate what you are trying to achieve. Example:
@echo off
:: Everything you put here won't display in the output file
setlocal enabledelayedexpansion
for /l %%i in (1,1,3) do set /a myVar%%i=!random!

@echo on
:: Everything you put here will display in the output file

for /l %%i in (1,1,3) do echo. !myVar%%i!

Run on the command line via test.bat > output.txt would leave an output.txt of:
C:\Test>for /L %i in (1 1 3) do echo. !myVar%i!

C:\Test>echo. !myVar1!
 11828

C:\Test>echo. !myVar2!
 30270

C:\Test>echo. !myVar3!
 19262


text:
Q: How to make migrations in zodb? I can see in docs, that if I would change some fields in class then I need to write a migration script. But what exactly do I need to write in that script? Also is there a some automatic migration maker like there is in dgango?

A: In your script you would modify the object stored in ZODB to match the new format of the object as your code requires.
No, there is no easy to use migration "maker".


text:
Q: Add a timer LM555C on Qucs Does anyone know how to add a timer on Qucs ? The component's navigation bar doesn't help at all, It confuses me, I can't find a timer. I wondering, perhaps It could be added through library. In this case, I need to add LM555C timer on my circuit.

A: There is no model for that component. What you can do is to model it as explained here.


text:
Q: NSURLSession returns different response than browser would, why? Any idea why NSURLSession returns this response:

The authorization type you provided is not supported. Only Basic and
  OAuth are supported

let username = "8r6nibK8Pe28WFhjTX1gGb1Rhhhc7xM02v7XKRPedL4"
let password = "8r6nibK8Pe28WFhjTX1gGb1Rhhhc7xM02v7XKRPedL4"
let loginString = NSString(format: "%@:%@", username, password)
let loginData: NSData = loginString.dataUsingEncoding(NSUTF8StringEncoding)!
let base64LoginString = loginData.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)

let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let authString = "Basic \(base64LoginString)"
config.HTTPAdditionalHeaders = ["Authorization" : authString]

let url = NSURL(string: "https://api.datamarket.azure.com/Bing/Search/Image?$format=json&Query='Rambo'+'Oscar'")
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"

let a = NSURLSession(configuration: config).dataTaskWithRequest(request, completionHandler: {data, urlResponse, error in

    if data != nil {

        let str = NSString(data: data!, encoding: NSUTF8StringEncoding)
        print(str)
    } else {
        _ = 7
    }
})

a.resume()

Browser returns different response with meaningful image information. And I am using basic authentication to send request.

A: The problem may probably the option: .Encoding64CharacterLineLength. try:
let base64LoginString = loginData.base64EncodedStringWithOptions([])

To investigate use Charles Proxy to see the difference in the requests. –  zaph 10 mins ago


text:
Q: React, material-ui and stepper: how to display html in each steps The title says it all. From the examples of  Stepper it seems there is only a text that can be shown. Is it possible to display html instead?
If I put html inside <StepContent /> the page looks weird:

I used the following code:
<Stepper activeStep={0}>
    <Step key={1}>
        <StepLabel>FOO</StepLabel>
        <StepContent>

                <FormControl component="fieldset" required>
                    <FormLabel component="legend">Gender</FormLabel>
                    <RadioGroup
                        aria-label="gender"
                        name="gender1"
                        value={this.state.value}>
                        <FormControlLabel value="female" control={<Radio/>} label="Female"/>
                        <FormControlLabel value="male" control={<Radio/>} label="Male"/>
                        <FormControlLabel value="other" control={<Radio/>} label="Other"/>
                        <FormControlLabel
                            value="disabled"
                            disabled
                            control={<Radio/>}
                            label="(Disabled option)"
                        />
                    </RadioGroup>
                </FormControl>

        </StepContent>
    </Step>
    <Step key={2}>
        <StepLabel> bar </StepLabel>
    </Step>
</Stepper>

A: Any content you put into StepContent will show up as part of the Step itself, and not shown in it's own content pane below.
If you want to show some larger content, you should keep track of the current step index in your state, and show content depending on that index. This will be a lot more code, but you'll be able to show content correctly. This is how the doc does it, by the way.
Here's a snippet showing how you might accomplish that:
class HorizontalLinearStepper extends React.Component {
  static propTypes = {
    classes: PropTypes.object,
  };

  // Track the active step to know what content to show
  state = {
    activeStep: 0,
  };

  getNumberOfSteps() {
    return 2;
  }

  // Get content based on which step is active
  getStepContent(step) {
    switch (step) {
      case 0:
        return (

            <FormControl component="fieldset" required>
              <FormLabel component="legend">Gender</FormLabel>
              <RadioGroup
                aria-label="gender"
                name="gender1"
                value={this.state.value}>
                <FormControlLabel value="female" control={<Radio />} label="Female" />
                <FormControlLabel value="male" control={<Radio />} label="Male" />
                <FormControlLabel value="other" control={<Radio />} label="Other" />
                <FormControlLabel
                  value="disabled"
                  disabled
                  control={<Radio />}
                  label="(Disabled option)"
                />
              </RadioGroup>
            </FormControl>

        );
      case 1:
        return (

            <Typography>Some more arbitrary content.</Typography>
            <Button>And a big button for good measure</Button>

        );
      default:
        return 'Unknown step';
    }
  }

  // Update the active state according to the next button press
  handleNext = () => {
    const { activeStep } = this.state;
    this.setState({
      activeStep: activeStep + 1
    });
  };

  // Similar for back and reset buttons
  handleBack = () => {
    const { activeStep } = this.state;
    this.setState({
      activeStep: activeStep - 1,
    });
  };

  handleReset = () => {
    this.setState({
      activeStep: 0,
    });
  };

  render() {
    const { classes } = this.props;
    const { activeStep } = this.state;

    // Notice that the content below isn't in the Stepper, it's in its own pane underneath
    return (

        <Stepper activeStep={activeStep}>
          <Step key={0}>
            <StepLabel>FOO</StepLabel>
          </Step>
          <Step key={1}>
            <StepLabel> bar </StepLabel>
          </Step>
        </Stepper>

          {activeStep === this.getNumberOfSteps() ? (

              <Typography className={classes.instructions}>
                All steps completed - you"re finished
              </Typography>
              <Button onClick={this.handleReset} className={classes.button}>
                Reset
              </Button>

          ) : (

              {
                // Populate the content pane based on the active step
                this.getStepContent(activeStep)
              }

                <Button
                  disabled={activeStep === 0}
                  onClick={this.handleBack}
                  className={classes.button}
                >
                  Back
                </Button>
                <Button
                  variant="raised"
                  color="primary"
                  onClick={this.handleNext}
                  className={classes.button}
                >
                    {activeStep === this.getNumberOfSteps() - 1 ? 'Finish' : 'Next'}
                </Button>

          )}

    );
  }
}

You can see a full working example here.

A: It is possible to insert HTML within the MUI's Stepper, however it is important to note that the this process is confined by the limitations of Material-UI - namely that you can't directly apply HTML as a child of Step. Given the example in the docs:
<Stepper linear={false}>
   <Step completed={visited.indexOf(0) !== -1} active={stepIndex === 0}>
      <StepButton onClick={() => this.setState({stepIndex: 0})}>
          Select campaign settings
      </StepButton>
   </Step>
   <Step completed={visited.indexOf(1) !== -1} active={stepIndex === 1}>
     <StepButton onClick={() => this.setState({stepIndex: 1})}>
        Create an ad group
      </StepButton>
    </Step>
  </Stepper>

We can simply switch add in a an element to the icon property of the StepButton, thereby overriding the default icon and inserting our own HTML. Please see the JS Fiddle as an example of this:
https://jsfiddle.net/Asalem1/te3yruxz/17/


text:
Q: Disabling interrupt with the ARM GIC (global interrupt controller) I have a specific requirement where I nee to disable my device interrupt for specific period without affecting other interrupts(code running on ARM processor). ARM document pointed that all GIC registers (related to enable, disable and clear interrupts) of ARM are Banked registers, that is there is one per CPU Interface. Banked registers accessible from the designated CPU and controls that CPU's PPI and SGI interrupts only.
What does that mean? If I disable a specific interrupt by writing to GIC register, does that get disabled only on that core or all on cores?

A: There are two register sets with the GIC; a banked per CPU set and the distribution (also distributor) which is system global for the GIC.  For the link above, the IrqEnSet0 is a per-CPU register which is banked (again) and handles the PPI and SGI interrupts to a CPU.  The IrqEnSet1 is a list of global interrupts and these maybe disable.  The distribution (also distributor) can also target certain interrupts to a CPU.
ARM has many different names for these registers and different versions of the GIC.  The concepts are the same for all of them.  There is a set of registers that are not banked per-CPU and these control things globally including disabling the interrupts system wide.  Hopefully the reader is competent enough to find and read the specific controller documentation for their SOC.

What does that mean? If I disable a specific interrupt by writing to GIC register, does that get disabled only on that core or all on cores?

*

*PPI - peripheral private interrupt.  For example, a per-CPU timer in SMP systems.

*SGI - software generated interrupt.  Also known as IPI on other systems.  This allows signaling from one CPU to another CPU. (IPI is inter-processor interrupt).

These interrupts only make sense for each and every CPU.  However, hardware like Ethernet, SPI, Video, CAN bus, i2c, ADC, etc. are usually system global.
For the distributor registers, usually the global interrupts have a read/write enable/disable.  The registers for the per-CPU are probably read-only in the distributor and indicate that the interrupt is present.  The other set of registers (per-CPU) are the normal mechanism to enable/disable the interrupt per-CPU.  Software should have an inter-lock (semaphore) when accessing the distributor as it is global to the system.  Alternatively, only an elected or boot CPU would use the distributor. The per-CPU registers are banked so a core may perform a read-modify-write without worrying about race conditions.
Reference: ARM Generic Interrupt Controller - Architecture Specification, may require registration.


text:
Q: Live Stream for windows mobile app I am new to windows mobile application development. I want to develop an application to play live stream on Windows mobile devices. I have both formats HLS(.m3u8) and RTMP of streams available. Please guide me to some useful player for integration open source preferably (if available)
Thanks

A: You might find this project helpful to get HLS running on Windows Phone. If you really mean Windows Mobile, which is deprecated, you probably would need to use the libav libraries.
RTMP is terrible, try to forget that it exists.

A: Player Framework: an open source media player framework for Windows and Windows Phone
http://playerframework.codeplex.com/


text:
Q: Simulate ArgumentParser object within Python I have a function (from some external module) that takes an ArgumentParser object (from the argparse module) . The function is external and I cannot change its code.
edit: the function actually takes a Namespace object which is the output of the ArgumentParser.parse_args function
I need to call the function from within Python and not from the shell, therefore I need to recreate the ArgumentParser object somehow. Assume I have a dictionary with the same keys as the necessary attributes.
I tried to create an Struct with the same attributes like so:
class Args:
    def __init__(self, **kwargs):
        self.__dict__.update(kwargs)

cfg = {'attrib': 'abc', 'path': "input/path"}
args = Args(**cfg)

# 1st option
f(args) # Error: argument of type 'Args' is not iterable
# 2nd option
f(cfg) # Error: 'dict' object has no attribute 'attrib'

but this fails when trying something like if 'attrib' in struct with an error of "argument of type 'Args' is not iterable" (1st option)
On the other hand, if I try to pass a dictionary to the function, I get an error when it tries to access it with args.attrib (2nd option)
How can I generate something that will be compatible with ArgumentParser?

A: ArgumentParser.parse_args just returns an argparse.Namespace object with arbitrary attributes. To imitate that, just instantiate that yourself and set your attributes on it:
import argparse

args = argparse.Namespace()
args.attrib = 'abc'
args.path = 'input/path'

f(args)

To convert an existing dict to such a Namespace object, something like this'll do:
>>> from functools import reduce
>>> reduce(lambda n, i: setattr(n, *i) or n, cfg.items(), argparse.Namespace())
Namespace(attrib='abc', path='input/path')

Or, it even appears to support constructor arguments:
args = argparse.Namespace(**cfg)


text:
Q: F# Beginner: retrieving an array of data from a server I'm trying to grab data from a MySQL database.
Approach 2 - apply/map style
I'm using the MySQL ADO Reference to try to build this system. In particular, the example found at 21.2.3.1.7.
(using a pseudo code)
let table = build_sequence(query.read)

Where query.read returns a row in the table(Or rather, a list of elements that happen to be a row in the table). And the table variable is a list of lists that will represent a table returned from the query.
I've stared at the code given below, and it's syntax is over my head, I'm afraid.
Approach 1 - looping.
Problem 1: It's inelegant, requiring a mutable.
Problem 2: This just feels wrong, based on my prior experience with Prolog & Lisp. There's gotta be a more...functional way to do this.
I'm not sure where to begin though. Comments & thoughts?
let reader : MySql.Data.MySqlClient.MySqlDataReader = command.ExecuteReader()

let arr = []

let mutable rowIter = 0
let readingLoop() =
    while(reader.Read()) do
        rowIter = rowIter + 1
        for i = 0 to reader.FieldCount do

            //set arr[someiterator, i] = reader.GetValue[i].ToString())

A: It can be hard to work with imperative APIs in a non-imperative way.  I don't have MySql handy, but I made an approxmiation, hopefully this will provide inspiration.  Seq.unfold is a function people find pretty awesome once they grok it.  List.init (or Array.init) are also handy for initializing known-size data structures without using mutables.
#light

type ThingLikeSqlReader() =
    let mutable rowNum = 0
    member this.Read() =
        if rowNum > 3 then
            false
        else
            rowNum <- rowNum + 1
            true
    member this.FieldCount = 5
    member this.GetValue(i) = i + 1

let reader = new ThingLikeSqlReader()
let data = reader |> Seq.unfold (fun (reader : ThingLikeSqlReader) ->
    if reader.Read() then
        Some (List.init reader.FieldCount (fun i -> reader.GetValue(i)), reader)
    else
        None) |> Seq.to_list
printfn "%A" data

A: The Seq type has a neat function for handling database cursors called generate_using (see F# Manual and the Data Access chapter in Foundations of F#). This is a higher order function that takes one function to open the cursor and another (called repeatedly) to process records from the cursor. Here is some code that uses generate_using to execute a sql query:
let openConnection (connectionName : string) =
    let connectionSetting = ConfigurationManager.ConnectionStrings.Item(connectionName)
    let connectionString = connectionSetting.ConnectionString
    let connection = new OracleConnection(connectionString)
    connection.Open()
    connection

let generator<'a> (reader : IDataReader) =
    if reader.Read() then
        let t = typeof<'a>
        let props = t.GetProperties()
        let types = props
                    |> Seq.map (fun x -> x.PropertyType)
                    |> Seq.to_array
        let cstr = t.GetConstructor(types)
        let values = Array.create reader.FieldCount (new obj())
        reader.GetValues(values) |> ignore
        let values = values
                     |> Array.map (fun x -> match x with | :? DBNull -> null | _ -> x)
        Some (cstr.Invoke(values) :?> 'a)
    else
        None

let executeSqlReader<'a> (connectionName : string) (sql : string) : 'a list =
    let connection = openConnection connectionName

    let opener() =
        let command = connection.CreateCommand(CommandText = sql, CommandType = CommandType.Text)
        command.ExecuteReader()

    let result = Seq.to_list(Seq.generate_using opener generator)

    connection.Close()
    connection.Dispose()
    result

For example to list all the tables in an Oracle database we need to define a column definition type and invoke executeSqlReader as follows:
type ColumnDefinition = {
    TableName : string;
    ColumnName : string;
    DataType : string;
    DataLength : decimal;
}

let tableList = executeSqlReader<ColumnDefinition>
    "MyDatabase"
    "SELECT t.table_name, column_name, data_type, data_length FROM USER_TABLES t, USER_TAB_COLUMNS c where t.TABLE_NAME = c.table_name order by t.table_name, c.COLUMN_NAME"


text:
Q: FINDSTR RegEx assistance? I'm processing the output from an SVNLOOK command. All the lines returned start with A, U or D. I need to find all the rows that do NOT start with "D". What's the Regex pattern for this? I tried ^[^D] (starting with, not "D") but that doesn't work. If you want to test the following test data
FILEA.txt:
A file1.txt
U file2.txt
D file3.txt
The output of "FINDSTR pattern FILEA.txt" needs to be only the lines that DON'T start with "D", so the A and the U.
ANy help is greatly appreciated.

A: It should work if you wrap the pattern in quotes:
findstr "^[^D]" filea.txt

Another option is to use -v to reverse the match:
findstr -v "^D" filea.txt

A: A little more detail. The Regex was for a FINDSTR in a BAT file. I originally was using "^[^D]" but just realized that I need to "escape" the carats. I changed it to "^^[^^D]" and now it works.


text:
Q: Why does my object created with "new" not exist out of scope? Hi and sorry for this propably incredibly stupid question - complete C++ beginner here..
I understood that creating objects with the "new" operator creates them on the heap and that they therefor should be global, right?
I tried this with this code, but end up getting an error, that I read as "out of scope" - what am I not seeing here, guys?
int main()
{
    bool mainLoop = true;
    do
    {
        string userInput1, userInput2;
        cout << endl << "Please enter a new recipe, or press X to quit: " << endl << endl;
        cin >> userInput1;
        if (userInput1 != "x")
        {
            cout << endl << "Please enter the recipes description: " << endl << endl;
            cin >> userInput2;
            Recipe *gulasch1 = new Recipe (userInput1, userInput2);
            gulasch1->speak(); // this is just to try out if this outputs anything, and it does
        }
        else
        {
            cout << "Thanks and goodbye!" << endl;
            mainLoop = false;
        }
    } while (mainLoop == true);

    gulasch1->speak(); // why does this throw an error? ('gulasch1': undeclared identifier)

    return 0;
}

Sorry if this is duplicate (I imagine it has to be, but I couldn't find anything that answered my question.
Thanks for the help, guys!

A: You are conflating two different objects. gulasch1 is a pointer. It points at a dynamically allocated object, yes. But gulasch1 itself is a separate object that has block scope.
If you want it available in the scope of main after the loop, define it before the loop, and turn the initialization inside the loop into assignment.

A: The variable gulasch1 is only in the scope of the if statement so it can't be used outside. What you have here is a compilation issue - nothing to do with heap vs stack. Yes the actual Recipe is on the heap and (if it compiled) would still be there after the while loop, but you have no variable pointing to it.

A: The object Recipe that you point to exists outside of the scope you created it in because you made that object on the free store (heap) using new.
But the pointer Recipe* pointing to it (gulasch1) only exists in the scope you created it in, because you made it an automatic (stack) variable.


text:
Q: Upon logging into sqlplus why does it always print the username? Upon logging into sqlplus why does it always print the username in linux?
$ sqlplus

SQL*Plus: Release 11.2.0.4.0 Production on Fri Apr 7 06:32:57 2017

Copyright (c) 1982, 2013, Oracle.  All rights reserved.

Enter user-name: scott

Enter password:

Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.4.0 - 64bit Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options

USER is "SCOTT"

I don't want to print that the "USER is "SCOTT" ".
One clue is that the message "USER is", I can see it in
/software/oracle/cli-11.02.00.04/sqlplus/mesg/sp2us.msg

 sqlplus/mesg/sp2us.msg:572:00291,0, "USER is \"%s\"\n"

do I need to change any settings somewhere?

A: That's not default SQL*Plus behavior. So you probably have a SHOW USER command (which does it) in your personal login.sql or the global glogin.sql files.
Have a look in your $ORACLE_HOME/sqlplus/admin sub-directory for the glogin.sql file.
login.sql can be in any directory in the $SQLPATH, but SQL*Plus starts its search in the current directory. So with luck the file will be in somewhere sensible such as your client $ORACLE_HOME.
SQL*PLus configuration is covered in the documentation. Find out more.

"in /upapps/oracle/dba/tools/login.sql ... there is show user command ... so is that the reason? "

Yep. SQL*Plus  runs login.sql every time we connect, for instance to use SET SQLPROMPT to change the prompt. Having SCOTT> as your prompt is probably more useful than showing the user you've just connected as.

" can I override login.sql and glogin.sql so that everytime I connect to sqlplus it will execute my login.sql and glogin.sql?"

You can't override glogin.sql because there is only one of them (g is for "global"). But there can multiple versions of login.sql. As I said above, SQL*Plus starts its search for the file in the current directory. So you need to create a login.sql file in a location where you have write privileges (e.g. $HOME/naren) and then always start SQL*Plus from there.

" is there any way we can acheive this even when we run from different folder? "

If you can't write a file where you start SQL*Plus and you can't start SQL*Plus where you can write a file it becomes a political problem not a technical problem. You need to negotiate with the people who administer your Oracle environment.
Or just learn to live with it. This is a fairly trivial thing; I can't believe I've put so much time and energy into this topic :) So if show user is the greatest annoyance in your working day you should count your blessings.


text:
Q: ios Any idea how to create a field like the "To:" sms or email field? Does anyone know how to create a field like the "To:" sms or email field?
Thanks

A: Try these:
http://www.cocoacontrols.com/platforms/ios/controls/titokenfield
http://www.cocoacontrols.com/platforms/ios/controls/jstokenfield
http://www.cocoacontrols.com/platforms/ios/controls/copeoplepickerviewcontroller
I haven't tried them myself yet, but the ratings look good.


text:
Q: What does Pardot API version 4 read by email response look like? The Pardot API version 4 response for "using prospects" operations looks the same as in version 3.
http://developer.pardot.com/kb/api-version-4/prospects/#xml-response-formats
http://developer.pardot.com/kb/api-version-3/prospects/#xml-response-formats
But version 4 may or may not return multiple prospects for some operations, since multiple prospects can now have the same email address.
I'm wondering what a JSON response looks like if you do a read by email like described in the documentation:
/api/prospect/version/4/do/read/email/<email>
And if one prospect is returned vs multiple prospects, how the response differs.