text:
Q: Android Studio exception in plugin Google Login "'userEmail' of com/google/gct/login/CredentialedUserRoster.setActiveUser must not be null" Using Android Studio 1.2.1.1.  When clicking the login icon (top right) I get this exception.
Argument for @NotNull parameter 'userEmail' of com/google/gct/login/CredentialedUserRoster.setActiveUser must not be null
java.lang.IllegalArgumentException: Argument for @NotNull parameter 'userEmail' of com/google/gct/login/CredentialedUserRoster.setActiveUser must not be null
    at com.google.gct.login.CredentialedUserRoster.setActiveUser(CredentialedUserRoster.java)
    at com.google.gct.login.GoogleLogin.setActiveUser(GoogleLogin.java:454)
    at com.google.gct.login.ui.GoogleLoginUsersPanel.valueChanged(GoogleLoginUsersPanel.java:232)
    at javax.swing.JList.fireSelectionValueChanged(JList.java:1798)
    at javax.swing.JList$ListSelectionHandler.valueChanged(JList.java:1812)
    at javax.swing.DefaultListSelectionModel.fireValueChanged(DefaultListSelectionModel.java:184)
    at javax.swing.DefaultListSelectionModel.fireValueChanged(DefaultListSelectionModel.java:154)
    at javax.swing.DefaultListSelectionModel.setValueIsAdjusting(DefaultListSelectionModel.java:685)
    at javax.swing.JList.setValueIsAdjusting(JList.java:2142)
    at javax.swing.plaf.basic.BasicListUI$Handler.mouseReleased(BasicListUI.java:2796)
    at java.awt.AWTEventMulticaster.mouseReleased(AWTEventMulticaster.java:290)
    at java.awt.AWTEventMulticaster.mouseReleased(AWTEventMulticaster.java:289)
    at java.awt.AWTEventMulticaster.mouseReleased(AWTEventMulticaster.java:289)
    at java.awt.AWTEventMulticaster.mouseReleased(AWTEventMulticaster.java:289)
    at java.awt.Component.processMouseEvent(Component.java:6516)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
    at java.awt.Component.processEvent(Component.java:6281)
    at java.awt.Container.processEvent(Container.java:2229)
    at java.awt.Component.dispatchEventImpl(Component.java:4872)
    at java.awt.Container.dispatchEventImpl(Container.java:2287)
    at java.awt.Component.dispatchEvent(Component.java:4698)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
    at java.awt.Container.dispatchEventImpl(Container.java:2273)
    at java.awt.Window.dispatchEventImpl(Window.java:2719)
    at java.awt.Component.dispatchEvent(Component.java:4698)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:747)
    at java.awt.EventQueue.access$300(EventQueue.java:103)
    at java.awt.EventQueue$3.run(EventQueue.java:706)
    at java.awt.EventQueue$3.run(EventQueue.java:704)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
    at java.awt.EventQueue$4.run(EventQueue.java:720)
    at java.awt.EventQueue$4.run(EventQueue.java:718)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:717)
    at com.intellij.ide.IdeEventQueue.defaultDispatchEvent(IdeEventQueue.java:734)
    at com.intellij.ide.IdeEventQueue._dispatchEvent(IdeEventQueue.java:565)
    at com.intellij.ide.IdeEventQueue.dispatchEvent(IdeEventQueue.java:382)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)

I have tried to fix it by doing the following (no success):

*

*rebooting my computer.

*reinstalling Android Studio

*following the suggested solution in   Google sign in issue.  I have revoked access to everything related to Android, Android Studio and the SDKs.

*disabling and re-enabling the "Google Login" plugin

How can this be fixed?  Or where should I look for this missing 'userEmail' parameter?
The same problem manifest in a different exception when I try to deploy my module to app engine:
Exception loading projects for null: 400 Bad Request
{
  "error" : "invalid_grant",
  "error_description" : "Token has been revoked."
}
com.google.api.client.auth.oauth2.TokenResponseException: 400 Bad Request
{
  "error" : "invalid_grant",
  "error_description" : "Token has been revoked."
}
at com.google.api.client.auth.oauth2.TokenResponseException.from(TokenResponseException.java:105)
at com.google.api.client.auth.oauth2.TokenRequest.executeUnparsed(TokenRequest.java:287)
at com.google.api.client.auth.oauth2.TokenRequest.execute(TokenRequest.java:307)
at com.google.api.client.auth.oauth2.Credential.executeRefreshToken(Credential.java:570)
at com.google.api.client.googleapis.auth.oauth2.GoogleCredential.executeRefreshToken(GoogleCredential.java:247)
at com.google.api.client.auth.oauth2.Credential.refreshToken(Credential.java:489)
at com.google.api.client.auth.oauth2.Credential.intercept(Credential.java:217)
at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:859)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:410)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:343)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:460)
at com.google.gct.idea.elysium.GoogleUserModelItem.loadUserProjects(GoogleUserModelItem.java:130)
at com.google.gct.idea.elysium.GoogleUserModelItem.access$100(GoogleUserModelItem.java:41)
at com.google.gct.idea.elysium.GoogleUserModelItem$1.run(GoogleUserModelItem.java:95)
at com.intellij.openapi.application.impl.ApplicationImpl$8.run(ApplicationImpl.java:405)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
at org.jetbrains.ide.PooledThreadExecutor$1$1.run(PooledThreadExecutor.java:56)

Note that this problem is not solved by the suggested solution in   Google sign in issue.  That solution suggests going to https://security.google.com/settings/security/permissions?pli=1 and revoking application access.  I have allowed no access related to Android, Android Studio and the SDKs.  Other applications running on my PC, like Chrome, can log in without issue.

A: This problem was a bug in Android Studio.  It disappeared when I upgraded to the latest "canary channel" version.  See http://tools.android.com/recent/androidstudio12beta3available to see what was fixed.  FYI the version that works for me is:
Android Studio AI-141.1962279
Build #AI-141.1962279, built on May 27, 2015
JRE: 1.7.0_79-b15 amd64
JVM: Java HotSpot(TM) 64-Bit Server VM by Oracle Corporation


text:
Q: Is there a better way to see MySql statements with parameters in C# using Visual Studios debugger? I have recently been changing some C# programs to add proper parameterizing to some MySQL statements that had originally been written with concatenated strings. Invariably, I've run into some problems with my statements and I can't find a way to directly see the complete MySQL statement with parameters applied other than this workaround that I have where I pass the MySQL command to this:
private string getMySqlStatement(MySqlCommand cmd)
{
    string result = cmd.CommandText.ToString();
    foreach (MySqlParameter p in cmd.Parameters)
    {
        string addQuote = (p.Value is string) ? "'" : "";
        result = result.Replace(p.ParameterName.ToString(), addQuote + p.Value.ToString() + addQuote);
    }
    return result;
}

This works, but I was wondering if there was a more proper way to see the full statement with parameters applied. Reading up on this, it looks like the parameters aren't actually applied until it reaches the server - is this correct? In that case, I suppose I can stick to my function above, but I just wanted to know if there was a better way to do it.
Note: I am just using this function for debugging purposes so I can see the MySQL statement.

A: MySQL supports two protocols for client/server communication: text and binary. In the text protocol, there is no support for command parameters in the protocol itself; they are simulated by the client library. With Connector/NET, the text protocol is always used, unless you set IgnorePrepare=true in the connection string and call MySqlCommand.Prepare() for each command. So it's most likely the case that you are using the text protocol. This is good, because it will be easier to log the actual statements with parameters applied.
There are three ways to view the statements being executed:
Use Connector/NET Logging
Add Logging=true to your connection string and create a TraceListener that listens for the QueryOpened event. This should contain the full SQL statement with parameters interpolated. Instructions on setting this up are here.
Use MySQL Server Logging
Enable the general query log on your server to see all queries that are being executed. This is done with the --general_log=1 --general_log_file=/var/path/to/file server options.
Packet Sniffing
If you're not using SslMode=Required (to encrypt the connection between client and server), then you can use WireShark to capture network traffic between your client and the server. WireShark has MySQL Protocol analysers that will inspect MySQL traffic and identify command packets (that contain SQL queries). This option is ideal if you aren't able to modify your client program nor change server logging settings.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Configuring 2017 SQL Server SSISDB Server-wide Default Logging Level does not seem to work Using SSMS, I have changed the SSIS Catalog Logging Level from Basic to Performance to a Custom Logging Level in a 2017 SQL Server Instance and then I run the report: "All Executions".  It doesn't seem to matter what Logging Level I am at, the amount of data/detail that is included in the SSIS Catalog Report remains the same.  I would think the amount of detail would change with each Logging Level.
If the SSIS Catalog Reports do not change when the Logging Level changes, then how do I see the changes to the Logging Levels?  Otherwise, if the SSIS Catalog Reports are suppose change, can someone please point me in the correct path to get the SSIS Catalog Reports to change?

A: As BCM indicates, that default will apply to new executions. Your job in SQL Agent likely has the earlier default level baked into the execution and so it's overriding the system default. In the Advanced properties, you'd switch it to the new value.
When you manually run a job, this is the syntax of the steps it takes (agent job does the same behind the scenes)
DECLARE @execution_id bigint;

EXEC SSISDB.catalog.create_execution
    @package_name = N'Package.dtsx'
,   @execution_id = @execution_id OUTPUT
,   @folder_name = N'FolderName'
,   @project_name = N'ProjectName'
,   @use32bitruntime = False
,   @reference_id = NULL;

SELECT
    @execution_id;

-- 0 = None
-- 1 = Basic
-- 2 = Performance
-- 3 = Verbose
-- 4 = Runtime Lineage
-- 100 = Custom
DECLARE @var0 smallint = 1;

EXEC SSISDB.catalog.set_execution_parameter_value
    @execution_id
,   @object_type = 50
,   @parameter_name = N'LOGGING_LEVEL'
,   @parameter_value = @var0;

EXEC SSISDB.catalog.start_execution
    @execution_id;
GO

If you use the custom/ 100 logging value, then you also need to specify what custom logging level you want to use. Assuming I created a log level called "New Custom Logging Level", I'd add set this parameter before invoking start_execution
DECLARE @logLevelName SQL_VARIANT = N'New Custom Logging Level'
EXEC [SSISDB].[catalog].[set_execution_parameter_value]
    @execution_id
,   @object_type = 50
,   @parameter_name = N'CUSTOMIZED_LOGGING_LEVEL'
,   @parameter_value = @logLevelName;

MSDN set_execution_parameter_value
Tim Mitchell has a good article on setting the execution parameter values


text:
Q: Atom is not neutral? The thing that always confused me, was how can atom be electrically neutral, if electrons are closer to observer. Well, okay, I started to read a quantum mechanics book, so to clarify: there is a big probability, that electrons will be closer. First, I imagined electric field as a finite sphere, but then, I understood, that it is infinite respectly to scales, hence, nucleou's and electron's fields canceles each other. But then I again understood, that density decreases with distance, hence the field near electron, and hence atom, should be negative.

A: For the purposes of this discussion, let's think of the atom as a positively-charged point surrounded by a negatively-charged cloud. The total charge of the negatively-charged cloud is equal to the total charge of the positively-charged point. This question can be answered entirely within the realm of classical electromagnetism.
An atom looks the same from every direction; we say that it has spherical symmetry. Because of this, the electric field should also look the same from every direction. This pretty strictly restricts the behavior of the electric field; because of this symmetry, the electric field can only depend on the distance from the atom, and it can only point either directly toward or directly away from the atom. Therefore, the electric field should look the same at every point on a sphere centered on the atom.
This fact is important because of a particular fact of electromagnetism: Gauss's Law, which says that the total electric field poking through a surface is dependent only on the total charge contained by that surface. Let's choose any sphere with a radius larger than the radius of the atom. The total charge contained in this sphere is zero (the positive and negative charges are the same magnitude, as we said in the beginning). This means that the net electric field poking through the surface is also zero. Ordinarily, this wouldn't tell us much; after all, there are lots of ways for an arbitrary electric field to have a net flux (amount poking through a surface) of zero; for example, half of the surface could have the electric field pointing outward and half could have the electric field pointing inward at the same magnitude. But we don't have an arbitrary electric field; our electric field is limited by the symmetry we talked about. It must look the same at every point on this sphere, and, as part of this, it must either point outwards everywhere or point inwards everywhere on the sphere. The only way to have zero net flux under these conditions is for the electric field to be zero everywhere on the sphere. Since the radius of the sphere didn't matter at all in these calculations, the electric field is zero at a sphere of any radius larger than the radius of the atom; therefore, the electric field is zero everywhere outside the atom. This type of argument is called an "argument by symmetry," and it occurs quite often in physics.
Intuitively, you can justify this by noting that, although part of the electron cloud is closer to an observer than the nucleus of the atom, there is also part of the electron cloud that is further away from the observer than the nucleus. It turns out that these two effects cancel. If your objection is that the electron is a point particle and can't be in two places at once, this is where quantum mechanics becomes important. In quantum mechanics, the electron is not a point particle; rather, it exists as a distribution over space. The "electron cloud" analogy is not perfect (for example, it does not imply that the electron's probability distribution maps directly to a charge distribution), but the arguments from symmetry still apply. We know that there's an electron somewhere in the atom, and we know that the atom is observed to be spherically symmetric, and that's all we need to complete the argument.

A: It is a property of the $1/r^2$ force law that charges display that any spherically symmetric charge density will appear to an outside observer as if all of that charge were located at a point in the center. If the density is "hollow" (zero from the center until some radius) so that there are also "inside observers" possible, it turns out that for them the force cancels out completely. You can use superposition to work out any other spherically symmetric charge distribution. A classic example is the uniformly charged sphere of total charge $Q$ where if you are inside of one, you can imagine a superposition of the charge at smaller radius and the charge at larger radius. The latter sees you in a hollow and thus exerts no net force on you after it is all added up; the former sphere has volume proportional to $r^3$ hence charge $Q r^3/R^3$ which acts on you as if it is concentrated at the center, so the field inside the sphere is $$E = \frac{kQr}{R^3}\hat r.$$
Many atoms have a spherically symmetric charge distribution for their electrons. This is a strange aspect of quantum mechanics, it allows for particles to be distributed over space. But this means that outside of the atom, when you shrink all of the charge to a point at the center of the sphere, you just get the number of protons minus the number of electrons. If those two are the same number, then you must not feel any force: the protons at the center must be perfectly canceled out by the electrons distributed around the shell.
Of course some atoms get together in other ways, like in the water molecule, the oxygen atom pulls electrons to it more strongly than the hydrogen atoms can hold, and those hydrogen atoms do not lineup on opposite sides, so there is no symmetry to the situation, and we would say that water has a small dipole moment, which is why ionic things like salt dissolve very readily in water, while more electrically neutral things like oil do not.

A: We can simplify your question by considering an electric dipole, which has $0$ overall charge but non-zero field.  On average, in the case of an atom with one positive and one negative charge, there is no reason to think that an electron would be more often on one side of the nucleus rather than the other, and this is certainly true if one thinks of electrons as circulating on orbits in the simplified pictures of the Bohr model.  If you have many electrons on multiple orbits in different planes, that would be even "truer" in this simplified picture.
Moreover, the field of a dipole decreases quite rapidly (along the axis of the dipole like $1/r^3$) so that, qualitatively at least, it's reasonable to consider the field to be $0$ unless you are interested in the field at very short distances or for very short times.


text:
Q: Android 4.4 remove shadow from CardView I tried to remove the shadow from the Cardview.
I used android support v7 Cardview on android v4.4.2
My layout look:
<android.support.v7.widget.CardView
    android:id="@+id/cardContainer"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@null"
    card_view:cardBackgroundColor="@color/transparent"
    card_view:cardCornerRadius="0dp"
    card_view:cardElevation="0dp"
    card_view:cardPreventCornerOverlap="false"
    card_view:contentPadding="0dp">

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

        <include layout="@layout/include_profile_header" />

        <include layout="@layout/include_profile_footer" />

    </RelativeLayout>

</android.support.v7.widget.CardView>

As you can see i used:
  card_view:cardElevation="0dp"

Tried so far:
android:background="@null"

But still you can see in the image i attached the top shadow that showed.

A: Just add below code to cardview tag

app:cardElevation="0dp"

and don't forget to add

xmlns:app="http://schemas.android.com/apk/res-auto"

UPDATE
Also try this put below codes in cardview
app:cardElevation="0dp"
app:cardMaxElevation="0dp"
app:cardCornerRadius="1dp"
app:cardUseCompatPadding="true"
app:cardPreventCornerOverlap="false"
android:background="@null"

The app:cardCornerRadius should be bigger than 0(>0) otherwise throw exception
I'm using API 28 support library

implementation 'com.android.support:cardview-v7:28.0.0'

A: You cannot remove the shadow from the cardview in 4.4. Anything below 5.0 elevation does nothing so all the cardview is in 4.4 is an image with a shadow

To create a card with a shadow, use the card_view:cardElevation
  attribute. CardView uses real elevation and dynamic shadows on Android
  5.0 (API level 21) and above and falls back to a programmatic shadow implementation on earlier versions. For more information, see
  Maintaining Compatibility.

http://developer.android.com/training/material/lists-cards.html#CardView

A: I just fixed this problem by using a relative layout instead. Simply change the CardView value to a relative layout and you will essentially get the same result, but without the shadow


text:
Q: .htaccess is not working in users' public_html directories I followed a tutorial: http://www.techytalk.info/enable-userdir-apache-module-ubuntu-debian-based-linux-distributions/
but .htaccess is not overriding Apache's configuration. May be "AllowOverride All" in userdir.conf is not working for users' public_html directories.
Here is my userdir.conf of Apache:
<IfModule mod_userdir.c>
    UserDir public_html www/public_html
    UserDir disabled root

    <Directory /home/*/www/public_html>
    AllowOverride All
    Options MultiViews Indexes SymLinksIfOwnerMatch
    <Limit GET POST OPTIONS>
        # Apache <= 2.2:
            Order allow,deny
            Allow from all

            # Apache >= 2.4:
            #Require all granted
    </Limit>
    <LimitExcept GET POST OPTIONS>
        # Apache <= 2.2:
            Order deny,allow
            Deny from all

        # Apache >= 2.4:
        #Require all denied
    </LimitExcept>
    </Directory>
</IfModule>


text:
Q: Can I create varying number of component based on length of array? Suppose I want to create number of components based on the length of the array which props from the parent component.
<template>
  <------here is some logic to toggle "ComponentName"------->
 <keep-alive>
      <component v-bind:is="ComponentName"></component>
 </keep-alive>
</template>
<script>
export default {
  components: {},
  methods: {
  createComponents: function(){
     for (let i = 0; i < this.MyArray.length;i++){
        ----Create component with name "Component-i" and based on the content in MyArray----
}
}
}
  data(){
      return{
          MyArray: this.$route.params.MyArray,
          ComponentName: '',
      },
  }
}
</script>

Is there are any way to do so? I mean, to create dynamic number of component?


text:
Q: What is so bad with goto when it's used for these obvious and relevant cases? I have always known that goto is something bad, locked in a basement somewhere never to be seen for good but I ran into a code example today that makes perfect sense to use goto.
I have an IP where I need to check if is within a list of IPs and then proceed with the code, otherwise throw an exception.
<?php

$ip = '192.168.1.5';
$ips = [
    '192.168.1.3',
    '192.168.1.4',
    '192.168.1.5',
];

foreach ($ips as $i) {
    if ($ip === $i) {
        goto allowed;
    }
}

throw new Exception('Not allowed');

allowed:

...

If I don't use goto then I have to use some variable like
$allowed = false;

foreach ($ips as $i) {
    if ($ip === $i) {
        $allowed = true;
        break;
    }
}

if (!$allowed) {
    throw new Exception('Not allowed');
}

My question is what's so bad with goto when it's used for such obvious and imo relevant cases?

A: GOTO is a tool. It can be used for good or for evil.
In the bad old days, with FORTRAN and BASIC, it was almost the only tool.
When looking at code from those days, when you see a GOTO you have to figure out why it is there.  It can be part of a standard idiom that you can understand quickly... or it can be part of some nightmarish control structure that should never have been.  You don't know until you have looked, and it is easy to be mistaken.
People wanted something better, and more advanced control structures was invented.  These covered most of the use cases, and people who were burned by bad GOTOs wanted to completely ban them.
Ironically, GOTO isn't so bad when it is rare.  When you see one, you know there is something special going on, and it is easy to find the corresponding label since it is the only label nearby.
Fast forward to today.  You are a lecturer teaching programming.  You could say "In most cases you should use the advanced new constructs, but in some cases a simple GOTO can be more readable."  Students are not going to understand that.  They are going to abuse GOTO to make unreadable code.
Instead you say "GOTO bad. GOTO evil.  GOTO fail exam."  Students will understand that!

A: There are some legitimate use cases for GOTO. For example for error handling and cleanup in C or for implementing some forms of state machines. But this is not one of these cases. The second example is more readable IMHO, but even more readable would be to extract the loop to a separate function and then return when you find a match. Even better would be (in pseudocode, I don't know exact syntax):
if (!in_array($ip, $ips)) throw new Exception('Not allowed');

So what is so bad about GOTO's? Structured programming uses functions and control structures to organize the code so the syntactic structure reflects the logical structure. If something is only conditionally executed, it will appear in a conditional statement block. If something is executed in a loop, it will appear in a loop block. GOTO enables you to circumvent the syntactic structure by jumping around arbitrarily, thereby making the code much harder to follow.
Of course if you have no other choice you use GOTO, but if the same effect can be achieved with functions and control structures, it is preferable.

A: With the exception of goto, all flow constructs in PHP (and  most languages) are scoped hierarchically.
Imagine some code examined through squinted eyes:
a;
foo {
    b;
}
c;

Regardless of what control construct foo is (if, while, etc.), there are only certain allowed orders for a, b, and c.
You could have a-b-c, or a-c, or even a-b-b-b-c. But you could never have b-c or a-b-a-c.
...unless you have goto.
$a = 1;
first:
echo 'a';
if ($a === 1) {
    echo 'b';
    $a = 2;
    goto first;
}
echo 'c';

goto (in particular backwards goto) can be troublesome enough that it's best to just leave it alone, and used hierarchical, blocked flow constructs.
gotos have a place, but mostly as micro-optimizations in low-level languages. IMO, there's no good place for it in PHP.

FYI, the example code can be written even better than either of your suggestions.
if(!in_array($ip, $ips, true)) {
    throw new Exception('Not allowed');
}

A: Nothing wrong with goto statements themselves. The wrongs are with some of the people that inappropriately use the statement.
In addition to what JacquesB said (error handling in C), you are using goto to exit a non-nested loop, something that you can do by using break. In this case you better use break.
But if you had a nested loop scenario, then using goto would be more elegant/simpler.
Bonous point: if your list of IPs is small, your method is fine. But if the list grows, know that your approach has an asymptotic worst run-time complexity of O(n). As your list grows, you may wish to use a different method that achieves O(log n) (such as a tree structure) or O(1) (a hash table with no collisions).

A: In low level languages GOTO is inevitable. But in high level it should be avoided (in the case the language supports it) because it makes programs more difficult to read.
Everything boils down to making the code more difficult to read. High level languages are supossedt o make code easier to read than low level languages like, say, assembler or C.
GOTO doesn't cause global warming nor it causes poverty in the third world. It just makes code more difficult to read.
Most modern languages have control structures that make GOTO unnecessary. Some like Java don't even have it.
In fact, the term spaguetti code comes from convoluted, difficult to follow code causes by unstructured branching structures.

A: As others have said, the problem isn't with the goto itself; the problem is with how people use goto, and how it can make code harder to understand and maintain.
Assume the following snippet of code:
       i = 4;
label: printf( "%d\n", i );

What value gets printed for i?  When does it get printed?  Until you account for every instance of goto label in your function, you can't know.  The simple presence of that label destroys your ability to debug code by simple inspection. For small functions with one or two branches, not much of a problem.  For not-small functions...
Way back in the early '90s we were given a pile of C code that drove a 3d graphical display and told to make it run faster.  It was only about 5000 lines of code, but all of it was in main, and the author used about 15 or so gotos branching in both directions.  This was bad code to begin with, but the presence of those gotos made it so much worse.  It took my co-worker about 2 weeks to puzzle out the flow of control.  Even better, those gotos resulted in code so tightly coupled with itself that we could not make any changes without breaking something.
We tried compiling with level 1 optimization, and the compiler ate up all available RAM, then all available swap, and then panicked the system (which probably had nothing to do with the gotos themselves, but I like throwing that anecdote out there).
In the end, we gave the customer two options - let us rewrite the whole thing from scratch, or buy faster hardware.
They bought faster hardware.
Bode's rules for using goto:

*

*Branch forward only;

*Do not bypass control structures (i.e., do not branch into the body of an if or for or while statement);

*Do not use goto in place of a control structure

There are cases where a goto is the right answer, but they are rare (breaking out of a deeply nested loop is about the only place I'd use it).
EDIT
Expanding on that last statement, here's one of the few valid use cases for goto.  Assume we have the following function:
T ***myalloc( size_t N, size_t M, size_t P )
{
  size_t i, j, k;

  T ***arr = malloc( sizeof *arr * N );
  for ( i = 0; i < N; i ++ )
  {
    arr[i] = malloc( sizeof *arr[i] * M );
    for ( j = 0; j < M; j++ )
    {
      arr[i][j] = malloc( sizeof *arr[i][j] * P );
      for ( k = 0; k < P; k++ )
        arr[i][j][k] = initial_value();
    }
  }
  return arr;
}

Now, we have a problem - what if one of the malloc calls fails midway through?  Unlikely an event as that may be, we don't want to return a partially allocated array, nor do we want to just bail out of the function with an error; we want to clean up after ourselves and deallocate any partially allocated memory.  In a language that throws an exception on a bad alloc, that's fairly straightforward - you just write an exception handler to free up what's already been allocated.
In C, you don't have structured exception handling; you have to check the return value of each malloc call and take the appropriate action.
T ***myalloc( size_t N, size_t M, size_t P )
{
  size_t i, j, k;

  T ***arr = malloc( sizeof *arr * N );
  if ( arr )
  {
    for ( i = 0; i < N; i ++ )
    {
      if ( !(arr[i] = malloc( sizeof *arr[i] * M )) )
        goto cleanup_1;

      for ( j = 0; j < M; j++ )
      {
        if ( !(arr[i][j] = malloc( sizeof *arr[i][j] * P )) )
          goto cleanup_2;

        for ( k = 0; k < P; k++ )
          arr[i][j][k] = initial_value();
      }
    }
  }
  goto done;

  cleanup_2:
    // We failed while allocating arr[i][j]; clean up the previously allocated arr[i][j]
    while ( j-- )
      free( arr[i][j] );
    free( arr[i] );
    // fall through

  cleanup_1:
    // We failed while allocating arr[i]; free up all previously allocated arr[i][j]
    while ( i-- )
    {
      for ( j = 0; j < M; j++ )
        free( arr[i][j] );
      free( arr[i] );
    }

    free( arr );
    arr = NULL;

  done:
    return arr;
}

Can we do this without using goto?  Of course we can - it just requires a little extra bookkeeping (and, in practice, that's the path I'd take).  But, if you're looking for places where using a goto isn't immediately a sign of bad practice or design, this is one of the few.

A: GOTO itself is not an immediate problem, it's the implicit state machines that people tend to implement with it. In your case, you want code that checks whether the IP address is in the list of allowed addresses, hence
if (!contains($ips, $ip)) throw new Exception('Not allowed');

so your code wants to check a condition. The algorithm to implement this check should be of no concern here, in the mental space of your main program the check is atomic. That's how it should be.
But if you put the code that does the check into your main program, you lose that. You introduce mutable state, either explicitly:
$list_contains_ip = undef;        # STATE: we don't know yet

foreach ($ips as $i) {
  if ($ip === $i) {
      $list_contains_ip = true;   # STATE: positive
      break;
  }
                                  # STATE: we still don't know yet, huh?
                                  # Well, then...
  $list_contains_ip = false;      # STATE: negative
}

if (!$list_contains_ip) {
  throw new Exception('Not allowed');
}

where $list_contains_ip is your only state variable, or implicitly:
                             # STATE: unknown
foreach ($ips as $i) {       # What are we checking here anyway?
  if ($ip === $i) {
    goto allowed;            # STATE: positive
  }
                             # STATE: unknown
}
                             # guess this means STATE: negative
throw new Exception('Not allowed');

allowed:                     # Guess we jumped over the trap door

As you see, there's an undeclared state variable in the GOTO construct. That's not a problem per se, but these state variables are like pebbles: carrying one is not hard, carrying a bag full of them will make you sweat. Your code will not stay the same: next month you'll be asked to differentiate between private and public addresses. The month after that, your code will need to support IP ranges. Next year, someone will ask you to support IPv6 addresses. In no time, your code will look like this:
if ($ip =~ /:/) goto IP_V6;
if ($ip =~ /\//) goto IP_RANGE;
if ($ip =~ /^10\./) goto IP_IS_PRIVATE;

foreach ($ips as $i) { ... }

IP_IS_PRIVATE:
   foreach ($ip_priv as $i) { ... }

IP_V6:
   foreach ($ipv6 as $i) { ... }

IP_RANGE:
   # i don't even want to know how you'd implement that

ALLOWED:
   # Wait, is this code even correct?
   # There seems to be a bug in here.

And whoever has to debug that code will curse you and your children.
Dijkstra puts it like this:

The unbridled use of the go to statement has as an immediate consequence that it becomes terribly hard to find a meaningful set of coordinates in which to describe the process progress.

And that's why GOTO is considered harmful.

A: return, break, continue and throw/catch are all essentially gotos--they all transfer control to another piece of code and could all be implemented with gotos--in fact I did so once in a school project, a PASCAL instructor was saying how much better Pascal was than basic because of the structure...so I had to be contrary...
The most important thing about Software Engineering (I'm going to use this term over Coding to refer to a situation where you are being paid by someone to create a codebase together with other engineers that requires ongoing improvement and maintenance) is making code Readable--getting it to do something is almost secondary.  Your code will be written only once but, in most cases, people will spend days and weeks revisiting/relearning, improving and fixing it--and every time they (or you) will have to start from scratch and try to remember/figure out your code.
Most of the features that have been added to languages over the years are to make software more maintainable, not easier to write (although some languages go in that direction--they often cause long-term problems...).
Compared to similar flow control statements, GOTOs can be nearly as easy to follow at their best (A single goto used in a case like you suggest), and a nightmare when abused--and are very easily abused...
So after dealing with spaghetti nightmares for a few years we just said "No", as a community we are not going to accept this--too many people mess it up if given a little leeway--that's really the only problem with them. You could use them... but even if it's the perfect case, the next guy will assume you are a terrible programmer because you don't understand the history of the community.
Many other structures have been developed just to make your code more comprehendible: Functions, Objects, Scoping, Encapsulation, Comments(!)... as well as the more important patterns/processes like "DRY" (preventing duplication) and "YAGNI" (Reducing over-generalization/complication of code)--all really only import for the NEXT guy to read your code (Who will probably be you--after you've forgotten most of what you did in the first place!)

A:
With goto I can write faster code!

True. Don't care.

Goto exists in assembly! They just call it jmp.

True. Don't care.

Goto solves problems more simply.

True. Don't care.

In the hands of a disciplined developer code that uses goto can be easier to read.

True. However, I've been that disciplined coder.  I've seen what happens to code over time.  Goto starts out fine.  Then the urge to reuse code sets in.  Fairly soon I find myself at a breakpoint having no damn clue what's going on even after looking at program state.   Goto makes it hard to reason about code.  We've worked really hard creating while, do while, for, for each switch, subroutines, functions, and more all because doing this stuff with if and goto is hard on the brain.
So no. We don't want to look at goto.  Sure it's alive and well in the binary but we don't need to see that in source.  In fact, if is starting to look a little shaky.

A: Assembly languages typically have only conditional/unconditional jumps (the equivalent of GOTO. Older implementations of FORTRAN and BASIC had no control block statements beyond a counted iteration (the DO loop), leaving all other control flow to IFs and GOTOs. The DO loop in these languages was terminated by a numerically labeled statement. As a result, code written for these languages could be, and often was, hard to follow and prone to mistakes.
To underscore the point, there is the facetiously invented "COME FROM" statement.
There is practically no need to use GOTO in languages like C, C++, C#, PASCAL, Java, etc.; alternative constructions can be used which will almost certainly be just as efficient and far more maintainable. It's true that one GOTO in a source file will not be a problem. The problem is that it doesn't take many to make a unit of code difficult to follow and error-prone to maintain. That's why the accepted wisdom is to avoid GOTO whenever possible.
This wikipedia article on the goto statement might be helpful


text:
Q: I think coxph post estimation with big data - confused about the results I am having trouble understanding if my data is cooked, and how bad, based on post-estimations for coxph. The regression and the cox.zph test is below. Based on the post-estimation, this looks bad because the values are significant and they are very different from 0.
However, I have over 2million observations. And this answer said that sometimes with lots of observations, the post-estimation is just significant because almost everything is statistically significant when you have 2million observations.

On the other hand, with 5001 events it's quite possible to find a
statistically significant non-proportionality that is of little
practical significance. As Therneau and Grambsch put it in Section 6.5
of their book:
A "significant" nonproportionality may make no difference to the
interpretation of a data set, particularly for large sampIe sizes.
They go on to describe a study with 771 events, in which the cox.zph()
test gave significant p values for 2 out of 3 predictors with Global p
= 1.95e-09. This result might be taken to require time-dependent estimates of each coefficient, β^(t), instead of a time-independent
estimate β. Examining plots of scaled Schoenfeld residuals over time,
however, led to the following conclusion about the association between
age and risk of death:
There is a profound effect of age on the risk of death, and the test
shows the effect to be significantly nonproportional. However, the
smoothed residual plot shows that the variation in β^(t) is small
relative to β^.

So these are my results:
Call:
coxph(formula = Surv(matt_tmove_cen, matt_moved_cen) ~ matt_ncdem +
    flood_risk_simple, data = matt_timeadd)

                         coef   exp(coef)    se(coef)        z                      p
matt_ncdem         0.16587990  1.18043132  0.01716598   9.6633 < 0.000000000000000222
flood_risk_simple -0.18664060  0.82974189  0.01646413 -11.3362 < 0.000000000000000222

Likelihood ratio test=132.42  on 2 df, p=< 0.00000000000000022204
n= 2482803, number of events= 281028

matt_sfit0 %>% cox.zph()
                    chisq df            p
matt_ncdem        21.2942  1 0.0000039392
flood_risk_simple 14.0987  1   0.00017347
GLOBAL            21.5385  2 0.0000210366

And here are the graphs I get from the following post-estimation code:
matt_sfit0 %>% cox.zph() %>%  {zph_result <<- .} %>% plot(var=1, resid = TRUE)
matt_sfit0 %>% cox.zph() %>%  {zph_result <<- .} %>% plot(var=2, resid = TRUE)

Making things a bit more complicated, when I turn on the resid option (which I don't actually know what this does), there's this weird split between the variables. I don't know if this is because the variables are binary (?), or really how I'm supposed to interpret all the dots sorting themselves in this way. Would love help interpreting both sets of plots.
matt_sfit0 %>% cox.zph() %>%  {zph_result <<- .} %>% plot(var=1, resid = TRUE)
matt_sfit0 %>% cox.zph() %>%  {zph_result <<- .} %>% plot(var=2, resid = TRUE)

A: The proportional hazards (PH) issue is pretty much a function of your understanding of the underlying subject matter. It's unlikely that the PH assumption ever holds strictly in real-world data, but small-scale data sets don't provide power to detect the violations.
So ask: for flood_risk_simple, is the difference between the minimum coefficient estimate of -0.2 and the maximum of about -0.17, and the apparent trend at later times, large enough to matter in practice? Is the variation of the coefficient for matt_ncdem around its estimate of 0.166 large enough to matter? Only you and your colleagues in the field can answer those questions.
Consider those questions in the context of what your model provides when the PH assumption is violated: "a failure-time weighted average hazard ratio over the duration of follow-up." Is that good enough for your purposes?
With resid = TRUE in your plot, the scaled Schoenfeld residuals are displayed for each event time. With 2 binary predictors you would get the banded pattern that you see. Their values are extremely high, making the underlying trends impossible to see, as those residuals are inversely scaled with respect to the coefficient covariance matrix and you have very small errors in the coefficient estimates.
With large data sets it might make sense to take an approach like that of almost sure hypothesis testing, which tries to account for large sample sizes. That's not standard practice yet, however.


text:
Q: How to cause Windbg to download the compressed versions of MS public symbols Microsoft state here:

The Microsoft Symbol Server provides compressed versions of the symbol
  files. The files have an underscore at the end of the filename's
  extension to indicate that they are compressed. For example, the PDB
  for ntdll.dll is available as ntdll.pd_.

I have 2 questions here:

*

*The more general question: How can I cause Windbg to prefer the compressed version of the symbols? This would result in massive bandwidth savings. (Compressing c:\Symbols on my computer resulted in a 68% reduction in size).
Sniffing the traffic reveals that the uncompressed version is tried first and then the compressed version (underscore at end of name).

*and specific to MS Public Symbols: Are the compressed versions currently available at all? Trying to manually download a compressed versions of ntdll.pdb returns a 404 error.
>$ wget https://msdl.microsoft.com/download/symbols/ntdll.pdb/38A5841BD353770D9C800BF1AF6B17EB1/ntdll.pdb
...
ntdll.pdb                                 100%[=====================================================================================>]   1.46M   406KB/s    in 4.4s
2018-11-11 01:16:56 (341 KB/s) - 'ntdll.pdb' saved [1534976/1534976]

>$ wget https://msdl.microsoft.com/download/symbols/ntdll.pdb/38A5841BD353770D9C800BF1AF6B17EB1/ntdll.pd_
....
HTTP request sent, awaiting response... 404 Not Found
2018-11-11 01:17:01 ERROR 404: Not Found.

Update:
I have now discovered that DbgHelp supports an option called SYMOPT_FAVOR_COMPRESSED which is explained as follows:

If there is both an uncompressed and a compressed file available, favor the compressed file. This option is good for slow connections.

The question now is how to enable this option in Windbg?
This option isn't documented in the officical Windbg documentation and setting it manually seems to only affect the UI level.
0:003> .symopt+ 0x800000
Symbol options are 0x830337:
  0x00000001 - SYMOPT_CASE_INSENSITIVE
  0x00000002 - SYMOPT_UNDNAME
  0x00000004 - SYMOPT_DEFERRED_LOADS
  0x00000010 - SYMOPT_LOAD_LINES
  0x00000020 - SYMOPT_OMAP_FIND_NEAREST
  0x00000100 - SYMOPT_NO_UNQUALIFIED_LOADS
  0x00000200 - SYMOPT_FAIL_CRITICAL_ERRORS
  0x00010000 - SYMOPT_AUTO_PUBLICS
  0x00020000 - SYMOPT_NO_IMAGE_SEARCH
  0x00800000 - SYMOPT_FAVOR_COMPRESSED

However inspecting the traffic using fiddler shows that the uncompressed version is still requested first.


text:
Q: Make multiple asynchronous requests but wait for only one I have a question concerning asynchronous requests. I want to request data from different sources on the web. Each source might have the data I want but I do not know that beforehand. Because I only want that information once, I don't care about the other sources as soon as one source has given me the data I need. How would I go about doing that?
I thought about doing it with a didSet and only setting it once, something like this:

var dogPicture : DogPicture? = nil {
  didSet {
    // Do something with the picture
  }
}

func findPictureOfDog(_ sources) -> DogPicture? {
  for source in sources {
    let task = URL.Session.shared.dataTask(with: source) { (data, response, error) in
      // error handling ...
      if data.isWhatIWanted() && dogPicture == nil {
        dogPicture = data.getPicture()
      }
    }
    task.resume()
  }
}

sources = ["yahoo.com", "google.com", "pinterest.com"]

findPictureOfDog(sources)

However it would be very helpful, if I could just wait until findPictureOfDog() is finished, because depending on if I find something or not, I have to ask the user for more input.
I don't know how I could do it in the above way, because if I don't find anything the didSet will never be called, but I should ask the user for a picture then.
A plus: isWhatIWanted() is rather expensive, so If there was a way to abort the execution of the handler once I found a DogPicture would be great.
I hope I made myself clear and hope someone can help me out with this!
Best regards and thank you for your time

A: A couple of things:

*

*First, we're dealing with asynchronous processes, so you shouldn't return the DogPicture, but rather use completion handler pattern. E.g. rather than:
func findPictureOfDog(_ sources: [String]) -> DogPicture? {
    ...
    return dogPicture
}

You instead would probably do something like:
func findPictureOfDog(_ sources: [String], completion: @escaping (Result<DogPicture, Error>) -> Void) {
    ...
    completion(.success(dogPicture))
}

And you'd call it like:
findPictureOfDog(sources: [String]) { result in
    switch result {
    case .success(let dogPicture): ...
    case .failure(let error): ...
    }
}

// but don't try to access the DogPicture or Error here

*While the above was addressing the "you can't just return value from asynchronous process", the related observations is that you don't want to rely on a property as the trigger to signal when the process is done. All of the "when first process finishes" logic should be in the findPictureOfDog routine, and call the completion handler when it's done.
I would advise against using properties and their observers for this process, because it begs questions about how one synchronizes access to ensure thread-safety, etc. Completion handlers are unambiguous and avoid these secondary issues.

*You mention that isWhatIWanted is computationally expensive. That has two implications:

*

*If it is computationally expensive, then you likely don't want to call that synchronously inside the dataTask(with:completionHandler:) completion handler, because that is a serial queue. Whenever dealing with serial queues (whether main queue, network session serial queue, or any custom serial queue), you often want to get in and out as quickly as possible (so the queue is free to continue processing other tasks).
E.g. Let's imagine that the Google request came in first, but, unbeknownst to you at this point, it doesn't contain what you wanted, and the isWhatIWanted is now slowly checking the result. And let's imagine that in this intervening time, the Yahoo request that came in. If you call isWhatIWanted synchronously, the result of the Yahoo request won't be able to start checking its result until the Google request has failed because you're doing synchronous calls on this serial queue.
I would suggest that you probably want to start checking results as they came in, not waiting for the others. To do this, you want a rendition of isWhatIWanted the runs asynchronously with respect to the network serial queue.

*Is the isWhatIWanted a cancelable process? Ideally it would be, so if the Yahoo image succeeded, it could cancel the now-unnecessary Pinterest isWhatIWanted. Canceling the network requests is easy enough, but more than likely, what we really want to cancel is this expensive isWhatIWanted process. But we can't comment on that without seeing what you're doing there.
But, let's imagine that you're performing the object classification via VNCoreMLRequest objects. You might therefore cancel any pending requests as soon as you find your first match.

*In your example, you list three sources. How many sources might there be? When dealing with problems like this, you often want to constrain the degree of concurrency. E.g. let's say that in the production environment, you'd be querying a hundred different sources, you'd probably want to ensure that no more than, say, a half dozen running at any given time, because of the memory and CPU constraints.
All of this having been said, all of these considerations (asynchronous, cancelable, constrained concurrency) seem to be begging for an Operation based solution.
So, in answer to your main question, the idea would be to write a routine that iterates through the sources, and calling the main completion handler upon the first success and make sure you prevent any subsequent/concurrent requests from calling the completion handler, too:

*

*You could save a local reference to the completion handler.

*As soon as you successfully find a suitable image, you can:

*

*call that saved completion handler;

*nil your saved reference (so in case you have other requests that have completed at roughly the same time, that they can't call the completion handler again, eliminating any race conditions); and

*cancel any pending operations so that any requests that have not finished will stop (or have not even started yet, prevent them from starting at all).

Note, you'll want to synchronize the the above logic, so you don't have any races in this process of calling and resetting the completion handler.

*Make sure to have a completion handler that you call after all the requests are done processing, in case you didn't end up finding any dogs at all.
Thus, that might look like:
func findPictureOfDog(_ sources: [String], completion: @escaping DogPictureCompletion) {
    var firstCompletion: DogPictureCompletion? = completion
    let synchronizationQueue: DispatchQueue = .main         // note, we could have used any *serial* queue for this, but main queue is convenient

    let completionOperation = BlockOperation {
        synchronizationQueue.async {
            // if firstCompletion not nil by the time we get here, that means none of them matched
            firstCompletion?(.failure(DogPictureError.noneFound))
        }
        print("done")
    }

    for source in sources {
        let url = URL(string: source)!
        let operation = DogPictureOperation(url: url) { result in
            if case .success(_) = result {
                synchronizationQueue.async {
                    firstCompletion?(result)
                    firstCompletion = nil
                    Queues.shared.cancelAllOperations()
                }
            }
        }
        completionOperation.addDependency(operation)
        Queues.shared.processingQueue.addOperation(operation)
    }

    OperationQueue.main.addOperation(completionOperation)
}

So what might that DogPictureOperation might look like? I might create an asynchronous custom Operation subclass (I just subclass a general purpose AsynchronousOperation subclass, like the one here) that will initiate network request and then run an inference on the resulting image upon completion. And if canceled, it would cancel the network request and/or any pending inferences (pursuant to point 3, above).

A: If you care about only one task use a completion handler, call completion(nil) if no picture was found.
var dogPicture : DogPicture?

func findPictureOfDog(_ sources, completion: @escaping (DogPicture?) -> Void) {
  for source in sources {
    let task = URL.Session.shared.dataTask(with: source) { (data, response, error) in
      // error handling ...
      if data.isWhatIWanted() && dogPicture == nil {
        let picture = data.getPicture()
        completion(picture)
      }
    }
    task.resume()
  }
}

sources = ["yahoo.com", "google.com", "pinterest.com"]

findPictureOfDog(sources) { [weak self] picture in
   if let picture = picture {
      self?.dogPicture = picture
      print("picture set")
   } else {
      print("No picture found")
   }
}

A: You can use DispatchGroup to run a check when all of your requests have returned:
func findPictureOfDog(_ sources: [String]) -> DogPicture? {
  let group = DispatchGroup()

  for source in sources {
    group.enter()
    let task = URLSession.shared.dataTask(with: source) { (data, response, error) in
      // error handling ...
      if data.isWhatIWanted() && dogPicture == nil {
        dogPicture = data.getPicture()
      }
      group.leave()
    }
    task.resume()
  }

  group.notify(DispatchQueue.main) {
    if dogPicture == nil {
        // all requests came back but none had a result.
    }
  }
}


text:
Q: Raw filter still converting & to & in the source I'm trying to use the raw filter on Twig, but it's still converting & to & in the source.
so it's outputting ' instead of '
{% if entry.title|last == "s" %}
    {% set pluralLocationName  = entry.title ~ "'"  %}
{% else %}
    {% set pluralLocationName  = entry.title ~ "'"  ~ "s" %}
{% endif %}

{% if entry.title|last == "s" %}
    {% set pluralLocationName  = entry.title ~ ("&"|raw) ~ "rsquo;" %}
{% else %}
    {% set pluralLocationName  = entry.title ~ ("&"|raw) ~ "rsquo;" ~ "s" %}
{% endif %}

edit: realizing i should have said "possessive" instead of "plural" :)

A: Twig is auto-escaping the output only so your code is working as you're expecting it and it's escaped whenever you print the result so you could either
Wrap only the output in {% autoescape %}:
{% if entry.title|last == "s" %}
    {% set pluralLocationName  = entry.title ~ "'"  %}
{% else %}
    {% set pluralLocationName  = entry.title ~ "'"  ~ "s" %}
{% endif %}

{% autoescape false %}

    {{ pluralLocationName }}

{% endautoescape %}

Output the |raw value:
{% if entry.title|last == "s" %}
    {% set pluralLocationName  = entry.title ~ "’"  %}
{% else %}
    {% set pluralLocationName  = entry.title ~ "’"  ~ "s" %}
{% endif %}

  {{ pluralLocationName|raw }}

A: The filter raw is meant to output content. You can't store content marked as safe in a variable. This mean you need to add raw to your output, not the input
{% if entry.title|last == "s" %}
    {% set pluralLocationName  = entry.title ~ "’"  %}
{% else %}
    {% set pluralLocationName  = entry.title ~ "’"  ~ "s" %}
{% endif %}

{{ pluralLocationName | raw }}

Same thing applies when you print the variable directly, instead of storing it in a variable. There you would need to wrap the full string in parentheses in order to make this work.
The reason is the that filter will be executed first, thus marking &ruqou; as safe, but as soon as you concat the string, it will be marked as unsafe content again.
{% if entry.title|last == "s" %}
    {{ (entry.title ~ "’")|raw  }}
{% else %}
    {{ (entry.title ~ "’"  ~ "s")|raw }}
{% endif %}

sidenote You may want to make your snippet shorter like this
{% set pluralLocationName  = entry.title ~ "’"  ~ (entry.title|last != 's' ? 's') %}
{{ pluralLocationName | raw }}

demo


text:
Q: Which event to add a Listener to get informed when added as aggregation? I got a xml view with a controller, which I create with sap.ui.view() and then add it to an aggregation of an other view with addDependent(). In the onInit() function of the Controller, I do not have a ownercomponent (this.getOwnerComponent() === undefined //true), since I initialize before I add it as aggregation.
Now I thought to add a Listener (attachEventOnce) and when added to a Aggregation, do the stuff I need.
Is there a event "OwnerComponentChanged" or something like this?
even more important: how can I find out, which event there are and which one to take?
Some.controller.js
var oView = sap.ui.view({viewName : "com.example.app.view.dialog", type : "XML"});
this.getView().addDependent(oView);

dialog.controller.js
(§§§ stands for the searched event)
onInit : function(){
    if (this.getOwnerComponent()===undefined) //true
    {
        this.attachEventOnce("§§§", BaseController.prototype.doSomething, this );
    }
}

A: As far as I have see there is no event fired when a view is added as a dependent.
In your code however, you are calling the addDependent method. When you do that, you could also fire your own event, message or function. Perhaps it is even better to resolve a Promise?
To find out which events are available for a certain control, you could have a look at the SDK. They're all pretty well documented there. Specifically, Views are documented here, and the list of available events is documented in paragraph "Event summary". To make that list complete, you can also see which events are inherited from lower-level components right underneath that section.
It is of course also always possible to extend the list of events by creating your own version of the View control, which may be a subclass of the actual View control. If you want the addDependent method to fire and event, you should override the addDepdendent method of your vesion. In that override, you could run the regular addDependent logic (using apply), and afterwards fire your custom event handler.
You can find very good information on how to create custom controls in step 34 of the sapui5 walkthough.


text:
Q: IIS rule rewrite for query string I have a URL that looks like
https://thesite.com/m/?pageName=profileSettings#notifications

I need to rewrite it to
https://thesite.com/m/?pageName=notificationSettings

I'm trying something like
            <rule name="m_notifications" stopProcessing="true">
                <match url="^m/(.*)" />
                <conditions>
                    <add input="{QUERY_STRING}" pattern="pageName=profileSettings#notifications" />
                </conditions>
                <action type="Rewrite" url="pageName=notificationSettings" appendQueryString="False"/>
            </rule>

This isn't working, no errors, just not making any changes. What am I missing?
Thanks

A: It is not possible to do a rewrite based on the hash string. Browser doesn't transmit the part after hash to the server.
It's called Fragment identifier and is client side only. It's not possible in any language unless you are using some browser implementation (or software) which would send that part of URL to the server.


text:
Q: How do I make default settings work for select fields with WordPress API? std is the default value of an option if it is not set. I only need the default value for the select fields. I've tried many things but nothing seems to work. I really need help on this. I don't know where to start.
So here, I do my function to add the setting to my options page.
                function nl_register_function_name() {
                    // Validation callback
                    register_setting( 'nl_theme_options', 'nl_theme_options', 'nl_validate_settings' );
                    // Add setting to section
                    add_settings_section( 'nl_styling_section', 'Styling', 'nl_display_styling_section', 'nl_theme_options.php' );
                    // Create selection field
                    $field_args = array(
                        'type'      => 'select',
                        'id'        => 'nl_function_name',
                        'name'      => 'nl_function_name',
                        'desc'      => 'Select border bottom size.',
                        'std'       => 'Small',
                        'label_for' => 'nl_function_name',
                        'items'     => array(
                            "None",
                            "Small",
                            "Medium",
                            "Large"
                        )
                    );
                    // Label
                    add_settings_field( 'label_function_name', 'function_name', 'nl_display_setting', 'nl_theme_options.php', 'nl_styling_section', $field_args );
                }
                // Registers the setting
                add_action( 'admin_init', 'nl_register_function_name' );

And here, I create the HTML for the select field.
        function nl_display_setting ( $args ) {
            extract( $args );
            $option_name = 'nl_theme_options';
            $options = get_option( $option_name );
            switch ( $args['type'] ) {
                case 'select':
                    if( isset( $options[$id] ) ) {
                        $options[$id] = stripslashes( $options[$id] );
                        $options[$id] = esc_attr( $options[$id] );
                        echo "<select name='" . $option_name . "[$id]' value='$options[$id]'>";
                        foreach( $items as $item ) {
                            $selected = ($options[$id]==$item) ? 'selected="selected"' : '';
                            echo "<option value='$item' $selected>$item</option>";
                        }
                    } elseif ( !isset( $options[$id] ) ) {
                        $std = $args['std'];
                        echo "<select name='" . $option_name . "[$id]' value='$std'>";
                        foreach( $items as $item ) {
                            echo "<option value='$item'>$item</option>";
                        }
                    }
                    echo "</select>";
                    echo ($desc != '') ? "
$desc" : "";
                break;
            }
        }

How do I make default settings work for select fields with WordPress API?

A: I fixed it! I'm going to post the solution here for others that might have the same problem in the future because there doesn't seem to be any solution online.
                case 'select':
                    if( isset( $options[$id] ) ) {
                        $options[$id] = stripslashes( $options[$id] );
                        $options[$id] = esc_attr( $options[$id] );
                        echo "<select name='" . $option_name . "[$id]' value='$options[$id]'>";
                        foreach( $items as $item ) {
                            $selected = ($options[$id]==$item) ? 'selected="selected"' : '';
                            echo "<option value='$item' $selected>$item</option>";
                        }
                    } elseif ( !isset( $options[$id] ) ) {
                        echo "<select name='" . $option_name . "[$id]' value='$std'>";
                        foreach( $items as $item ) {
                            $selected = ($std==$item) ? 'selected="selected"' : '';
                            echo "<option value='$item' $selected>$item</option>";
                        }
                    }
                    echo "</select>";
                    echo ($desc != '') ? "
$desc" : "";
                break;


text:
Q: Out of line definition of PostOrder c++ Does anyone know why do I get out of line definition at bst_node* node?
They say that it does not match any declaration in bst
template<class T>
void bst<T>::postOrder(void(*func)(const T &func), bst_node<T>* node) {
    if (node == nullptr)
        return;

    /* first recur on left child */
    postOrder(func,node->left);
    /* now recur on right child */
    postOrder(func, node->right);
    /* then print the data of node */
    func(node->value);
}


text:
Q: Keycloak SAML request in an iframe: No 'Access-Control-Allow-Origin' (CORS error) I'm working on a tool that embeds an iframe of an external app. The authentication to this external app is via SAML and Keycloak. However when using the iframe, the SAML request to Keycloak does not work: "... has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource."
Scenario 1: Accessing the external app using the browser (normal way)
I get redirected to the Keycloak login page and after successful authentication, it redirects to the external app and everything works fine.
Scenario 2: Loading the external app using the iframe
The iframe is loaded and the Keycloak login page is shown. However, after entering the credentials, the triggered SAML request to Keycloak is blocked due to the CORS issue, see
Failed SAML request to Keycloak within the iframe.
Once I click on the failed URL (starting with "saml?SAMLRequest=...") and access it the normal way (browser), everything works fine.
I read on multiple sites, e.g. here Keycloak Access-Control-Allow-Origin, that you have to enter your webpage (in this case localhost:8080) to the Web Origin field within the Keycloak interface. This one only exists when choosing the openid-connect value in Client Protocol though. So, when switching from openid-connect to SAML, which I use, the Web Origin field disappears. I even tried to export the config file for that Keycloak client in order to manually enter the WebOrigin property, which did not work either.
How can I change the CORS policy for this iframe when using SAML (not openid-connect) since I don't have access to the Web Origin field?
Thanks in advance!

A: Keycloak doesn't allow to be loaded in the iframe by default.
Keycloak admin must allow that explicitly per realm in the Realm settings->Security Defenses->Headers->X-Frame-Options. Make sure you understand all security consequences before you allow Keycloak in the iframe. It's a security setting.


text:
Q: Redux-thunk action returns a function, which is not executed, so data is not fetched I have a container component that should populate the redux store with item data when it's mounted, the component correctly calls the action with the id that was requested. The action returns a dispatch function, which is never executed, so data is never retrieved.
What am I doing wrong?
my container component is this:
import { connect } from "react-redux";
import React, { Component } from "react";

import fetchItem from "../actions/itemActions";
import ItemDetails from "../components/ItemDetails";

class ItemDetailsContainer extends Component {
  state = {
    item: null
  };

  componentDidMount() {
    return fetchItem(this.props.match.params.number);
  }

  render() {
    return <ItemDetails {...this.props} />;
  }
}

const mapStateToProps = (state, props) => {
  return {
    item: state.item,
    user_location: state.user_location
  };
};

export default connect(mapStateToProps)(ItemDetailsContainer);

my action file looks like this:
 import * as actions from "../constants/constants";
import fetch from "isomorphic-fetch";

const itemDetailsRequest = id => {
  return {
    type: actions.FETCH_ITEM_REQUEST,
    id,
    receivedAt: Date.now()
  };
};

const itemDetailsSuccess = (id, json) => {
  return {
    type: actions.FETCH_ITEM_SUCCESS,
    items: json.map(child => child),
    receivedAt: Date.now()
  };
};

const itemDetailsFailure = (id, json) => {
  return {
    type: actions.FETCH_ITEM_FAILURE,
    error: json.error,
    receivedAt: Date.now()
  };
};

const fetchItem = id => {
  console.log(`returning dispatch function for item, id: ${id}`);
  return function(dispatch) {
    console.log("fetching Item: " + id);
    dispatch(itemDetailsRequest(id));
    fetch(`item.json?id=${id}`)
      .then(
        response => response.json(),
        error => console.log("AN ERROR OCCURED.", error)
      )
      .then(json => {
        dispatch(itemDetailsSuccess(id, json));
      });
  };
};

export default fetchItem;

A: You forgot to use the dispatch when calling fetchItem:
componentDidMount() {
  return this.props.dispatch(fetchItem(this.props.match.params.number));
}

Or if you don't want to use dispatch directly in the componentDidMount, you can directly use mapDispatchToProps:
const mapStateToProps = (state, props) => {
  return {
    item: state.item,
    user_location: state.user_location
  };
};

const mapDispatchToProps = dispatch => {
  return({
    fetchItem: (number) => dispatch(fetchItem(number)),
  })
}

export default connect(mapStateToProps, mapDispatchToProps)(ItemDetailsContainer);

And in the componentDidMount:
componentDidMount() {
  return this.props.fetchItem(this.props.match.params.number);
}


text:
Q: Comparing two dates with NSDateComponents I'm using this code to compare two dates and return the number of difference in days. I want to use it and get the minutes and the Hours, but I get the same number.
NSDate *todaysDate =[NSDate date];
NSDate *eventDate = [self.event objectForKey:@"eventDate"];

NSDateComponents *components = [[NSCalendar currentCalendar] components: NSDayCalendarUnit
                                                                   fromDate: todaysDate toDate: eventDate options: 0];

NSInteger days = [components day];
NSInteger hours = [components hour];

NSLog(@"Number of days %ld", days);
NSLog(@"Number of hours %ld", hours);

the eventDate its on this format "2014-08-08 13:11:00 +0000"
What I always get in return for the number of hour or minutes is "9223372036854775807".

A: If you enter "9223372036854775807" as a decimal value into a programming calculator and convert it to hex, you get 0x7FFFFFFFFFFFFFFF. That is probably the NSUndefinedDateComponent constant, and that means the NSDateComponents object doesn't have the requested fields because you didn't ask for them using NSHourCalendarUnit and NSMinuteCalendarUnit when you created the NSDateComponent. Only those fields you specify in the "components:" parameter will be initialized. The days field should contain a correct value. To get hours and minutes, you need to change this line:
NSDateComponents *components = [[NSCalendar currentCalendar] components: NSDayCalendarUnit
                                          | NSHourCalendarUnit | NSMinuteCalendarUnit
                                          fromDate: todaysDate toDate: eventDate options:

0];


text:
Q: How do I set the accessible text for TreeView items when using HierarchicalDataTemplates and multiple item types? I have an application with a TreeView control that is built using a set of data types representing different levels in the hierarchy and an accompanying set of HierarchicalDataTemplates.  What I want to do now is set appropriate AutomationProperties.Name values on the tree items.
Normally, I would use TreeView.ItemContainerStyle to bind the accessible name, but this is rather limited, as it requires I use a binding path that works for all types.
In this case, however, I would much rather be able to control the accessible name independently for each type.  For example, it may be useful to include Id in some layers, but not in others.
I could probably live with using the displayed text, but while I can easily use a RelativeSource binding in TreeView.ItemContainerStyle to get at the TreeViewItem, the Path needed to ultimately reach the TextBlock.Text value in the templated item from there eludes me.
I have also tried using HierarchicalDataTemplate.ItemContainerStyle, but that only applies to child items.  Even further, when I tried to define it on each template, only BazItems were properly set, even though I would have expected BarItems to work as well.
I put together a minimal example to illustrate the issue.  The item types are as follows:
public sealed class BazItem
{
    public BazItem(int id, string name)
    {
        Id = id;
        Name = name ?? throw new ArgumentNullException(nameof(name));
    }

    public int Id { get; }
    public string Name { get; }
}

public sealed class BarItem
{
    public BarItem(int id, string display)
    {
        Id = id;
        Display = display ?? throw new ArgumentNullException(nameof(display));
        Bazs = new ObservableCollection<BazItem>();
    }

    public int Id { get; }
    public string Display { get; }
    public ObservableCollection<BazItem> Bazs { get; }
}

public sealed class FooItem
{
    public FooItem(int id, string name)
    {
        Id = id;
        Name = name ?? throw new ArgumentNullException(nameof(name));
        Bars = new ObservableCollection<BarItem>();
    }

    public int Id { get; }
    public string Name { get; }
    public ObservableCollection<BarItem> Bars { get; }
}

The corresponding templates are as follows:
<HierarchicalDataTemplate DataType="{x:Type local:BazItem}">
    <TextBlock Text="{Binding Name, StringFormat='baz: {0}'}"/>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType="{x:Type local:BarItem}"
                          ItemsSource="{Binding Bazs}">
    <TextBlock Text="{Binding Display, StringFormat='bar: {0}'}"/>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType="{x:Type local:FooItem}"
                          ItemsSource="{Binding Bars}">
    <TextBlock Text="{Binding Name, StringFormat='foo: {0}'}"/>
</HierarchicalDataTemplate>

Finally, the tree view in the view is as follows:
<TreeView ItemsSource="{Binding Foos}"/>

where Foos is an ObservableCollection<FooItem> property on the underlying view.

A: The solution I came up with for now (pending a better answer) is to change the TreeView.ItemContainerStyle to use a value converter against the tree item object rather than a property on the object:
TreeView element:
<TreeView ItemsSource="{Binding ElementName=View, Path=Foos}">
    <TreeView.ItemContainerStyle>
        <Style TargetType="{x:Type TreeViewItem}">
            <Setter Property="AutomationProperties.Name" Value="{Binding Converter={StaticResource AccessibleConverter}}"/>
        </Style>
    </TreeView.ItemContainerStyle>
</TreeView>

Converter:
[ValueConversion(typeof(object), typeof(string), ParameterType = typeof(Type))]
public sealed class AccessibleTextConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        switch (value)
        {
            case FooItem foo:
                return $"foo: {foo.Name}";
            case BarItem bar:
                return $"bar: {bar.Display}";
            case BazItem baz:
                return $"baz: {baz.Name}";
            default:
                return Binding.DoNothing;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

This works, but it's less-than-ideal for several reasons:

*

*it duplicates the format strings (though I could pull them out into a shared resource location)

*the value converter has to first convert object to the appropriate type before it can come up with the appropriate string format

*adding a new tree item type requires I touch both the templates as well as the value converter

A: I came along the same issue and the way I solved it was by overriding the ToString() method of the class of the object i was binding the TreeViewItem.
For example, in your case the type of item you bind to TreeViewItem is of type BazItem, go to BazItem class and:
public override string ToString()
{
    // This is what the Windows Narrator will use now
    return "Name of Baz Item";
}


text:
Q: Specific part (not entire question) of the proof that O can be written as a union of disjoint open intervals I have completed a proof of the following statement:
Prove that any bounded open subset of R is the union of disjoint open intervals
Let O $\subset$ R
We want to write O as a disjoint union of open intervals
Since O is bounded, we can define $\forall x \in O$
\begin{align}
a_x &= \inf\{ y \in R: (y,x) \subset O\}\\
b_x &= \sup\{z \in R: (x,z) \subset O\}
\end{align}
Let
$$\ U = \bigcup_{x \in O} (a_x,b_x),$$
where $(a_x,b_x) \subset O$.
There is more to the proof, but this is the part I need help on. I have been told by my instructor the proof is correct. However, he says it is not evident that $(a_x,b_x) \subset O$. He wants me to prove this specific part, and I cannot figure out how to do it. I know I need to take an element in $(a_x,b_x)$, and show that it is in O, but I am not sure how to do this and how to connect it. I've been trying this for a week, and I've decided it is about time I ask for help. Can anyone help me here?

A: So $a_x = \inf\{y \in \Bbb R\mid (y,x) \subseteq O\}$
and $b_x = \sup\{y \in \Bbb R\mid (x,y) \subseteq O\}$
which are well-defined (there are $a' < x < b'$ such that $(a',b') \subseteq O$ as $x$ is in the interior of $O$ so the sets are non-empty); and $O$ is bounded so any lower bound for $O$ is one for the set defining $a_x$ etc.
Why $(a_x, b_x) \subseteq O$? Let $z \in (a_x, b_x)$. If $z=x$ we are done, so assume (first case) that $z < x$. Because $a_x$ is the greatest lower bound for the set $A_x:=\{y \in \Bbb R\mid (y,x) \subseteq O\}$, we are sure that $z$ is not a lower bound for $A_x$, so there is some $z' \in A_x$ such that $z' < z$. But then $z' \in A_x$ implies $(z',x) \subseteq O$ and as $z \in (z',x)$, we know $z \in O$.
A similar argument can be held for $b_x$ and $B_x = \{y \in \Bbb R\mid (x,y) \subseteq O\}$ when $z > x$ instead, using that $b_x$ is the smallest upper bound for $B_x$ etc.

A: Hint: prove that $(a_x+\frac1n,\, b_x-\frac1n)\subseteq O$ for all $x\in O$ and big enough $n\in\Bbb N$.

A: Let $x\in O.$
Consider any $v\in (x,b_x).$ We have $v<b_x.$ Now  $$ v\not \in O\implies \forall z\in \Bbb R\,(\,(x,z)\subset O\implies z\le v)\implies b_x\le v$$ contrary to $v<b_x.$ So $v\in O.$
So $(x,b_x)\subset O.$
Similarly we obtain $(a_x,x)\subset O.$
So $(a_x,b_x)=(a_x,x)\cup \{x\}\cup (x,b_x)\subseteq O.$


text:
Q: Viewport width adaption in a narrow WebView Currently I have a HTML document with viewport width set to device width. My issue is with adapting viewport width to WebViews that are narrower than the full device width. Using device width in this case will render the document wider than the WebView, which I am trying to avoid.
The document is to be displayed in both Android and iOS apps, and is built using only document relative sizes for all elements. It is therefore dependant on the document width being correctly adapted to the width of the view.
How can I fit the viewport width to the actual width of the WebView instead of the device width?

A: I am dealing with something similar in Android. So that you understand my situation: my testing device width actual resolution is 540 and the fixed width of the design is 640. My goal was to set the webview used in cordova to zoom out to show the full design width.
Does this code help you resolve the issue on Android?
public class MainActivity extends DroidGap {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    super.loadUrl("file:///android_asset/www/index.html");

    super.appView.getSettings().setSupportZoom(true);
    //super.appView.getSettings().setBuiltInZoomControls(true);

    super.appView.getSettings().setLoadWithOverviewMode(true);
    super.appView.getSettings().setUseWideViewPort(true);
    }
}


text:
Q: Typescript file-naming conventions I'm looking for the Typescript file-naming conventions, specifically for a file which stores only types and interfaces.
Now, I've found a couple of Typescript Coding Convention projects on GitHub, and they even refer to file-naming conventions here and here. But none of them refers to the specific file that I'm interested in, namely - a file which stores only types and interfaces.
For all it matters, within my project this file serves for both internal usage and external API.

A: Sometimes I get tired of spending time researching for things like this so I have decided to go with the following practice.
interfaces folder for files that contain interfaces
file naming convention: file.interface.ts
types folder for files that contain types
file naming convention: file.type.ts

A: we usually go for "index.d.ts" and have multiple spaced throughout the project.


text:
Q: Apparent Memory Leak when dispatching from HttpClient continuation The Issue: After using HttpClient correctly (as a static single instance) over a long time, ConcurrentStack+Node instances consistently grow in size causing increased memory usage. Edit: This seems related to the dispatcher called in SetText and AddText.
The Use-Case: I am polling a device on my local network through HTTP transmission. I use System.Threading.Timer to control the frequency of my requests. The callback for the polling timer is async void so that the await operator can be used for continuation control. The default window dispatcher is used to display text results after the HttpRequest is called.
The Code for Recreation: .NET Framework 4.5 ; WPF ; All standard settings with a single TextBlock created in MainWindow with x:Name="Debug"
 using System;
 using System.Net;
 using System.Net.Http;
 using System.Threading;
 using System.Threading.Tasks;
 using System.Windows;

 namespace LeakIsolator
 {
     /// <summary>
     /// Interaction logic for MainWindow.xaml
     /// </summary>
     public partial class MainWindow : Window
     {
         static MainWindow()
         {
             WebClient.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore);
             HttpClient.DefaultRequestHeaders.CacheControl = new System.Net.Http.Headers.CacheControlHeaderValue()
             {
                 NoStore = true,
                 NoCache = true
             };
         }

         public MainWindow()
         {
             InitializeComponent();

             Timer = new Timer(Poll, null, Timeout.Infinite, Timeout.Infinite);
             Loaded += MainWindow_Loaded;
         }

         private static HttpClient HttpClient { get; } = new HttpClient();

         private static WebClient WebClient { get; } = new WebClient();

         private Timer Timer { get; }

         private void SetText(string text)
         {
             Dispatcher.Invoke(() => Debug.Text = text);
         }

         private void AddText(string text)
         {
             Dispatcher.Invoke(() => Debug.Text += text);
         }

         private async void Poll(object a)
         {
             try
             {
                 SetText("Getting status...");
                 SetText(await GetResponseStringHttpClient("http://10.10.10.87/status"));
             }
             catch (Exception e)
             {
                 SetText($"Exception. {e.Message}");
             }
             finally
             {
                 Start();
             }
         }

         private async Task<string> GetResponseStringWebClient(string address)
         {
             return await WebClient.DownloadStringTaskAsync(address);
         }

         private async Task<string> GetResponseStringHttpClient(string address)
         {
             using (var response = await HttpClient.GetAsync(address))
             {
                 if (response.IsSuccessStatusCode)
                 {
                     AddText(" Success...");
                     return await response.Content.ReadAsStringAsync();
                 }
                 else
                 {
                     AddText(" Fail.");
                     return null;
                 }
             }
         }

         private void Start()
         {
             Timer.Change(1000, Timeout.Infinite);
         }

         private void MainWindow_Loaded(object sender, RoutedEventArgs e)
         {
             Start();
         }
     }
 }

Using ANTS memory profiler, and running the application for 37 minutes in the most recent test, 2.618 MB (small for now, but this is a long-running application) inaccessible-to-me bytes are allocated by a PinnableBufferCache, presumably stored in the gen 2 heap.
I am not sure if this is a memory leak or is a part of something I do not understand. Why am I seeing these memory increases and why am I unable to dictate the local caching behavior of HttpClient and WebClient?

A: I would guess AddText, you could try commenting out the code in that method and see if the memory leak goes away.


text:
Q: Return 404 with TomEE and Intellij I created a sample Jakarta EE web application which is auto-generated by IntelliJ.
I deployed the war file to TomEE (9.0) and It returns 404 error.
I deployed the same war file to Tomcat (10.0) and it shows me index.jsp successfuly.
I wonder why TomEE is not working?
I downloaded it (webprofile) from https://tomee.apache.org/download.html
(latest one, TomEE 9.0)
TomEE
TomEE 404 status
Tomcat
Tomcat Successful index.jsp
Create Sample Project - 1
Create Sample Project - 2
I tried everything I can do.
Application context and url path are same.

A: Hmm, I found the answer: You should exactly match application context with your war file name
I don't believe IntelliJ will do this for you
Example:
WAR: DEMO-1-1.0-SNAPSHOT.war
Application Context: DEMO-1-1.0-SNAPSHOT
It looks like Tomcat does not care about this?
TomEE is strict.


text:
Q: Bootstrap 4 vertical alignment of progress bar I'd like to vertically center bootstrap 4's progress bar in a column. This seems like it should be simpler than I'm experiencing. I've tried align-content-center, align-items-center, and my-auto, various containing boxes with various combinations of alignment classes. I obviously don't have a real command of vertical alignment. What's preventing it from moving?

.progress-bar {
  width: 65%;
  background-color: ;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

The box to the right shows a progress bar that should be vertically aligned

Codpen link

A: Vertical alignment is often a bit harder than simply using vertical-align: middle. In your particular case, you can position your progress bar by using position: absolute. You set it to 50% from top and 0 from left, and use transform to offset it by its own height. In this case the element will also need to set the elements width.
.progress{
    position: absolute;
    top: 50%;
    left: 0;
    transform: translate(0%, -50%);
    width: 100%;
}


text:
Q: python: replace item in a list with items in a another list I have a dictionary:
d = {'name': ['sarah', 'emily', 'brett'], 'location': ['LA', 'NY', 'Texas']}

I also have a list:
l = ['name', 'location']

I want to replace 'name' in the list l with the list ['sarah', 'emily', 'brett'] in dictionary d (same thing for location).
So the outcome would be:
l = ['sarah', 'emily', 'brett', 'LA', 'NY', 'Texas']

for item in l:
    l.append(d[item])
    l.remove(item)

this is what I did and I got a type error, unhashable type: 'list'.
what should I do to fix this?

A: You should not change the list inside the loop if you are iterating in the items of that list.
Try creating a new one and then rename it. The garbage collector will take care of old version of l.
new_l = []
for item in l:
    new_l.extend(d[item])
l = new_l

A: The simplest solution is to create a new list:
l = [y for x in l for y in d[x]]

The results are the flattened substituted items:
print l
>>> ['sarah', 'emily', 'brett', 'LA', 'NY', 'Texas']

A: Use this code:
l = [d.get(k, k) for k in l]

A: Don't change list when you are looping in, because iterator will not be informed of your changes.
To replace them, just generate a new one containing d lists selected with l items.
[d[item] for item in l]

If you are not sure that all items in l are keys in d you can add test before trying to get from d:
[d[item] for item in l if d.has_key(item)]

A: replace .append() with .extend()
tmp = []
for i in l:
    tmp.extend(d[i])
l = tmp

A: In my case, the item in list only partial shown in dictionary. To avoid error I used:
[y for x in l for y in d.get(x,[x])]
When test data changed like:
l = ['name', 'location', 'test']

The result would like below:
print([y for x in l for y in d.get(x,[x])])
>>> ['sarah', 'emily', 'brett', 'LA', 'NY', 'Texas', 'test']


text:
Q: beamer: \insertshortsection \documentclass{beamer}

\begin{document}

\begin{frame}
\frametitle{Contents}
\tableofcontents
\end{frame}

\section[Sec. A]{Section A}
\subsection{SubSec a}
\begin{frame}
\frametitle{\insertsection: \insertsubsection}
\end{frame}

\subsection{SubSec b}
\begin{frame}
\frametitle{\insertsection: \insertsubsection}
\end{frame}

\section[Sec. B]{Section B}
\subsection{SubSec a}
\begin{frame}
\frametitle{\insertsection: \insertsubsection}
\end{frame}

\subsection{SubSec b}
\begin{frame}
\frametitle{\insertsection: \insertsubsection}
\end{frame}

\end{document}

*

*I often use \frametitle{\insertsection: \insertsubsection} (or similar) to automatically generate frame titles in beamer.

*Sometimes I would like to use the short version of the title, such as in \section[Sec. A]{Section A} --> \insertshortsection (= Sec. A) which is not available (see also here).

Is there an easy way to access the short version of section and friends? With "easy" I mean that the solution does not have many side effects.

Probably Related

*

*Short section name in toc

Solution
\documentclass{beamer}

\let\oldsection\section
\makeatletter
\def\section{%
\@ifstar{\@Starred}{\@nonStarred}%
}
\def\@Starred{%
\@ifnextchar[%
{\GenericWarning{}{Warning: A starred section can not have parameters. I am going to ignore them!}\@StarredWith}%
{\@StarredWithout}%
}
\def\@StarredWith[#1]#2{%
\xdef\myshortsec{#1}
\oldsection*{#2}%
}
\def\@StarredWithout#1{
\xdef\myshortsec{#1}
\oldsection*{#1}%
}
\def\@nonStarred{%
\@ifnextchar[%
{\@nonStarredWith}%
{\@nonStarredWithout}%
}
\def\@nonStarredWith[#1]#2{%
\xdef\myshortsec{#1}
\oldsection[#1]{#2}%
}
\def\@nonStarredWithout#1{%
\xdef\myshortsec{#1}
\oldsection{#1}%
}
\makeatother

\begin{document}

\begin{frame}
\frametitle{Contents}
\tableofcontents
\end{frame}

\section[Sec. A]{Section A}
\subsection{SubSec a}
\begin{frame}
\frametitle{\insertsection\ \texttt{(long)}: \myshortsec\ \texttt{(short)}: \insertsubsection}
\end{frame}

\subsection{SubSec b}
\begin{frame}
\frametitle{\insertsection\ \texttt{(long)}: \myshortsec\ \texttt{(short)}: \insertsubsection}
\end{frame}

\end{document}

A: You can use \insertsectionhead:
\documentclass{beamer}

\begin{document}

\begin{frame}
\frametitle{Contents}
\tableofcontents
\end{frame}

\section[Sec. A]{Section A}
\subsection{SubSec a}
\begin{frame}
\frametitle{\insertsectionhead: \insertsubsection}
\end{frame}

\end{document}

A: Here is an answer stolen from this one:
https://tex.stackexchange.com/a/380116/120578
(It is mine too and have been used at least 5-6 times for solving different problems, but for some reason has still zero votes :( :P )
\documentclass{beamer}

\let\oldsection\section
\makeatletter
\def\section{%
\@ifstar{\@Starred}{\@nonStarred}%
}
\def\@Starred{%
\@ifnextchar[%
{\GenericWarning{}{Warning: A starred section can not have parameters. I am going to ignore them!}\@StarredWith}%
{\@StarredWithout}%
}
\def\@StarredWith[#1]#2{%
\xdef\myshortsec{#1}
\oldsection*{#2}%
}
\def\@StarredWithout#1{
\xdef\myshortsec{#1}
\oldsection*{#1}%
}
\def\@nonStarred{%
\@ifnextchar[%
{\@nonStarredWith}%
{\@nonStarredWithout}%
}
\def\@nonStarredWith[#1]#2{%
\xdef\myshortsec{#1}
\oldsection[#1]{#2}%
}
\def\@nonStarredWithout#1{%
\xdef\myshortsec{#1}
\oldsection{#1}%
}
\makeatother

\begin{document}

\begin{frame}
\frametitle{Contents}
\tableofcontents
\end{frame}

\section[Sec. A]{Section A}
\subsection{SubSec a}
\begin{frame}
\frametitle{sect-\insertsection : short-\myshortsec: \insertsubsection}
\end{frame}

\subsection{SubSec b}
\begin{frame}
\frametitle{sect-\insertsection: short-\myshortsec : \insertsubsection}
\end{frame}

\end{document}

If we redefine sectioning commands this way we can do many things to use their arguments as I noticed in the original answer too :P