text:
Q: Using substring in C# textboxes I wanted to display the remaining characters using a label beside my textbox just in case the user input exceeded the maximum length of characters.
This is my code for remaining characters:
private void txtID_TextChanged(object sender, EventArgs e)
    {
        int MaxChars = 10 - txtID.Text.Length;
        labelChars.Text = MaxChars.ToString() + " characters remaining.";
    }

What I wanted to do now is to prevent the user from entering characters in my textbox when he/she already exceeded the character limit. I'm planning to use the Substring property of the textbox but I don't know how. Help me out? Thanks.

A: You should use the MaxLength property. http://msdn.microsoft.com/en-us/library/system.windows.forms.textboxbase.maxlength.aspx

A: You can just set the MaxLength property of the textbox and it will do that for you.

A: Could you just use the MaxLength property? http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.textbox.maxlength.aspx

A: You know the MaxLength property?

A: This would work much better on the client side. Use the MaxLength property of the textbox and maybe a little javascript to keep the lblChars control functioning.
<asp:TextBox MaxLength="10" runat="server" ID="txtID" ClientIDMode="Static" onkeydown="changedID();"></asp:TextBox>
<asp:Label ClientIDMode="Static" ID="lblChars" runat="server"></asp:Label>
<script type="text/javascript">
    function changedID() {
        var t = document.getElementById("txtID");
        var l = document.getElementById("lblChars");
        l.innerText = (10 - t.value.length) + " characters remaining.";
    }
</script>


text:
Q: Firebase iOS -What is the difference between .queryOrdered().queryEqual(toValue: and child().observeSingleEvent In Firebase when searching for a username (or anything search related for that matter) what is the difference between
.queryOrdered().queryEqual(toValue: and child().observeSingleEvent(
I looked at the answer and comments below from @Frank van Puffelen
In these comments he says to use:
reference.child("usernames").child(usernameYourSearchingFor).observeSingleEvent(of: .value, with: { (snapshot) in

    if snapshot.exists() { ... } else { ... }
})

But in this answer he answered with:
ref.child("users").queryOrdered(byChild:"username").queryEqual(toValue: usernameYourSearchingFor).observeSingleEvent(of: .value, with: { snapshot in

    if snapshot.exists() { ... } else { ... }
})

When searching the database using either of these methods, is there a difference between speed and efficiency, or is it simply a matter of using 2 different methods to achieve the same exact goal?

A: Basically, those operations are meant for two different data structures.
In the first one, you'd have a data structure similar to this:
{
  "usernames": {
    "usernameYourSearchingFor": {
      // some data
    },
    "otherUsername": {
      // different data
    }
  }
}

As you can see, the username you're searching for is a key under the "usernames" node. You can access it directly, by calling the child() function. (and then a single event observer is attached to it)

Now in the second structure:
{
  "users": {
    "user1": {
      "username": "usernameYourSearchingFor",
      "email": "user1@email.com"
    },
    "user2": {
      "username": "otherUsername",
      "email": "user2@email.com"
    }
  }
}

The username is actually an attribute belonging to the User object. There's no way you can access it directly, so you need to query the "users" node in order to find the username you're searching for, hence the need of .queryOrdered(byChild:"username").queryEqual(toValue: usernameYourSearchingFor).

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I generalize the Outer Class in Json Response mapping using REST template? I'm developing a series of clients to webservices and I'm observing that they follow a simple json structure, like this:
{
  "typex": { "property1" : "value"},
  "page": 1,
  "count": 200,
  "next_page": 2
}

I have near 15 webservices each returning the same structure, where the main information is within the object "typex" and their properties.
Today, these returns needs to have, at least, 2 classes, one for outer data and one for inner information.
public class TypeXWrapper {
 @JsonProperty
 TypeX typex;
 @JsonProperty
 Integer page;
 @JsonProperty
 Integer count;
 @JsonProperty
 Integer next_page;
}
public class TypeX {
 @JsonProperty
 String property1;
}

In this way, it would be necessary to create 30 classes.
Is there any way to implement some kind of generalization for situations like this?
I was thinking something like:
public class GenericWrapper<InnerClass> {
 @JsonProperty
 InnerClass data;
 @JsonProperty
 Integer page;
 @JsonProperty
 Integer count;
 @JsonProperty
 Integer next_page;
}
public class TypeX {
 @JsonProperty
 String property1;
}

But the problem is that the root property of the inner class data, changes for each webservice endpoint. That means that the next answer, for example TypeY, the property will have the name "typey", like:
{
  "typey": { "property2" : "value"},
  "page": 1,
  "count": 200,
  "next_page": 2
}

Is there anything that I could use to achieve this generalization? The environment and frameworks are Spring Boot 2.1.18 (can change if needed), using resttemplate with the return object encapsulated in ParameterizedTypeReference.
Thanks!


text:
Q: How can I find commits which contain credentials/passwords with git log So, I have a repository and suspicions that someone accidentally commited credentials into it
I need to find all commits which contains my credentials: tiWEythzNEX8N3sktiWEythzNEX8N3sk
Let's see some commits. There is small repo to reproduce
Use command git log --oneline -n 10
963f080 (HEAD -> find-credentials-git-log) feat(3309): add middleware
b83a41f fix(3309): rm credentials
70ec8dc bug: ooops I show my credentials
895937f feat(3309): add server
534792d feat(3309): add types
9cce5c9 feat(3309): add position entity

Now lets see git diff of 70ec8dc bug: ooops I show my credentials commit
Use command git show 70ec8dc
commit 70ec8dc914609d50bd0ef3c0b420db0b7a4aa7f5
Author: Yegor <mail@gmail.com>
Date:   Wed Jun 19 12:21:38 2019 +0300

    bug: ooops I show my credentials

diff --git a/typeorm/3309/startServer.ts b/typeorm/3309/startServer.ts
index 0f1c9bd..b3bd09e 100644
--- a/typeorm/3309/startServer.ts
+++ b/typeorm/3309/startServer.ts
@@ -45,7 +45,7 @@ export const startServer = async () => {
         prefix: redisSessionPrefix
       }),
       name: 'offerhub',
-      secret: process.env.SESSION_SECRET,
+      secret: 'tiWEythzNEX8N3sktiWEythzNEX8N3sk', // My credentials
       resave: false,
       saveUninitialized: false,
       cookie: {

I need to find all commits which git diff contains this text/credentials tiWEythzNEX8N3sktiWEythzNEX8N3sk. How to do it?

A: git log --oneline -S 'tiWEythzNEX8N3sktiWEythzNEX8N3sk'

See the doc here.


text:
Q: Why am I getting garbage characters in my output for Test 1 and Test3 occasionally? I am having problems with my test cases writing garbage to my result variable. I am pretty new to C, so I am having trouble determining what is causing it.
//Author: Ryan Fehr
//Contributors:
#include <stdio.h>
#include <string.h>

int remover(char[], char[], char[]);

int remover(char source[], char substring[], char result[])
{
    char *current = source;
    // printf("%s n", current);
    char *currentSub = substring;
    //printf("%c n", *currentSub);
    int i = 0;

    while(*current != '\0')//Loops through the source string
    {
        //Uncommenting the line below will show you the comparisons being performed
        printf(" %c | %c \n", *current, *currentSub);

        if(*current == *currentSub || *currentSub == '\0')//True when a letter matches with a letter in the subStr or the complete subStr was found
        {

            if(*currentSub == '\0')
            {
                char pre[((current-(i) - source))];//Stores everything before the subString in pre(current-i) - source
                memcpy(pre, source, (current-i) - source);
                printf("Pre: %s\n",pre);
                //Counts how many chars are after the substring
                int n = 0;
                while(*current != '\0')
                {
                    n++;
                    current++;
                }
                char post[n];//Stores everything after the subString in post
                memcpy(post, current-n, n);
                printf("Post: %s\n",post);
                strcat(result, pre);
                strcat(result,post);
                printf("Substring removed: %s\n", result);//Prints the value after substring has been removed
                return 1;
            }
            i++;
            currentSub++;
        }
        else
        {
            i=0;
            currentSub = substring;
        }
        current++;
    }
    return 0;
}

int main(void)
{
    //TEST 1
    char s[] = "jump_on_down_to_getfart_and_up_to_get_down_";
    char sub[] = "fart";
    char r[100] = "";
    printf("Test 1:\n");
    printf("Source: %snSubstring: %s\n",s,sub);
    printf("%d\n\n", remover(s, sub, r));
    //EXPECTED OUTPUT: 1
    //TEST 2
    strcpy(s, "racecar");
    strcpy(sub, "x");
    strcpy(r, "");
    printf("Test 2:n");
    printf("Source: %snSubstring: %s\n",s,sub);
    printf("%d\n\n", remover(s, sub, r));
    //EXPECTED OUTPUT: 0
    //TEST 3
    strcpy(s, "jump on down to get and up to get down ");
    strcpy(sub, "up");
    strcpy(r, "");
    printf("Test 3:n");
    printf("Source: %snSubstring: %s\n",s,sub);
    printf("%d\n\n", remover(s, sub, r));
    //EXPECTED OUTPUT: 1
}

Here is a screen shot of the output for Test1, as you can see I am getting extra garbage printing and I think my math is correct for my substrings, so I am not sure what is causing this.
I can't embed images so it is linked

A: Nested functions are not a part of standard C.  Only GCC (and maybe Clang emulating, or in compatibility mode with, GCC) support it.  Do not post nested functions on Stack Overflow (or Code Review) if you want to get away without scathing comments being passed on the unsuitability of nested functions.
Your problem is that your variable r in main is an array of size 1, but you use it in the remover() function as if it was bigger.  You get undefined behaviour as a result.
At minimum, you should use:
char r[100];  // Or any other convenient size - for the test data 50 would do

There may be other problems; I've not compiled the code (I decline to compile C code with nested functions; it won't pass my default compilation options).

A: Do not insert one function inside another function.
The posted code has the remover() function nested inside the main() function.
While some compilers will allow that as an 'extension', (gcc comes to mind ) you should never nest functions.
For ease of readability and understanding: 1)  consistently indent the code.  indent after every opening brace '{'. unindent before every closing brace '}. Suggest using 4 spaces for each indent level.  2) separate code blocks (for, if, else, while, do... while, switch, case, default) via a blank line


text:
Q: Cannot find namespace 'go' I am integrating gojs in angular 8 project.
I have already installed gojs-angular package.
npm install gojs gojs-angular.
Below is the code snippet.
error: Cannot find namespace 'go'
public initDiagram(): go.Diagram {};

A: Please follow and verify below steps.

*

*Install gojs and gojs-angular

npm i gojs gojs-angular

*import * as go from 'gojs';

We can just use variable by import in the component.ts file.
No need to add script or import in other places,


text:
Q: Titanium handling different resoutions Simple question, which is the best way to make sure that the app works on different screen resolutions without looking crap? I can't use static values, then it want adjust according to the resolution. Right now i am using relative measurements (percentage of screen) but wonder if that's really the best way to handle it!?

A: Another/additional option we have been successful with is  a small set of functions which use the screen density value to compute display sizes... this is of course only an approximation, as there are only the four densities, but we have found this to be very helpful.
//=============================================================================
// inch
//
// compute approximate number of pixels for the specified physical on-screen
// size based on the density reported by the OS
//=============================================================================
function inch(size)
{
    // default to 160 dpi if unavailable
    var height = size * 160.0;

    try
    {
        // compute header height based on screen density ... target .25" height
        height = size * Ti.Platform.displayCaps.dpi;
    }
    catch(e) { warn("Error accessing display caps for screen density calculation: " + e); }

    return height;
}

So if you want something to be 3/4 inch high on the screen....
Ti.UI.createThing({ height: inch(.75)});

...or if you want to scale things by point size, one could make some constants...
const g_12pt = inch(12/72); //0.166667
const g_10pt = inch(10/72); //0.138889
const g_8pt = inch(8/72);   //0.111111
const g_6pt = inch(6/72);   //0.083333
...
...font:{fontSize: g_10pt, fontWeight:"bold"},...

We also created a couple of functions to get the screen height and width, so if we wanted a better layout on a tablet or something tiny we could better understand what we were dealing with.
//=============================================================================
// screenWidth - return screen width in inches
//=============================================================================
function screenWidth()
{
    return Titanium.Platform.displayCaps.platformWidth / Titanium.Platform.displayCaps.dpi;
}

//=============================================================================
// screenHeight - return screen height in inches
//=============================================================================
function screenHeight()
{
    return Titanium.Platform.displayCaps.platformHeight / Titanium.Platform.displayCaps.dpi;
}

You can go on and on from there... but this really helped us nail down how we laid out our screens on the different densities and platforms.  The inch function has exception handling only because we use it early in the app, and sometimes the Ti.Platform is still undefined.  By the time we are laying out our reports Ti.Platform is available and so the screen functions do not have the exception handling.  If you need to query earlier you may need exception handling in those as well.
Hope this helps!

A: You'll want to modify your tiapp.xml - in the android section you add a manifest record like so:
<android xmlns:android="http://schemas.android.com/apk/res/android">
    <manifest>
        <supports-screens android:anyDensity="false"/>
    </manifest>
</android>

That will make the app default to the same style that the older versions of titanium used, where it basically scales them according to the device in use. More details on the change can be found here: http://developer.appcelerator.com/blog/2011/06/new-defaults-for-android-layouts-in-1-7.html

A: well, as far as I googled, the solution is :
1.detect the specific screen resolution:
// app/alloy.js
Alloy.Globals.isIos7Plus = (OS_IOS && parseInt(Ti.Platform.version.split(".")[0]) >= 7);
Alloy.Globals.iPhoneTall = (OS_IOS && Ti.Platform.osname == "iphone" && Ti.Platform.displayCaps.platformHeight == 568);

2.write query style tss:
// Query styles
"#info[if=Alloy.Globals.isIos7Plus]" : {
    font : { textStyle : Ti.UI.TEXT_STYLE_FOOTNOTE }
},
"#title[if=Alloy.Globals.isIos7Plus]" : {
    top: '25dp', // compensate for the status bar on iOS 7
    font : { textStyle : Ti.UI.TEXT_STYLE_HEADLINE }
},
"#content[if=Alloy.Globals.isIos7Plus]" : {
    font : { textStyle : Ti.UI.TEXT_STYLE_CAPTION1 }
},
"ScrollView[if=Alloy.Globals.iPhoneTall]" : {
    height : '500dp'
}

refer to:  http://docs.appcelerator.com/titanium/3.0/#!/guide/Alloy_Styles_and_Themes-section-35621526_AlloyStylesandThemes-Platform-SpecificStyles


text:
Q: string concatenation problem Please how this string concatenation taking place?
i am really confuse what is happening why that slash i there and how the double quotes are used
SessionStateItemCollection items = new SessionStateItemCollection();

items["LastName"] = "Wilson";
items["FirstName"] = "Dan";

foreach (string s in items.Keys)
  Response.Write("items[\"" + s + "\"] = " + items[s].ToString() + "
");

//here i am looking for explanation please elaborate me on this please
Response.Write("items[\"" + s + "\"] = " + items[s].ToString() + "
");

A: Only the \" (doubles quotes immed after the backslash) is escaped.

A: The backslash escapes the ".  This tells the compiler that you just want a literal double-quote, rather than ending the string literal.

A: The slash is escaping the quote. Basically it is going to write the name in quotes inside brackets. For your example the output would be:
items["Wilson"] = Wilson

The escaping happens for the character directly after the backslash \. So \" is escaped to ". The following " is stopping the string and you are appending the s variable which in turn is the current item in the foreach loop.
Here is a article on escape characters.


text:
Q: How to override value of read-only field in view depending on query param? I have this model that has a read-only field where I calculate some property.
class BlastEvent(Event):
    tonnes = models.FloatField()
    blast_type = models.ForeignKey(BlastType)

    @property
    def size(self):
        return self.tonnes / BlastEvent.objects.all().aggregate(Max('tonnes'))['tonnes__max']

This is my serializer:
class BlastEventSerializer(serializers.HyperlinkedModelSerializer):

    size = serializers.ReadOnlyField()

    included_serializers = {'blast_type': BlastTypeSerializer}

    blast_type = ResourceRelatedField(
        queryset=BlastType.objects,
        related_link_view_name='blastevent-blasttype-list',
        related_link_url_kwarg='pk',
        self_link_view_name='blastevent-relationships'
    )

    class Meta:
        model = BlastEvent
        fields = ('url', 'id', 'tonnes', 'blast_type', 'size')

    class JSONAPIMeta:
        included_resources = ['blast_type']

And this is my view:
class BlastEventViewSet(EventViewSet):
    queryset = BlastEvent.objects.all()
    serializer_class = BlastEventSerializer

Now I need to re-calculate and override this read-only field depending on query parameter. I'm not sure where is the proper place to do it. I tried to do it in get_queryset() method of my view like this:
class BlastEventViewSet(EventViewSet):
    queryset = BlastEvent.objects.all()
    serializer_class = BlastEventSerializer

    def get_queryset(self):
        queryset = self.queryset
        instrument_id = self.request.GET.get('instrument_id')
        if instrument_id:
            for e in queryset:
                e.size = e.size + Instrument.objects.get(pk=instrument_id).distance
        return queryset

but it doesn't work. It says 'AttributeError: can't set attribute':
Traceback:

File "/home/nargiza/virtualenvs/myenv/local/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner
  41.             response = get_response(request)

File "/home/nargiza/virtualenvs/myenv/local/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "/home/nargiza/virtualenvs/myenv/local/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/home/nargiza/virtualenvs/myenv/local/lib/python2.7/site-packages/django/views/decorators/csrf.py" in wrapped_view
  58.         return view_func(*args, **kwargs)

File "/home/nargiza/virtualenvs/myenv/local/lib/python2.7/site-packages/rest_framework/viewsets.py" in view
  86.             return self.dispatch(request, *args, **kwargs)

File "/home/nargiza/virtualenvs/myenv/local/lib/python2.7/site-packages/rest_framework/views.py" in dispatch
  489.             response = self.handle_exception(exc)

File "/home/nargiza/virtualenvs/myenv/local/lib/python2.7/site-packages/rest_framework/views.py" in handle_exception
  449.             self.raise_uncaught_exception(exc)

File "/home/nargiza/virtualenvs/myenv/local/lib/python2.7/site-packages/rest_framework/views.py" in dispatch
  486.             response = handler(request, *args, **kwargs)

File "/home/nargiza/virtualenvs/myenv/local/lib/python2.7/site-packages/rest_framework/mixins.py" in list
  40.         queryset = self.filter_queryset(self.get_queryset())

File "/home/nargiza/Development/geotechnical-data-platform-api/events/views.py" in get_queryset
  205.             e.size = ...

Where I can override this field's value depending on query parameter?

A: Properties require setters for assignment. Try adding a setter to BlastEvent like this:
https://docs.python.org/3/library/functions.html#property
class BlastEvent(Event):
    tonnes = models.FloatField()
    blast_type = models.ForeignKey(BlastType)

    def _get_size(self):
        return self.tonnes / BlastEvent.objects.all().aggregate(Max('tonnes'))['tonnes__max']

    @property
    def size(self):
        if callable(self._get_size):
            return self._get_size()
        else:
            return self._get_size

    @size.setter
    def size(self, value):
        self._get_size = value

A: The solution I came up with is to override to_representation() method of serializer:
def to_representation(self, instance):
    ret = super(BlastEventSerializer, self).to_representation(instance)

    instrument_id = self.context['request'].query_params.get('instrument_id')
    if instrument_id:
        ret['size'] = 77  # some custom calculations
    return ret


text:
Q: Ruby SQL query inter related attributes I have three tables skills_development, training_programs and participants. skills_development has many training_programs and training_programs have many participants. training_programs also have different categories A-F, and participants have different genders.
I want to be able to access all participants within a skills development that are female and that belong to training programs A-C.
Is there a way to do this with a single query?
I can do
tp = @skills_development.training_programs.where("category = ?", "A")

to get all the training programs with category A
p = @skill_development.participants.where("gender = ?", "female")

and all female participants
But how to mix these together is frying my brain. i thought you could just
tp = @skills_development.training_programs.where("category = ?", "A")
tp.participants.where("gender = ?", "female")

But i get
NoMethodError: undefined method `participant' for #<ActiveRecord::Relation:0x007fc7e6bcdaa8>

any ideas?

A: You should join the tables.
http://guides.rubyonrails.org/active_record_querying.html#joining-tables
This should work:
participants = Participant.joins(:training_programs).
  where('training_programs.skills_development_id' => @skills_development.id).
  where('training_programs.category' => %w(A B C)).
  where('participants.gender' => 'female')


text:
Q: pandas extractall() is not extracting all cases given a regex? I have a nested list of strings which I would like to extract them the date. The date format is:

Two numbers (from 01 to 12) hyphen tree letters (a valid month)
  hyphen two numbers, for example: 08-Jan—07 or 03-Oct—01

I tried to use the following regex:
r'\d{2}(—|-)(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-\d{2,4}'

Then I tested it as follows:
import pandas as pd
df = pd.DataFrame({'blobs':['6-Feb- 1 4 Facebook's virtual-reality division created a 3-EBÚ7 11 network of 500 free demo stations in Best Buy stores to give people a taste of VR using the Oculus Rift 90 GT 48 headset. But according to a Wednesday report from Business Insider, about 200 of the demo stations will close after low interest from consumers. 17-Feb-2014',
                         'I think in a store environment getting people to sit down and go through that experience of getting a headset on and getting set up is quite a difficult thing to achieve," said Geoff Blaber, a CCS Insight analyst. 29—Oct-2012 Blaber 32 FAX 2978 expects that it will get easier when companies can convince  18-Oct-12 credit cards. '
                            ]})
df

Then:
df['blobs'].str.extractall(r'\d{2}(—|-)(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-\d{2,4}')

Nevertheless, they are not working. The previous regex doesn't give me anything (i.e. just hypens -):
    Col
0   NaN
1    -
2    -
3   NaN
4   NaN
5    -
...
n    -

How can I fix them in order to get?:
           Col
0 6-Feb-14, 17-Feb-2014
1 29—Oct-2012, 18-Oct-12

UPDATE
I also tried to:
import re
df['col'] = df.blobs.apply(lambda x: re.findall('\d{2}(—|-)(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-\d{2,4}',x))
s = df.apply(lambda x: pd.Series(x['col']),axis=1).stack().reset_index(level=1, drop=True)
s.name = "col"
df = df.drop('col')
df

Nevertheless I also got:
ValueError                                Traceback (most recent call last)
<ipython-input-4-5e9a34bd159f> in <module>()
      3 s = df.apply(lambda x: pd.Series(x['col']),axis=1).stack().reset_index(level=1, drop=True)
      4 s.name = "col"
----> 5 df = df.drop('col')
      6 df

/usr/local/lib/python3.5/site-packages/pandas/core/generic.py in drop(self, labels, axis, level, inplace, errors)
   1905                 new_axis = axis.drop(labels, level=level, errors=errors)
   1906             else:
-> 1907                 new_axis = axis.drop(labels, errors=errors)
   1908             dropped = self.reindex(**{axis_name: new_axis})
   1909             try:

/usr/local/lib/python3.5/site-packages/pandas/indexes/base.py in drop(self, labels, errors)
   3260             if errors != 'ignore':
   3261                 raise ValueError('labels %s not contained in axis' %
-> 3262                                  labels[mask])
   3263             indexer = indexer[~mask]
   3264         return self.delete(indexer)

ValueError: labels ['col'] not contained in axis

A: When you use Series.str.extract or Series.str.extractall, the captured substrings are returned, not the whole matches. So, you need to make sure you capture (i.e. add ( and ) around) the part of pattern you need to grab.
Now, several expected matches in your rows make it more difficult to do with extractall, it seems you may use Series.str.findall that may return the whole matches if no capturing group is defined in the pattern.
Use
rx = r'\b\d{1,2}[-–—](?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[-–—](?:\d{4}|\d{2})\b'
df['Col'] = df['blobs'].str.findall(rx).apply(','.join)

The .apply(','.join) will convert lists to comma-separated strings in Col column.
The pattern means:

*

*\b - a word boundary

*\d{1,2} - 1 or 2 digits

*[-–—] - a hyphen, em- or en-dash

*(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)  - any of the 12 month shortened names

*[-–—] - a  hyphen, em- or en-dash

*(?:\d{4}|\d{2}) - 4 or 2 digits

*\b - a word boundary


text:
Q: Ordering and grouping in mongoid I want groups of person which is ordered by age
I tried something like this
Person.only(:name).asc(:age).group

But didn't ordered by age.
How can I do it?
I'm using mongoid beta 19.

A: If I remember correctly, once you have called
Person.only(:name)

Mongoid basically considers the collection to only have that field so once you have tried to sort by age, there is no age field to sort by so it does nothing.
Try
Person.asc(:age).only(:name).group

Or possibily
Person.asc(:age).only([:name, :age]).group


text:
Q: how to navigate to login in angular In my app-component I verify if the user is logged in (i use tokens).
If the user is logged he can access the app pages, if not, I want to redirect him to the login page.
For the moment, my app redirects him to the Not Found page.
Also in routing module I have made my routes for several pages
If the user is not logged and tries to access the path 'm-dashboard' will be activated a guard that verifies his role using a switch statement that has default this.router.navigate([Urls.LOGIN])
Urls is an external file where I have all my paths for the app.
i've thought that calling GoToLogin() method will solve this, but didn't.
How can I solve this without having to modify the switch's default? I don't want to do that because I have more guards using that.
app-routing.module
const routes: Routes = [
  { path: '', redirectTo: '/m-dashboard', pathMatch: 'full' },
  {
    path: 'login',
    loadChildren: () => import('./auth/auth.module').then(m => m.AuthModule)
  },
  {
    path: 'm-dashboard',
    canActivate: [MGuard],
    loadChildren: () => import('./m-dashboard/m-dashboard.module').then(m => m.MDashboardModule)
  },
  {
    path:'v-dashboard',
    canActivate: [VGuard],
    loadChildren: () => import('./v-dashboard/v-dashboard.module').then(m => m.VDashboardModule)
  },
  { path: 'error', component: ErrorPageComponent },
  { path: '**', component: PageNotFoundComponent }
];

app.component
    export class AppComponent implements OnInit {  ngOnInit() {
        StorageHelper.getToken()
          ? this.getUserDetails()
          : this.goToLogin();
      }
     goToLogin() {
        this.loading = false;
        this.router.navigate([Urls.LOGIN]);
        }

  }

m-guard
 canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
      let customerType = StorageHelper.getCustomerType();
      let userRole = this.userService.computeUserRole(customerType);

      switch(userRole) {
        case UserRoles.M:
          return true;
          break;
        case UserRoles.V:
          this.router.navigate([Urls.V_DASHBOARD]);
          return false;
          break;
        default:
            this.router.navigate([NOT_FOUND]);
          return false;
      }
  }

A: The canActivate array can have several guards - you could create another guard just for this task, and test StorageHelper.getToken() there (checking it only in AppComponent's ngOnInit won't do - the user can simply edit the URL bar). Sth like this:
canActivate(): < boolean | URLTree > {
    return StorageHelper.getToken()
        ? true
        : this.router.parseUrl(Urls.LOGIN)
}


text:
Q: Dirac's quantization rule I first recall Dirac's quantization rule, derived under the hypothesis that there would exit somewhere a magnetic charge: $\frac{gq}{4\pi} = \frac{n\hbar}{2} $ with $n$ a natural number.
I am wondering how the quantization of electric charge can be deduced from it. The quantization of the product $gq$ is certainly not enough; what else is demanded?

A: i) First of all, the Dirac quantization rule
$$\tag{1} \frac{qg}{2\pi\hbar} ~\in~ \mathbb{Z} $$
for magnetic monopoles can be generalized to the Dirac-Zwanziger-Schwinger quantization condition
$$\tag{2} \frac{q_1g_2-q_2g_1}{2\pi\hbar} ~\in~ \mathbb{Z} $$
for dyons. (In a slight misuse of terminology, we shall in the following also include purely electrically charged particles and pure magnetic monopoles into the definition of dyons.)
II) Let $\Gamma=\{(q,g)\}$ denote the set of electric and magnetic charges for dyons. It is natural to think of $\Gamma$ as a subset of the plane $\mathbb{R}^2$. The left-hand side of (2) has a geometric meaning as a signed area spanned by two vectors $(q_1,g_1)$ and $(q_2,g_2)$.
III) Now assume that $\Gamma\backslash\{(0,0)\} $ is non-empty, i.e. there exists a dyon $(q_1,g_1)\neq(0,0)$ to begin with. What points $(q_2,g_2)\in\Gamma$ of $\mathbb{R}^2$ would not conflict with condition (2)? The answer is a set of equidistant discrete lines parallel to the vector $(q_1,g_1)$.
IV) Now assume that $\Gamma$ contains at least two linearly independent vectors $(q_1,g_1)$ and $(q_2,g_2)$. What points $(q_3,g_3)\in\Gamma$ of $\mathbb{R}^2$ would not conflict with condition (2)? The answer is a discrete grid/lattice of intersection points, namely precisely where the corresponding two sets of equidistant discrete parallel lines from section III meet. In other words, the charges are quantized.
V) As a special case, if there exist at least one purely electrically charged particle and at least one pure magnetic monopole, we are in the situation described in section IV, and hence the charges must be quantized.

A: I think this is a valid open question. If it turned out that there wasn't just one magnetic charge g, but a continuum of magnetic charge, then the quantization condition would not be a sufficient explanation for e.
However to actually prove whether or not a continuum of magnetic charge leads to any contradiction would require at the very least solving an n-body problem with multiple magnetic charges, which is not a trivial  matter even for professionals in the field. (or at least a 3 body problem with 2 magnetic charges to see whether a contradiction or reaffirmation of the quantization arises)
If this subject has been touched upon in the literature it would be nice for someone with the knowledge to give some citations as reference material for those interested.

A: 1) Assume there exists a minimum nonzero electric charge, $q_0$. Therefore, the minimum magnetic charge is
$$ g_0 = \frac{2\pi}{q_0}. $$
2) Secondly, if the theory preserves C and CP. Then the dyon $(q,g_0)$ automatically implies a conjugate dyon $(-q,g_0)$. Applying Dirac-Zwanziger (see, in @Qmechanic answer) condition for these two dyons
$$ 2qg_0 = 2\pi n, $$
or,
$$ q = \frac{n}{2}q_0. $$
So we have two possibilities, the electric charge $q$ takes integer multiples of $q_0$, or takes odd integer multiples of $q_0/2$.

A: I will try to answer from a pure mathematical perspective. The quantization rule states that for any possible $q$ and $g$, there is some $n\in\mathbb{Z}$ such that $qg=nh$.
Now consider the set $X=\{n\in\mathbb Z^+|\exists q\in Q^+, g\in G^+\ \mathrm{s.t.} \ qg=nh\}$, where $Q^+$ contains all the possible positive charges and $G^+$ contains all the possible positive magnetic charges (of magnetic monopoles). Consider the minimal element $n_0$ in the set $X$, then there is some $q_0$ and $g_0$ that satisfies $q_0g_0=n_0h$.
Note that it is often assumed that $n_0=1$, but it is not needed in this proof.
Now consider some $g\neq g_0$. Then $q_0g=nh$ for some $n$. Since $n_0$ is minimal, we have $n>n_0$. Since both $n$ and $n_0$ are integers, we have $n=pn_0+r, 0\leq r<n_0, p\in\mathbb{Z}^+$. If $r\neq 0$, then $0<q_0(g-pg_0)=rh<nh$, contradicting that $n$ is minimal. Therefore $r=0$. and $g=pg_0$, so $g$ is quantized in the unit of $g_0$. Similarly, we can prove that $q$ must be multiples of $q_0$.
Mathematically speaking, the only assumptions used above are that if $q$ is a valid charge, then $-q$ is also a valid charge, and that if $q_1$ and $q_2$ are valid charges, then $q_1+q_2$ is a valid charge. The same for $g$. I think these assumptions should be pretty natural given the physical nature of $q$ and $g$.


text:
Q: Setting up jupyter-notebook "Binder" in Github I am trying to obtain the correct GitHub repo or URL from my GitHub repository for "mybinder.org" so that I can create a link in my repository to launch jupyter-notebook from within my repository. I seem to not be able to set things up correctly.

A: I've just made my first binder repo, a very simple one, you could use it as a model.
The steps are:

*

*create a repo in github containing your jupyter notebooks.

*create a folder called "binder" with a requirements.txt in this repo indicating the packages used in your notebook - or a environment.yml if you use conda instead of pip. See the examples in the docs. Although it is possible to put the requirements.txt in the root folder, creating the "binder" folder reduced the building time from 2-4 minutes to 30s-1 minute.

*After you create your repo on github, the only thing you need to do is paste its url (e.g, https://github.com/lincolnfrias/binder/) on mybinder.org e click the launch button.
Please, don't hesitate to ask if you need any clarification.


text:
Q: Programmable/scriptable mail server I have the following scenario:
Users send email messages to the special mail addresses (each address is associated with a user).
When the message arrives to the server I need to extract a certain information from the message body and store it in the database.
I am looking for a mail server (or client) that matches following conditions:

*

*Free/open-source

*Users/inboxes can be created/deleted via some API on the fly

*Works in unix/mac environment (Ubuntu/MacOS X in my case)

*Allows me to set up hooks on message queue (via API or receive the data via some I/O channel)

*Has good performance and/or scalability potential

*Does not have a dependency on Java or other heavy framework.

Note that I do not need a full-fledged mail server i.e. all I need is messages processing.

A: Finally, I decided to use http://mailgun.net/ service which provides exactly what I need


text:
Q: Objective C : How to Insert text in Movie Player View? I am making a Apache Cordova Application.
On this Application, I used the plugin : Cordova Streaming Media plugin
Link is : https://github.com/nchutchind/Streaming-Media-Cordova-Plugin
I want to insert a "Hello World!" label on my movie but I don't know how to do that.
I think the script is : StreamingMedia.m
Link is : https://github.com/nchutchind/Streaming-Media-Cordova-Plugin/blob/master/src/ios/StreamingMedia.m
And function is : startPlayer()
Can you tell me where is my error :
-(void)startPlayer:(NSString*)uri {
    NSURL *url = [NSURL URLWithString:uri];

    moviePlayer =  [[MPMoviePlayerController alloc] initWithContentURL:url];

// Listen for playback finishing
   [[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(moviePlayBackDidFinish:)
                                             name:MPMoviePlayerPlaybackDidFinishNotification
                                           object:moviePlayer];
// Listen for click on the "Done" button
   [[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(doneButtonClick:)
                                             name:MPMoviePlayerWillExitFullscreenNotification
                                           object:nil];
// Listen for orientation change
   [[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(orientationChanged:)
                                             name:UIDeviceOrientationDidChangeNotification
                                           object:nil];

    moviePlayer.controlStyle = MPMovieControlStyleDefault;

    moviePlayer.shouldAutoplay = YES;
if (imageView != nil) {
    [moviePlayer.backgroundView setAutoresizesSubviews:YES];
    [moviePlayer.backgroundView addSubview:imageView];
}

    moviePlayer.backgroundView.backgroundColor = backgroundColor;

    [self.viewController.view addSubview:moviePlayer.view];

// Note: animating does a fade to black, which may not match background color
    [moviePlayer setFullscreen:YES animated:NO];

     // Here my code :

     UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 100, 0, 0)];
     label.text = @"Hello World!";

     CGRect frame = label.frame;

     frame.origin.x = 100;
     frame.origin.y = 50;

     label.frame = frame;

     [self.viewController.view addSubview:label];
}

Thank You!

A: You have two choices:

*

*You can add a view to the app window/root controller view.

*Create custom controller and add to his view MPMoviePlayerController like
subView.

A: Errors:

*

*Your UILabel has 0x0 sizes. Just set up sizes :)

*You send _rangeSlider to back of view via sendSubviewToBack. Remove it and it's start working.

And it seems you can just add subview to the MPMoviePlayerController view.


text:
Q: Create a folder and get its path after that using python I am trying to create a folder inside of a selected folder, name it after the date of creation and get an absolute path of this newely created folder. My code is down below:
today = datetime.now()
dateAndTime = today.strftime("%m-%d-%Y")
workingdir = os.path.dirname(os.mkdir(delovnaMapa + "/" + dateAndTime))
print(workingdir)

This code creates a folder inside of the selected one, but I get following error message:
Traceback (most recent call last):
  File "C:\Program Files\ArcGIS\Pro\bin\Python\envs\arcgispro-py3\lib\site-packages\IPython\core\interactiveshell.py", line 3437, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-19-f0c6828b61d4>", line 3, in <module>
    workingdir = os.path.dirname(os.mkdir(delovnaMapa + "/" + dateAndTime))
  File "C:\Program Files\ArcGIS\Pro\bin\Python\envs\arcgispro-py3\lib\ntpath.py", line 223, in dirname
    return split(p)[0]
  File "C:\Program Files\ArcGIS\Pro\bin\Python\envs\arcgispro-py3\lib\ntpath.py", line 185, in split
    p = os.fspath(p)
TypeError: expected str, bytes or os.PathLike object, not NoneType

What am I doing wrong?

A: os.mkdir function creates a directory, its return is None.
For your work to be done, you should be using
os.mkdir(delovnaMapa + "/" + dateAndTime)
then, use
os.path.dirname(delovnaMapa + "/" + dateAndTime)


text:
Q: How to launch a node with a parameter in ROS2? Migrating ros1 package to ros2 and couldn't figure how to launch with a paramter in ros2.
With ros1 I have a launch file that refers to a config file and from cpp code I use node.getParam
launch file:
<launch>
    <arg name="node_name" default="collector" />
    <arg name="config_file" default="" />
    <node name="$(arg node_name)" pkg="collector" type="collector" respawn="true">
      <rosparam if="$(eval config_file!='')" command="load" file="$(arg config_file)"/>
    </node>
</launch>

config file:
my_param: 5

cpp code:
double my_param = 0;
n.getParam("my_param", my_param);

My question is how would that translate to ROS2?

A: For ROS2, please see this link and this link.
For reference, as of this post, ROS2 has had three releases. While Crystal Clemmens supports Python nodes, the previous release, Bouncy Bolson, does not. Similarly, future releases may add additional support for how/where to input config files.
The ROS2 Wiki references using a .yaml config file to store parameters and, when running the ROS2 node, passing the config file as a command line parameter.
ROS2 Wiki: Node Arguments
Example demo_params.yaml file:
talker:
    ros__parameters:
        some_int: 42
        a_string: "Hello world"
        some_lists:
            some_integers: [1, 2, 3, 4]
            some_doubles : [3.14, 2.718]`

Then run the following:
ros2 run demo_nodes_cpp talker __params:=demo_params.yaml

A: I wanted to expand a bit on the answer from @PSA which is really good.
As stated, put your parameters in a .yaml file
talker:
    ros__parameters:
        some_int: 42
        a_string: "Hello world"
        some_lists:
            some_integers: [1, 2, 3, 4]
            some_doubles : [3.14, 2.718]

To use it in a ROS2 launch file, now built in Python, pass the .yaml file path as an argument parameters as described here https://github.com/ros2/launch/blob/master/launch_ros/launch_ros/actions/node.py like so:
ld = LaunchDescription([
        launch_ros.actions.Node(
            package='nmea_navsat_driver', node_executable='nmea_serial_driver_node', output='screen',
            parameters=["config.yaml"])
    ])

here config.yaml is the parameter file.
If you want to start your node manually, start it as stated in @PSAs answer:
ros2 run demo_nodes_cpp talker __params:=demo_params.yaml
update: parameters expect a list of config files.


text:
Q: Is there a way to convert an IEnumerable into a collection of XElements? I'm trying to persist an XML file to disk using LINQ. I have a class of business objects including collections of strings (List) that I want to convert into XML. Is there a simple, one liner to convert this list into a list of XML Elements?
For example, my list may be:
List<string> collection = new List<string>() {"1", "2", "3"}

The output should be:
<Collection>
     <Element>1</Element>
     <Element>2</Element>
     <Element>3</Element>
</Collection>

At the moment, I'm using this sort of syntax:
XElement Configuration =
    new XElement("Configuration",
    new XElement("Collection",  collection.ToArray()
    ),
);

However, this concatenates the collection into a a single string element.

A: XElement Configuration = new XElement("Collection",
      collection.Select(c=>new XElement("Element", c)));


text:
Q: Unexpected images order with ConTeXt startcombination I want to use combinations to show a chronological overview of the Eastern Roman Empire at different ages. The trouble is my pictures are displayed in a apparently random order.
\defineexternalfigure[carte][width=0.45 \textwidth ]

\starttext
\placefigure[here][fig:cartes]
   {Extension de l'Empire romain d'Orient à différentes dates. Droits d'auteurs :}
   {\startcombination[2*4]
      {\externalfigure[./illustrations/cartes-empire-romain-orient-0.png][carte]}
      {\externalfigure[./illustrations/cartes-empire-romain-orient-1.png][carte]}
      {\externalfigure[./illustrations/cartes-empire-romain-orient-2.png][carte]}
      {\externalfigure[./illustrations/cartes-empire-romain-orient-3.png][carte]}
      {\externalfigure[./illustrations/cartes-empire-romain-orient-4.png][carte]}
%      {\externalfigure[./illustrations/cartes-empire-romain-orient-5.png][carte]}
      {\externalfigure[./illustrations/cartes-empire-romain-orient-6.png][carte]}
      {\externalfigure[./illustrations/cartes-empire-romain-orient-7.png][carte]}
      {\externalfigure[./illustrations/cartes-empire-romain-orient-8.png][carte]}
   \stopcombination}
\stoptext

I would  expect some
| 0 | 1 |
| 2 | 3 |
| 4 | 6 |
| 7 | 8 |
Here is what I get (pay attention to the numbers).

The wider line between row 2 and 3 may be a clue. Did I miss something?

A: I luckily found the issue while adding titles for each picture (something I didn't plan at first). The next externalfigures where taken as title, hence the wider line and unexpected order. If I add empty titles, everything goes as expected.
\defineexternalfigure[carte][width=0.45 \textwidth ]

\starttext

\placefigure[fig:cartes]
   {Extension de l'Empire romain d'Orient à différentes dates. Droits d'auteurs :}
   {\startcombination[2*4]
      {\externalfigure[./illustrations/cartes-empire-romain-orient-0.png][carte]}{}
      {\externalfigure[./illustrations/cartes-empire-romain-orient-1.png][carte]}{}
      {\externalfigure[./illustrations/cartes-empire-romain-orient-2.png][carte]}{}
      {\externalfigure[./illustrations/cartes-empire-romain-orient-3.png][carte]}{}
      {\externalfigure[./illustrations/cartes-empire-romain-orient-4.png][carte]}{}
%      {\externalfigure[./illustrations/cartes-empire-romain-orient-5.png][carte]}{}
      {\externalfigure[./illustrations/cartes-empire-romain-orient-6.png][carte]}{}
      {\externalfigure[./illustrations/cartes-empire-romain-orient-7.png][carte]}{}
      {\externalfigure[./illustrations/cartes-empire-romain-orient-8.png][carte]}{}
   \stopcombination}

\stoptext

ConTeXt wiki info may be outdated, because it stats that we can bypass the empty caption. I shall update it ASAP.


text:
Q: Probability of choosing a specific point on a sphere Problem
My question is about the probability of choosing a specific point on a sphere.  Let's suppose I divide my sphere into 4 equally-sized sectors (so 4  semi-hemispheres), and I choose a point randomly distributed on the semi-hemisphere surface, while the selection of the semi-hemisphere depends on a probability distribution.
My question is: what is the probability of choosing that specific point?
Example
I divide my sphere into 4 semi-hemispheres. The probabilities of choosing a specific semi-hemisphere are $q = [0.2, 0.3, 0.4, 0.1]$, meaning the probability of choosing the first semi-hemisphere is 0.2, the second 0.3, etc..
After choosing a semi-hemisphere, I choose a random point on the surface of it.
My solution
My solution consists of two steps:
1) First of all I choose a semi-hemisphere. The probability is $$p1 = \frac{prob(S1)}{Total Probability}$$ where $prob(S1)$ is a specific probability sampled from $q$, choosing a random number in range {0,1} and checking when this number is lower then the cumulative probability (sorry if this is not clear, I'll do the actual calculus below). $TotalProbability$ is the normalized sum (which, in this case, is already normalized).
2) In the second step I need to choose a random point in this semi-hemisphere. In this case, the probability would be:
$$p2 = \frac{1}{\frac{Area}{NumberPartitions}} = \frac{1}{\frac{4\pi R^2}{4}} = \frac{1}{\pi R^2}$$
For this reason, the combined probability should be:
$$ p = p1 * p2$$
Let's suppose the random number sampled is 0.43. Checking the cumulative probability of the probability bins in $q$, this number belongs to the second bin, 0.3. The probability would be:
$$ p = p1 * p2 = \frac{0.3}{1} * \frac{1}{\pi R^2} $$
Is this correct, or I am missing something? Thanks
EDIT:
Bonus question 1
What if I can only choose a specific point in each semi-hemisphere (so I don't have the option to randomly choose a point on the semi-hemisphere surface)? In this case, my intuition suggests that the solution would be only the first part of the previous equation, so $p = p1$. Is this correct?
Bonus question 2
What if I choose only a random point on the semi-hemisphere with the highest relative probability? This case really confuses me. Indeed, there is no probability involved in choosing a semi-hemisphere, since I just take the highest one. But this choice depends on the probability distribution. Should I only consider the second part of the previous equation, so $ p = p2$?


text:
Q: Does spring support invoke dynamic for groovy-backed beans? Is it possible to configure Groovy beans declared with lang namespace or manually with GroovyScriptFactory in such a way, that they use invoke dynamic support?
<lang:groovy id="messenger" script-source="classpath:Messenger.groovy">

I have not found any reliable documentation on this case.
And, does a GroovyClassLoader provided with groovy-all:indy maven artifact uses this feature, or it can be used only with groovy compiler?

A: In order to activate the invoke-dynamic support, you have to :

*

*Use groovy-indy.jar

*Set the system property groovy.target.indy to true or the CompilerConfiguration.DEFAULT.getOptimizationOptions().put("indy", true)
This will enable this function for all invocations of the groovy compiler (and Spring will use this option). I don't think there is a way to configure this option through the ScriptEngine, for only a subset of scripts.
If you use directly a GroovyClassLoader, you can provide this option through the CompilerConfiguration.optimizationOptions.indy property


text:
Q: PHP - Get the contents of an post from instagram page using simple php is there a way to get instagram page the contents of an post using simple php
i did some search and i found this script
 $url = 'https://www.instagram.com/pagename/';
 $str = file_get_contents($url);
 $count = 0;
 if(preg_match('#followed_by": {"count": (.*?)}#', $str, $match)) {
    $count = $match[1]; // get the count from Regex pattern
  }
echo $count;

but it is getting only number of follower is there a way
to get  the contents of an Instagram post using same concept ?

A: Here's a code that works (today). But as @Andy said, it's not reliable and it's dirty af :)
<?php

$source = file_get_contents("https://www.instagram.com/p/POST_ID/");

preg_match('/


text:
Q: How can I run Python code on a windows system? I am used to using PHP and it is easy to set up, I can just run an exe package like Xampp and have apache and PHP running in 5 minutes on my windows system.  Is there something similar to Python?

A: Unlike PHP, Python's primary purpose is a general-purpose tool for running on the desktop/server, not necessarily as a web application. It has bindings to many powerful GUI toolkits (Qt and wx are two examples of free and popular toolkits that work great on Windows), and so on. Therefore you just download it (either from python.org or from activestate), install it, and run it. That's it.
That said, Python is actually great for web apps too. See the Django tutorial for running a simple web-app on your PC in just a few minutes. Python actually comes with a simple web-server built-in, and it supports SQLite out of the box as well, so you can have a fully functional DB-backed web-application running without actually installing anything else. Naturally, if you need to use tools like MySQL and Apache, these are easy to connect to Python on the desktop too. Just start with that Django tutorial and everything will be clear.

A: Yes, you can find python from http://python.org
and If you like to make executable files from .py source file you may use py2exe

A: You don't say in your question what you are going to use Python for, so most answers above are completely correct in pointing out that you install Python by downloading it from Python.org. But you seem to expect more. Is it correct to assume you are going to use it to do web development?
In that case, prepare for a shock, because Python doesn't do things like PHP does at all. You want to use a web framework. There are loads of them for Python. Which on to use depends both on what you are going to do, and your personal taste.
The only "Download as one file and install to run" web system I know of that's based on Python is Plone. And Plone is great, but it's not a webframework, it's a content management system. But hey, maybe that's what you want? :-)
The other frameworks are usually easy to install as well.
(In the long run: If you are going to do web development, you'll be happier with something Unix based. Just saying.)

A: Download python installer and run python.

A: Nope no easy way out for you yet, Python is obviously not popular enough in Web dev. You should install mod_python and django. There are some nice step here.

A: Here's my opinionated answer:

*

*Download and install ActivePython

*Open Command Prompt and type pypm install django

*Follow the Django tutorial
Note that Django does not necessarily require a webserver like Apache, as it already includes one for development purposes. Nor do you necessarily have to install MySQL as Python already includes SQLite which is supported by Django.


text:
Q: C# BotFramework PromptDialog.Choice() Too Many Attempts Handler I'm currently working on a ChatBot, so basically I want a way to handle the "Too Many Attempts" message when the user hit the maximum attempts. Base on this documentation of the  PromptDialog.Choice() link here. The message can be change but there is no parameter or whatsoever to handle the next occurrence of the method.
I have tried to research about scorable-bot that I have researched but in my scope I cannot change the flow of the ChatBot, so I'm stuck at waterfall method in developing the ChatBot.
Any piece of advice will be nice. Thanks.
Also this is the piece of code I've working on:
[Serializable]
public class CustomPromptDialog : IDialog<string>
{
    public async Task StartAsync(IDialogContext context)
    {
        List<string> choices = new List<string>();
        choices.Add("Choice 1");
        choices.Add("Choice 2");
        PromptDialog.Choice(context, ResumeAfter, choices, "Title", "Wrong!", 5);

    }
    public async Task ResumeAfter(IDialogContext context, IAwaitable<string> result)
    {
            var choice = await result;
            //A Too Many Attempts handler here

            //Returns the choice to the caller
            context.Done(choice);
    }
}

A: I found a solution but I don't know if this a ethical solution.
So when the "Too Many Attempts" message occur, it throws an exception to the ResumtAfter. So I just need to take handle the exception. That's it, but for those who have a more good solution to my problem please share it.
[Serializable]
public class CustomPromptDialog : IDialog<string>
{
    public async Task StartAsync(IDialogContext context)
    {
        List<string> choices = new List<string>();
        choices.Add("Choice 1");
        choices.Add("Choice 2");
        PromptDialog.Choice(context, ResumeAfter, choices, "Title", "Wrong!", 5);

    }
    public async Task ResumeAfter(IDialogContext context, IAwaitable<string> result)
    {
            try{
                 var choice = await result;
                context.Done(choice);
            }catch(Exception e){
                // Code here after "Too Many Attempts" message
            }

    }
}


text:
Q: Best way to troubleshoot custom web part without original source code? We have been asked to troubleshoot a custom web part in SharePoint 2013 on-premises.  The problem is that we are unable to determine exactly what it's trying to do, as we were not given the source code (and the client cannot find it).  What are my best options in this scenario?
I understand we might be able to extract the web-part WSP from the farm using PowerShell, but I don't think that will help us with any compiled DLLs that it might contain? Also, am I likely going to be able to update the WSP afterwards and redeploy (in the event a code change is needed)?
Thanks in advance for any tips or tricks.

A: Download the WSP file from the production server CA using the PowerShell script, then you can rename .wsp file to .cab file. Extract it. Once extracted you will get all files and assembly. Either use REFLECTOR or ILSPY to get the code of assembly. So once you have code you can copy-paste in visual studio. This process is called reverse engineering.
Once you get the source code - first deploy this solution in the dev or test server and debug it - it will give you more clarity about the source code what exactly it is doing.
References:
Convert .wsp file into SourceCode?
SharePoint 2010: Reverse Engineering SharePoint WSP Packages


text:
Q: how to get WebApplicationContext outside current servlet context? There are two WARs deployed in Tomcat (or other server), foo1.war and foo2.war.
All spring beans are defined in foo1.war, but is it possible to get these spring beans in the servlet that deployed in foo2.war?
I cannot just use WebApplicationContextUtils to get the WebApplicationContext, right? They are different WAR.
thanks

A: Technically, you can get the WebApplicationContext of the other app, if you expose the servlet context and call servletContext.getContext("/otherapp").getAttribute(..), but that's ugly.
You can have instances of the same bean definitions if you simply move the common definitions to a common.xml and include it in both projects.
If you need to communicate some data betweent the two apps, use another mechanism: web services (soap, rest), messaging (jmx).

A: Adding to @Bozho answer: you can also share instance data (e.g. singletons), when the two WARs are deployed in a single EAR. You should be able to expose the appContexts as statically visible fields in a class provided by EAR and thus visible to both WARs.


text:
Q: Redis SCAN command returning keys that don't match pattern So any ideas why this is happening?
localhost:0>scan 0 MATCH 20180223:c5*
 1)  "6553600"
 2)
localhost:0>scan 6553600 MATCH 20180223:c5*
 1)  "655360"
 2)    1)   "20180223:c5192875:o4998561"
  2)   "20180223:c1354879:o1160565"
  3)   "20180223:c1008709:o814395"
  4)   "20180223:c4485666:o4291352"
  5)   "20180223:c4560776:o4366462"
  6)   "20180223:c1646865:o1452551"
  7)   "20180223:c3515588:o3321274"
  8)   "20180223:c938489:o744175"
  9)   "20180223:c4895806:o4701492"
  10)   "20180223:c1767235:o1572921"

localhost:0>

Looking at https://redis.io/commands/scan it looks this scan command is right, so I don't get what is happening.
Any ideas?

A: This isn't supposed to happen, and I can't reproduce it locally (unstable branch) using the same keys and debug populate 10000.
I'm using the below Lua script for testing:
$ cat /tmp/lua
local cursor = 0
local rep = {}

repeat
  local r = redis.call('scan', cursor, 'match', '20180223:c5*')
  cursor = tonumber(r[1])
  for _, v in ipairs(r[2]) do
    table.insert(rep, v)
  end
until cursor == 0

return rep
$ redis-cli --eval /tmp/lua
1) "20180223:c5192875:o4998561"


text:
Q: Keycloak auth for picketlink old app I need some help from community!
My old applications are running on Jboss 5 and 6, using Java with Hibernate and Struts or Seam.
The application running on Jboss 6 are SPs of the IDP that is running on Jboss 5.
The users and roles are inside a database and with a specific query, the roles are returned and a SAML response is sent from IDP to SPs.
Everything is done with JAAS and Picketlink 2.5.
We want to move to Keycloak 3 and in fact I was able to replace everything inside the application, but since the applications are huge, I do not have time to do all together mainly due to needed regression testing time.
New applications come in React, protected with Keycloak and JWT.
So, imagine the scenario where I am logged with picketlink and SAML and want to access an new React application.
Since react application is protected with Keycloak server, it will push the user into Keycloak login server page.
How can I avoid it?
I was planning to make some code on server side ti authenticate into Keycloak server (with an authentication endpoint is available) and get the tokens from response and send it back to the client, before client gets the react app in fact.


text:
Q: REST service not working 400 bad request This is my web.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>

  <system.web>
    <compilation debug="true" targetFramework="4.0">
      <assemblies>
        <add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
      </assemblies>
    </compilation>
  </system.web>
  <system.serviceModel>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
    <services>
      <service name="WCFRestExample.HelloWorld">
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:60503"/>
          </baseAddresses>

        </host>
        <endpoint address="" binding="basicHttpBinding" contract="WCFRestExample.IHelloWorld"/>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
          <serviceMetadata httpGetEnabled="true" />
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="true" />

        </behavior>

      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
  <!--<system.webServer>
    <modules runAllManagedModulesForAllRequests="true" />
        <rewrite>
            <rules>
                <rule name="RequestBlockingRule1" patternSyntax="Wildcard" stopProcessing="true">
                    <match url="*" />
                    <conditions>
                        <add input="{URL}" pattern="*.aspx" />
                    </conditions>
                    <action type="Redirect" url="http://localhost/WCFRestExample/CustomError" />
                </rule>
            </rules>
        </rewrite>
  </system.webServer>-->
  <connectionStrings>
    <add name="PubsEntities" connectionString="metadata=res://*/PubsModel.csdl|res://*/PubsModel.ssdl|res://*/PubsModel.msl;provider=System.Data.SqlClient;provider connection string="Data Source=.\SQLEXPRESS;Initial Catalog=pubs;Integrated Security=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
  </connectionStrings>
</configuration>

This is my actual service:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.ServiceModel.Activation;

namespace WCFRestExample
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
    public class HelloWorld : IHelloWorld
    {
        [WebGet(UriTemplate="/GetData", ResponseFormat=WebMessageFormat.Xml)]
        public string GetData()
        {
            return "HIIII";
        }

        [WebGet(UriTemplate = "/GetPublisherList", ResponseFormat = WebMessageFormat.Xml)]
        public List<publisher> GetPublisherList()
        {
            using (PubsEntities entities = new PubsEntities())
            {
                return entities.publishers.ToList();
            }
        }
    }
}

This is my interface:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.ServiceModel.Activation;

namespace WCFRestExample
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
    [ServiceContract]
    public interface IHelloWorld
    {

        [OperationContract]
        string GetData();

        [OperationContract]
        List<publisher> GetPublisherList();

    }

}

This is my markup of svc:
<%@ ServiceHost Language="C#" Debug="true" Service="WCFRestExample.HelloWorld"
Factory="System.ServiceModel.Activation.WebServiceHostFactory"
CodeBehind="HelloWorld.svc.cs" %>

If I remove this section from web.config, it works fine:
 <service name="WCFRestExample.HelloWorld">
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:60503"/>
          </baseAddresses>

        </host>
        <endpoint address="" binding="basicHttpBinding" contract="WCFRestExample.IHelloWorld"/>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
      </service>

But the method that returns List still doesn't work. I am using EF 4.1. Can anybody tell me what is happening?
Thanks in advance :)

A: Change the binding from basicHttpBinding to webHttpBinding. If you want to do REST, you need to use the webHttpBinding.


text:
Q: Limit max available memory during development in Visual Studio for .NET Core / C# code We deploy our ASP .NET Core application in a Docker container.
We develop it using Visual Studio 2019. Also when we are coding and debugging it, we don't run it in a container.
But we would like to emulate the docker container memory limits as close as possible during development.
Do you have a suggestion on how to do this?


text:
Q: Estilizar cada linha diferente Tenho um texto em quatro linhas:
Pare de perder
    tempo
    por falta de

    Presença Digital.

Quero que cada uma dessas linhas tenha um tamanho de fonte diferente. Qual seria a forma mais correta de fazer?

A: Usando um div e divs internos (você também pode colocar uma classe específica em cada um):

.mensagem div:nth-child(1) {
  font-weight: bold;
}
.mensagem div:nth-child(2) {
  color: red;
}
.mensagem div:nth-child(3) {
  text-decoration: underline;
}
.mensagem div:nth-child(4) {
  font-size: 18pt;
}

    Pare de perder

    tempo

    por falta de

    Presença Digital.

A: O correto seria usando a tag
 de parágrafo.

 The Paragraph element
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/p

.container {
    margin-left: 4rem;
}
.container > p:first-child {
    position: relative;
    margin-left: -2rem;
}

Pare de perder

tempo

por falta de

Presença Digital.

A: Uma forma dinâmica e aleatória de fazer isso é usando JavaScript, trocando  por
. O pre permite pre-formatação exibindo o texto da forma que foi digitado, com espaços e quebras de linha.

var pre = document.querySelector("pre"),
teste = pre.innerHTML.trim().split("\n"),
final = '';
for(var x=0; x<teste.length; x++){
   final += ""+teste[x]+"\n";
}

pre.innerHTML = final;
pre{
   font-family: Tahoma, Arial, Helvetica;
}

Pare de perder
    tempo
    por falta de
    Presença Digital.

O valor 24 é o tamanho máximo da fonte e 12 o mínimo. Por exemplo, caso queira uma fonte máxima de 28 e mínima 9:
Math.floor(Math.random()*(28-9)+9)


text:
Q: How to make prettier recognise double curly brackets as JavaScript in Google Tag Manager? I use VS Code editor with prettier to format my code, but in Google Tag Manager, you wrap variables with double curly brackets around it. E.g to define a variable in Google Tag Manager, you do
{{my_own_variable}}

This causes issues with prettier as it's not valid JavaScript code. What can I do to make prettier simply see this as a variable? I am willing to write a plugin for this (if possible) or is there some kind of config I can use etc. Any help would be appreciated
Edit: I want to make prettier accept and format the file, just like normal JavaScript. E.g I don't want to comment out EVERY line of code where it contains a GTM variable, can prettier simply recognise that say {{my_own_variable}}.map() is the same as my_own_variable.map()


text:
Q: summary of lm to compare models instead of ANOVA What does it mean to use anova to compare models? For example, if I have two models
$$
   \text{model}_1 \colon y = b_0 + b_1 x_1 + b_2 x_2
$$
and
$$
   \text{model}_2 : y = b_0 + b_1 x_1 + b_2 x_2 + b_3 x_3
$$
and I use anova(model1, model2) in R, then is it the same as testing the null hypothesis $b_3 = 0$? If not, then what hypothesis exactly is getting tested here? And if yes, then why not simply use the summary of the lm function to test whether $b_3 = 0$, i.e. what is the whole point of using anova then?

A: The anova method for linear model objects in R is doing the usual F test comparing sum of squares of residuals (SSR), assuming nested models. (It will give an output also in the non-nested case, but that is less useful).
In your example, this is equivalent to a t-test of the hypothesis $b_3=0$, but is more general than that, so can be used in cases where there is no equivalent t-test. An example using your example, say you are interested in some possible effect of variable $x_3$, but you are not sure the effect is linear, so you represent the possible effect in your model with a quadratic polynomial, to represent some curvature. That is:
$$
   \text{model}_3 : y = b_0 + b_1 x_1 + b_2 x_2 + b_3 x_3 + b_4 x_3^2
$$
and now you can use anova(model, model3).
As a generalization, anova can also be called on generalized linear model (glm) objects, in that case it calculates an (approximation of) a likelihood ratio test, with the same interpretation as above.


text:
Q: Faster huge data-import than Get["raggedmatrix.mx"]? Can anybody advise an alternative to importing a couple of
GByte of numeric data (in .mx form) from a list of 60 .mx files, each about 650 MByte?
The - too large to post here - research-problem involved simple statistical operations
with double as much GB of data (around 34)  than RAM available (16).
To handle the data size problem I just split things up and used
a Get / Clear strategy to do the math.
It does work, but calling Get["bigfile.mx"] takes quite some time, so I was wondering if it would be quicker to use BLOBs or whatever with  PostgreSQL or MySQL or whatever database people use for GB of numeric data.
So my question really is:
What is the most efficient way to handle truly large data set imports in Mathematica?
I have not tried it yet, but I think that SQLImport from DataBaseLink will be slower than Get["bigfile.mx"].
Anyone has some experience to share?
(Sorry if this is not a very specific programming question, but it would really help me to move on with that time-consuming finding-out-what-is-the-best-of-the-137-possibilities-to-tackle-a-problem-in-Mathematica).

A: Here's an idea:
You said you have a ragged matrix, i.e. a list of lists of different lengths.  I'm assuming floating point numbers.
You could flatten the matrix to get a single long packed 1D array (use Developer`ToPackedArray to pack it if necessary), and store the starting indexes of the sublists separately.  Then reconstruct the ragged matrix after the data has been imported.

Here's a demonstration that within Mathematica (i.e. after import), extracting the sublists from a big flattened list is fast.
data = RandomReal[1, 10000000];

indexes = Union@RandomInteger[{1, 10000000}, 10000];
ranges = #1 ;; (#2 - 1) & @@@ Partition[indexes, 2, 1];

data[[#]] & /@ ranges; // Timing

{0.093, Null}

Alternatively store a sequence of sublist lengths and use Mr.Wizard's dynamicPartition function which does exactly this. My point is that storing the data in a flat format and partitioning it in-kernel is going to add negligible overhead.

Importing packed arrays as MX files is very fast.  I only have 2 GB of memory, so I cannot test on very large files, but the import times are always a fraction of a second for packed arrays on my machine.  This will solve the problem that importing data that is not packed can be slower (although as I said in the comments on the main question, I cannot reproduce the kind of extreme slowness you mention).

If BinaryReadList were fast (it isn't as fast as reading MX files now, but it looks like it will be significantly sped up in Mathematica 9), you could store the whole dataset as one big binary file, without the need of breaking it into separate MX files.  Then you could import relevant parts of the file like this:
First make a test file:
In[3]:= f = OpenWrite["test.bin", BinaryFormat -> True]

In[4]:= BinaryWrite[f, RandomReal[1, 80000000], "Real64"]; // Timing
Out[4]= {9.547, Null}

In[5]:= Close[f]

Open it:
In[6]:= f = OpenRead["test.bin", BinaryFormat -> True]

In[7]:= StreamPosition[f]

Out[7]= 0

Skip the first 5 million entries:
In[8]:= SetStreamPosition[f, 5000000*8]

Out[8]= 40000000

Read 5 million entries:
In[9]:= BinaryReadList[f, "Real64", 5000000] // Length // Timing
Out[9]= {0.609, 5000000}

Read all the remaining entries:
In[10]:= BinaryReadList[f, "Real64"] // Length // Timing
Out[10]= {7.782, 70000000}

In[11]:= Close[f]

(For comparison, Get usually reads the same data from an MX file in less than 1.5 seconds here.  I am on WinXP btw.)

EDIT  If you are willing to spend time on this, and write some C code, another idea is to create a library function (using Library Link) that will memory-map the file (link for Windows), and copy it directly into an MTensor object (an MTensor is just a packed Mathematica array, as seen from the C side of Library Link).

A: I think the two best approaches are either:
1) use Get on the *.mx file,
2) or read in that data and save it in some binary format for which you write a LibraryLink code and then read the stuff via that. That, of course, has the disadvantage that you'd need to convert your MX stuff. But perhaps this is an option.
Generally speaking Get with MX files is pretty fast.
Are sure this is not a swapping problem?
Edit 1:
You could then use also write in an import converter: tutorial/DevelopingAnImportConverter


text:
Q: Warning on EditText I'm trying to define an EditText but this warning is shown:
This text field does not specify an inputType or a hint.

The code in main.xml is:
<EditText android:id="@+id/input"
              android:layout_width="fill_parent"
              android:layout_height="wrap_content"
              android:text="@string/textTest" />

How can I fix it?

A:  <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="text"
        >

I think You should add input type.......

A: You could add a hint :
android:hint="This will appear to the user if he didn't enter something yet in the EditText"

and a inputType so you could present to the user a better suited soft keyboard for the text he is suposed to enter in the EditText:
android:inputType="number"

will present a soft keyboard with only numbers and various signs.
Those are just warnings, you could ignore them but is better for the user to implement them.

A: This is a known issue. Sometimes it doest work with changing to:
android:inputType="text"

I got it to work by setting:
android:inputType="textNoSuggestions"

Hope this helps

A: Above all are the solutions but before that you should understand what does that warnig mean.
Hint:- Hint is the text shown to user before writing anything over.
           For eg. if you are putting a edittext where you want user to add his
           name then you can write
<Edittext
 android:layout_height="wrap_content"
 android:layout_width="wrap_content"
 android:hint="Enter Name"/>

Input Type:- This is the xml tag that is to be used within edittext to let edittext to follow that particular restriction. if you are giving inputtype:number then user would be able to enter only numbers. There are several input type fields are there for that you can refer official developer site.


text:
Q: Scrollbar handling scroll event in winforms I am creating a form which looks like this.
Form1 has two panels:

*

*the bottom panel (yellow)

*the top panel, which is himself composed by two panels:

*

*the left panel (red)

*the right panel (green)

As the image shows, the top panel, exceeds form1's height, so I would like to use a scrollbar. I have several problems:
a) Setting auto-scroll to true in the top panel does not work.
b) If I put a button on the top panel whose location exceeds form1's height, then it scrolls, but NOT if I put it in any of its subpanels (red or green)
c) Instead of setting auto-scroll to true in the top panel, I could create my own scrollbar, but I just couldn't find a simple example handling the scroll event that moves the panel so that the view port changes as desired.
How could I properly add a scrollbar with the desired behaviour?

A: As LarsTech and Hans Passant suggested, AutoScrollMinSize worked, so a and b questions were solved.
Regarding question C, I thought there was a way to create a scrollbar so that it behaves like I guess 99% of scrollbars should behave (just to move a desired panel). Finally, I coded that logic myself.
I added a Scrollbar1 as a control of the basic form. initialPanelY is catched on the constructor.
This is the code that responds to the scroll event. I just move the panel panelRest2's Y location depending on the scrollbar value
using System;
 .
 .
using System.Windows.Forms;

namespace WindowsFormMyTests
{
  public partial class Form1 : Form
  {
    int initialPanelY;
    public Form1()
    {
        InitializeComponent();
        initialPanelY = this.panelRest2.Location.Y;
    }

    private void vScrollBar1_Scroll(object  sender, ScrollEventArgs e)
    {
        int v = (sender as VScrollBar).Value; //between 1 and 100
        int hiddenPanelHeight = this.panelRest2.Size.Height - this.Size.Height;
        float moveY = (float)hiddenPanelHeight * ((float)v / 100);
        int newY = initialPanelY - (int)moveY;
        this.panelRest2.Location = new Point(this.panelRest2.Location.X, newY);
    }
  }
}


text:
Q: When to use assembly language to debug a c/c++ program? When to use the assembly to debug a c/c++ program?
Does it help to learn some assembly to debug programs?

A: It can be very helpful in cases where you can not (yet) reliably reproduce a
bug, such as due to heap/stack corruption. You might get one or two core
dumps, quite possibly from a customer. Even assuming your debugger is
reliable, looking at assembly can tell you exactly which instruction is
crashing (and thus which piece of memory is corrupted).
Furthermore, in my experience (primarily in kernel debugging) the debuggers
have been relatively bad at dealing with optimized code. They get things like
parameters/etc wrong, and to really tell what's going on I need to look at
diassembly.
If I can reproduce a problem reliably/easily it doesn't tend to be as helpful
to deal with disassembly, because I'll get more information from just stepping
through the program. On the other hand, getting to the point where you can
reproduce a problem is usually more than halfway to fixing it.

A: I presume you are asking when to use a dis-assembly when you want to debug your C/C++ written code.
There will be cases when you suspect that the compiler has not generated the code as you would have wanted it to. Typically, when the optimized version of the executable does not operate correctly but the un-optimized form works well. You would want to check the dis-assembly then to see what optimization has changed the behavior.
Another case would be when you want to understand the executable behavior but you do not have the source code to start with -- this is called reverse engineering. You have no options but to work with the dis-assembly of the executable.
A Wiki reference of dis-assembly and analysis tools for understanding the tools and start learning the one most suitable to your environment.

A: I can't tell you "When" but sometimes you can have weird C/C++ behavior and you really don't understand what's going on... Just look at the asm code, it will never betray you.
But here I check the ASM code of my C programs all the time... for Optimization , curiosity and learning purposes.
By all means learn x86 assembly language!

A: Unless you suspect the compiler, I wouldn't go low-level for debugging. Best to debug at the same level of abstraction as you are expressing your intent in the algorithm.
If you write the code in C/C++ then use a good C/C++ debugger to go with it.

A: I've definitly fallen back to reading the assembly a few times. GCC makes it fairly convenient.
One good example is the subject of one of my questions. GCC changed behavior between 2.95 and 3.4.3, and going to the assembly in the suspect function explained why my program was crashing.
It's also useful on those occasions when you really need to know how certain accesses are being done. If you have memory mapped onto a bus, for example, you might want to know that you are doing a 16 bit access instead of a 32 bit access.
Another case I've been using assembly for lately is to check that my 'volatile' variables really are being treated as volatile. It turns out that almost all compilers get this wrong sometimes, so I've started checking the output of specific cases to ensure that the assembly actually references the memory location instead of some register.

A: The reason assembly can help to debug a program is that gcc often optimizes for you.  You have to look through the assembly for any "improvements" by gcc and make sure they don't screw things up.
For example
/* global */
int x = 1;

void *myFunc() {
    /* do something productive */
    x = 0;
    return NULL;
}

int main() {
    thread_create(myFunc);

    while(x) continue;

    exit(1);
}

Under certain optimizations, while(x) continue; becomes a jmp 0xDEADBEEF (where 0xDEADBEEF is the jmp instruction).  You can see this in the assembly, and know to change x to volatile.
Otherwise, assembly is likely to hurt you in terms of understanding anything.

A: It may help with some of the advanced stuff, and it always helps to understand what's going on "under the hood". But unless you're doing assembly coding anyway (and if you were, you'd know assembly), debugging with assembly is probably overkill. Bugs will probably be directly in your code, and not in the translation between your code and assembly.

A: In some circumstances you have no choice but to revert to assembler. If your system crashes and all you have is a core dump or stack trace with few symbols then staring at the high level source code is not going to get you very far.

A: I think that memory dumps are much more useful at debugging than learning assembler to do so. With visual studio for example you can check which memory location change after a particular line of code. The shortcut key is ALT-6 while in debug mode. You can get variable locations by using the standard watches.

A: I have has some use for my assembly skills searching for bugs that was cause by a new release of the compiler we were using. But compiler bugs are very rare so my answer would be no not for debugging.
It is interesting to look at how the compiler solves a problem in assembly from your source but that is not really debugging.

A: It's useful for debugging optimized release builds; in particular, when a customer sends you a minidump from your application out in the field. In these cases many debuggers are quite weak at keeping track of local variables, and you have to go fish them out of the stack (or registers) by hand.


text:
Q: Improving this code for reversing the string and removing duplicate characters I recently attended an interview where I was asked to write a program.
The problem was:

Take a string. "Hammer", for example.
  Reverse it and any character should not be repeated.
  So, the output will be  - "remaH".

This is the solution I gave:
public class Reverse {
    public static void main(String[] args) {
        String str = "Hammer";
        String revStr = "";

        for(int i=0; i<=str.length()-1;i++){
            if(revStr.indexOf(str.charAt(i))==-1){
                revStr = str.charAt(i)+revStr;
            }
        }
        System.out.println(revStr);
    }
}

How I can improve the above?

A: The problem is String is immutable object, and when using operator+ to concat a char with the current result, you actually create a new string.
This results in creating strings of length 1+2+...+n, which gives you total performance of O(n^2) (unless the compiler optimizes this for you).
Using a StringBuilder instead of concatting strings will give you O(n) performance, and with much better constants as well.
Note that a StringBuilder offers an efficient append() implementaiton, so you need to append elements to it, and NOT add them at the head of your StringBuilder.
You should also reconsider usage of indexOf() - if a characters cannot appear twice at all, consider using a Set<Chatacter> to maintain the list of 'used' characters, if it can appear twice, but not one after the other (for example "mam" is valid) - there is really no need for the indexOf() in the first place, just check the last character read.

A: Here is a solution without using any stringbuilder or intermediary String objects, just treating Strings as arrays of chars; this should be more efficient.
import java.util.Arrays;

public class Reverse {

  public static void main(String[] args) {
    String str = "Hammer";
    String revStr = null;

    char [] chars = str.toCharArray();
    char [] reversedChars = new char[chars.length];

    // copy first char
    reversedChars[reversedChars.length - 1] = chars[0];

    // process rest
    int r = reversedChars.length - 2;
    for(int i = 1 ; i < chars.length ; i++ ){
      if(chars[i] != chars[i-1]){
        reversedChars[r] = chars[i];
        r--;
      }
    }

    revStr = new String(Arrays.copyOfRange(reversedChars, r+1, reversedChars.length));

    System.out.println(revStr);
  }

A: package com.in.main;

public class Reverse {

public static void main(String[] args) {

    String str = "Hammer";
     StringBuilder revStr= new StringBuilder("");

    for(int i=str.length(); i>=0;i--){
        if(revStr.indexOf(str.charAt(i))==-1){
            revStr.append(str.charAt(i));
        }
    }
    System.out.println(revStr);
}

}


text:
Q: In app purchase through sim card for android Is there any functionality in Google's in-app purchase API that can charge a user's sim card? I would like to allow a user to make an in-app purchase with just a button click and without the hassle of entering a credit card number.

A: I think you may have misunderstood how In-App purchases (for Android) work. From the In-App Billing page:

When you use Android Market's in-app billing service to sell an item,
  Android Market handles all checkout details so your application never
  has to directly process any financial transactions. Android Market
  uses the same checkout service that is used for application purchases,
  so your users experience a consistent and familiar purchase flow.

So what this means is that when the user makes an In-App purchase within your application, the checkout procedure is identical to if/when they purchase an app in the Android Market. Assuming they have a credit card registered with Android Market, it gets automatically charged and your users are good to go. If they don't have a credit card registered, they're prompted to add/register one when they initiate the purchase.
In either case, it's all taken care of by Google.


text:
Q: How I can get return value based on argument type? When I define function
func test(a int, b int) int {
    //bla
}

I must set arguments and return value types. How I can return value based on argument type, ex
func test(argument type) type {
    //if argument type == string, must return string
    //or else if argument int, must return integer
}

Can I do this and how?

A: Go lacks generics, (not going to argue this point one way or the other), you can achieve this by passing interface{} to functions and then doing a type assertion on the other side.
package main

import "fmt"

func test(t interface{}) interface{} {
    switch t.(type) {
    case string:
        return "test"
    case int:
        return 54
    }
    return ""
}

func main() {
    fmt.Printf("%#v\n", test(55))
    fmt.Printf("%#v", test("test"))
}

You will have to type assert the value you get out
v := test(55).(int)

A: Go does not yet have generics like C# or Java.
It does have an empty interface (interface{})
Here is code that I believe answers your question, if I understood it correctly:
package main
import (
  "fmt"
  "reflect"
)

type generic interface{} // you don't have to call the type generic, you can call it X

func main() {
    n := test(10) // I happen to pass an int
    fmt.Println(n)
}

func test(arg generic) generic {
   // do something with arg
   result := arg.(int) * 2
   // check that the result is the same data type as arg
   if reflect.TypeOf(arg) != reflect.TypeOf(result) {
     panic("type mismatch")
   }
   return result;
}


text:
Q: Riemann-esque sums (complex analysis) I have been struggling to prove the following statement:
"Let $\gamma:[t_0,t_1] \rightarrow \mathbb{C}$ be a $C^1$ curve. For any $N \in \mathbb{N}$ and $k \in (0,N]$ define $t_N^k := \bigg(1 - \dfrac{k}{N}\bigg)t_0 + \dfrac{k}{N}t_1$
Show that for every continous function $f:\mathbb{C} \rightarrow \mathbb{C}$ the following Riemann type sums converge as below: $$\sum_{k=0}^{N-1}f(\gamma(t_N^k))(\gamma(t_N^{k+1}) - \gamma(t_N^k)) \longrightarrow \int_{\gamma}f(z)dz$$ As $N \rightarrow \infty$ "
Here's what I have so far, but it's incomplete (even though I can see some idea of showing it):
First thing to note is that $\gamma$ is continous on a closed domain; thus, by the partition defined by $t_N^k$ above, we can invoke the mean value theorem on each interval $[t_N^k,t_N^{k + 1}]$. Namely, $\exists s \in [t_N^k,t_N^{k + 1}]$ s.t. $\gamma(t_N^{k + 1}) - \gamma(t_N^k) = \gamma'(s)ds$ where $ds = t_N^{k + 1} - t_N^k$. So we can rewrite the sum as follows: $$S_N := \sum_{k = 0}^{N-1}f(\gamma(t_N^k))\gamma'(s)ds$$ Also we can rewrite the line integral as a sum of integrals over each increment $ds$ as follows: $$I_N := \sum_{k=0}^{N-1}\bigg(\int_{t_N^k}^{t_N^{k+1}}f(\gamma(s))\gamma'(s)ds\bigg)$$ Taking the absolute difference of these terms yields: $$|I_N - S_N| = \bigg|\sum_{k=0}^{N-1}\bigg(\int_{t_N^k}^{t_N^{k+1}}f(\gamma(s)) - f(\gamma(t_N^k)))\gamma'(s)ds\bigg) \bigg| \\ \leq \sup_{s \in [t_N^k,t_N^{k+1}]}|f(\gamma(s)) - f(\gamma(t_N^k))|\sum_{k=0}^{N-1}\int_{t_N^k}^{t_N^{k+1}}|\gamma'(s)|ds$$
And then from here I'm not sure how to completely finish this off. I assume it takes one or two more steps to show this converges to zero, but I don't know how to do it exactly. Could somebody guide me there?
Thanks very much in advance!

A: The MVT doesn't hold for curves unfortunately. But it looks like you have some good ideas. I would look at
$$[\gamma (t_{k+1}) - \gamma (t_{k})] - \gamma'(t_k)(t_{k+1}-t_k)= \int_{t_k}^{t_{k+1}} [\gamma'(t)-\gamma'(t_k)]\,dt.$$
Because $\gamma'$ is continuous, it is unifomly continuous. So if the partition is fine enough, that last integral, in absolute value, will be $< \epsilon\cdot(t_{k+1} - t_{k})$ for all $k.$

A: I am assuming that you are defining $\int_{\gamma}f(z)dz$ by $I=\int_{t_0}^{t_1} f(\gamma(t)) \gamma'(t) dt$.
Let $M = \sup_{t \in [t_0,t_1]} |\gamma'(t)|$.
Since $\phi = f \circ \gamma $ is continuous, it is uniformly continuous on $[t_0,t_1]$. Let $\epsilon>0$  and let $\delta>0$ be such that if $|s-t|<\delta$, then $|\phi(s)-\phi(t)| < \epsilon$.
Pick a partition $P=(s_0=t_0, s_1,...,s_n=t_1)$ such that successive points are less than $\delta$ apart and let $\tilde{\phi} = \sum_{k=0}^{n-1} \phi(s_k) 1_{[s_k,s_{k+1})}$. Then we have
$\sup_{t \in [t_0,t_1)} |\phi(t) - \tilde{\phi}(t)| < \epsilon$ (note that
$t_1$ is excluded from the $\sup$).
Hence
$| \int_{t_0}^{t_1} \phi(t) \gamma'(t) dt  - \int_{t_0}^{t_1} \tilde{\phi}(t) \gamma'(t) dt| < \epsilon M (t_1-t_0)$.
Now note that $\int_{t_0}^{t_1} \phi(t) dt = \int_{\gamma}f(z)dz$ and
$\int_{t_0}^{t_1} \tilde{\phi}(t) dt = \sum_{k=0}^{n-1} f(\gamma(s_k))\int_{s_k}^{s_{k+1}} \gamma'(t)dt = \sum_{k=0}^{n-1} f(\gamma(s_k))(\gamma(s_k)-\gamma(s_{k+1})) dt$.
If you choose $s_k = t^k_N$, with ${t_1-t_0 \over N} < \delta$, then this gives
$|\int_{\gamma}f(z)dz- \sum_{k=0}^{n-1} f(\gamma(t^k_N))(\gamma(t^{k+1}_N)-\gamma(t^k_N)) dt| < \epsilon M (t_1-t_0)$.
Since $\epsilon>0$ was arbitrary, we have the desired result.


text:
Q: I'm getting a "Control may reach the end of non-void function" error with the gRPC library in Xcode I'm installing a bunch of "Control may reach the end of non-void function" errors in Xcode when I installed a library via Cocoapods that included the gRPC library as a dependency. What's going on? How can I fix it?

A: The underlying gRPC issue is addressed in the latest gRPC release. Do a pod update and make sure you see:

Installing gRPC 1.6.5 (was 1.6.0)
Installing gRPC-Core 1.6.5 (was 1.6.0)
Installing gRPC-ProtoRPC 1.6.5 (was 1.6.0)
Installing gRPC-RxLibrary 1.6.5 (was 1.6.0)

A: The reason this is probably happening is that the gRPC library uses some macros to return out of a function that the compiler doesn't seem to understand.
This is not a big deal, except that for some reason, when Cocoapods installed the pod that included gRPC, it set the Mismatched return type value to Yes (treat as error) instead of Yes.
You can fix this by opening up the Pods project inside of your XCWorkspace, find the various gRPC* targets within there, go to Build settings and search for Mismatched return type. If, for some reason, it's set to Yes (treat as error) then set the value to either Yes or No and your project should then build just fine.


text:
Q: Want to load signup page before dashboard in angular 5 I dont have much knowledge on routing in angular. I have different routing modules, in what i want to do is, i want to load my signup component before the dashboard component.
app.routing.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { SignupComponent } from './auth/signup/signup.component';
import { SigninComponent } from './auth/signin/signin.component';
import {  UpdatepasswordComponent } from
'./auth/updatepassword/updatepassword.component';

 // Import Containers
 import {
 FullLayoutComponent,
 SimpleLayoutComponent
  } from './containers';

 export const routes: Routes = [
 {
 path: '',
 redirectTo: 'dashboard',
 pathMatch: 'full',
 },

 { path: 'signup', component: SignupComponent },
   { path: 'signin',
 component: SigninComponent
  },

 { path: 'updatepassword',   component: UpdatepasswordComponent },

  {
path: '',
component: FullLayoutComponent,
data: {
  title: 'Home'
},
children: [
  {
    path: 'base',
    loadChildren: './views/base/base.module#BaseModule'
  },
  {
    path: 'buttons',
    loadChildren: './views/buttons/buttons.module#ButtonsModule'
  },
  {
    path: 'charts',
    loadChildren: './views/chartjs/chartjs.module#ChartJSModule'
  },
  {
    path: 'dashboard',
    loadChildren: './views/dashboard/dashboard.module#DashboardModule'
  },
  {
    path: 'icons',
    loadChildren: './views/icons/icons.module#IconsModule'
  },
  {
    path: 'notifications',
    loadChildren:
  './views/notifications/notifications.module#NotificationsModule'
  },
  {
    path: 'theme',
    loadChildren: './views/theme/theme.module#ThemeModule'
  },
  {
    path: 'widgets',
    loadChildren: './views/widgets/widgets.module#WidgetsModule'
  }
  ]
 },
 ];

 @NgModule({
  imports: [ RouterModule.forRoot(routes) ],
 exports: [ RouterModule ]
 })
   export class AppRoutingModule {}

base-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { addActivityComponent } from './addActivity.component';
import { activitiesComponent } from './activities.component';

import { usersComponent } from './users.component';
import { userActivitiesComponent } from './userActivities.component';

const routes: Routes = [
{
path: '',
data: {
  title: 'Admin'
},
children: [
  {
    path: 'addActivity',
    component: addActivityComponent,
    data: {
      title: 'Add Activity'
    }
  },
  {
    path: 'activities',
    component: activitiesComponent,
    data: {
      title: 'Manage Activities'
    }
  },
 {
    path: 'users',
    component: usersComponent,
    data: {
      title: 'Users'
    }
  },

  ]
 }
];

@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})

export class BaseRoutingModule {}
dashboard-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes,
 RouterModule } from '@angular/router';

import { DashboardComponent } from './dashboard.component';

const routes: Routes = [
{
 path: '',
component: DashboardComponent,
data: {
  title: 'Dashboard'
}
 }

];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
 })
export class DashboardRoutingModule {}

In app routing i tried to redirect my empty to path to signup like this:
 {
 path: '',
 redirectTo: 'signup',
 pathMatch: 'full',
 }

and FullLayoutComponent path like this:
   {
path: 'dashboard',
component: FullLayoutComponent,
data: {
  title: 'Home'
},

from this approach i will succesfully redirect my app to login page and after signin, it will go to the dashboard admin page as well but the problem is that i have 2 cards in my FullLayoutComponent which is showed in the dashboard  page, after doing this approach those cards wouldnt successfully load into page. Except cards all pages where loaded successfully into the app.
here u will find the 2  pictures differences
https://i.stack.imgur.com/htbDA.png
after redirect to signup:
 https://i.stack.imgur.com/yk2I6.png
Any help will be appreciated. Thankyou :)