text:
Q: Subgroup scheme of a constant group scheme I am studying the basics of group-schemes, and I found this statement in a book.

Let $A$ be a finite abelian group, and let $S$ be a connected scheme. We denote by $(A)_S$ the constant group scheme associated to $A$ over $S$. Let $G/S$ be a subgroup scheme of $(A)_S/S$. Then $G$ is a constant group scheme over $S$.

This looks rather basic but it is actually bugging me. Here is what I've done.
Because $S$ is connected, we know that the group $A(S)$ of sections of $(A)_S$ is isomorphic to $A$. It follows, by definition, that $G(S)$ is a subgroup of $A$, which we denote $K$. I would like to show that $G$ is none other than the constant group scheme $(K)_S$.
For this, I need to show that for any scheme $T$ over $S$, the group of $T$-points of $G$ over $S$, denoted $G_S(T)$, is isomorphic to the group of locally constant functions from $T$ to $K$ (equipped with the discrete topology). By definition, we already know that $G_S(T)$ is a subgroup of the group of locally constant functions from $T$ to $A$.
Then, I do not know how to continue further. Namely, I would like to show that any point of $G_S(T)$ maps $T$ to $K$, and that any such locally constant function belongs to $G_S(T)$.
Is the way I am proceeding correct? Is there another way of prooving the statement? Any hint or sketch of the proof would be gladly appreciated.
Thank you very much.

A: Maybe my attempt is a little too envolved, but this is how I would do it, at least in the case where $S$ is noetherian (using as much category theory and as little scheme theory as possible):
Let $G(S)=G \subseteq A$. By the Yoneda Lemma it suffices to show that for every $S$-scheme $H \rightarrow S$ with a section $S \rightarrow H$ we have $G(H)=G^{\pi_0(G)}$. If $S$ is noetherian, we can restrict to noetherian $H$ and therefore reduce to the case where $H$ is connected (because then $H$ is the coproduct of its connected components).
By functoriality we have a morphism $G= G(S) \rightarrow G(H) \subseteq A(H)=A(S)=A$. On the other hand, from the section, we get a surjection $G(H) \rightarrow G(S)$, inducing (by the subfunctor property) a commutative diagram
$$\require{AMScd} \begin{CD} G(H) @>{incl}>> A \\ @VVV @VVV \\ G(S) @>{incl}>> A \end{CD}$$
where the right hand side is just the identity map. Showing that $G(H) \rightarrow G(S)$ is also the identity map.
For the case where $S$ is not noetherian:
Let $H= \bigcup_I H_i$ where the $H_i$ are the connected components (note that this is not necessarily the coproduct on $S$-schemes). Let $H' = \coprod_I H_i$. The canonical morphism $H' \rightarrow H$ induces the identity on $A(H) \rightarrow A(H')$, thus an injection $G(H) \rightarrow G(S)^I$ and therefore we obtain a functorial injection $G \rightarrow G(S)$, yielding $G$ as a subgroup scheme of $G(S)$, where I write $G(S)$ for the constant group scheme. Thus, we are reduced to the case "if $G$ is a subgroup scheme of a finite constant group scheme $A$ with $G(S)=A(S)$, then $G=A$".
Then we can write $G= \coprod_{a \in A(S)} X_a$ where the $X_a$ are maybe not connected $S$-schemes and have an $S$-section. We want to show that every such $X_a$ is connected (then we are done!). Assume $X_a = X_1 \cup X_2 \cup X_3$, where $X_1$ is the connected component containing $S$ and $X_2$ is connected. But then $G$ has at least $|A(S)|+1$-many $X_2$-valued points, which is a contradiction. Showing the $X_a$ are connected and (a postiori) isomorphic to $S$.


text:
Q: how to write new columns on the side of old columns I want to make a script that extract two columns from  file-1 and them write them into file-2. However, If file-2 already contains columns, and want the new columns to be written on the side (of the current columns), and not at the bottom. My current script appends the "new" columns at the bottom of the current ones, instead of doing it on the side. How can I add the new columns on the side a not at the bottom?. Someone suggested CSV module, and I tried, but I could not figure out how to do it.
Here is my current code
https://dl.dropbox.com/u/63216126/paula.txt
Here is the output file if I run the script once
https://dl.dropbox.com/u/63216126/try2.txt
Here is the output file if I run the script twice (Keep in mind this is not want I want)
https://dl.dropbox.com/u/63216126/try3.txt
Here is how I want the output to look after running the script three times
https://dl.dropbox.com/u/63216126/try.txt
Here are two input samples
https://dl.dropbox.com/u/63216126/file5.txt
https://dl.dropbox.com/u/63216126/file6.txt
I hope what I want to do is clear. Thanks a lot for the help.

A: sys.argv is a list. You can get the number of arguments with len(sys.argv), and iterate through them like so:
for arg in sys.argv[1:]:
    do_something(arg)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Div transition over div onclick I need to have two div one above the other, and when I click over an image I want  the second div slide up over the first.
Why I can't get running my code onclick and it runs instead if I change onclick to AboutUs ?
Something like this

.AboutUsH {
  height: 400px;
  overflow: hidden;
}
.move-in-to-place {
  position: absolute;
  bottom: -100%;
  height: 100%;
  width: 100%;
  background: #AAAAAA;
  opacity: 0;
  height: 0;
}
.AboutUsH img.clicked {
  bottom: 0;
  -webkit-transition: all 1s, -webkit-transform 1s;
  transition: all 1s, transform 1s;
  height: 100%;
  opacity: 1;
}

  <asp:Panel ID="Centering" runat="server" CssClass="Centering">

  </asp:Panel>

LBLTitle

  <asp:Literal ID="LTR" runat="server"></asp:Literal>

    Form content

Any ideas ?
Thanks

A: $('.blue').click(function(){
    //expand red div width to 200px
    $('.red').animate({width: "200px"}, 500);
    setTimeout(function(){
        //after 500 milliseconds expand height to 800px
        $('.red').animate({height:"800px"}, 500);
    },500);
    setTimeout(function(){
        //after 1000 milliseconds show textarea (or textbox, span, etc)
        $('.red').find('input[type="textarea"]').show();
    },1000);
});


text:
Q: django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: I am following the django tutorial, Many have asked the question but I think my situation is bit unique because after installing python-mysql I still get this error when I try to do python manage.py syncdb,
I am in a virtualenv since I use macports to manage my python installation I created my virtualenv
virtualenv code/vdjango --no-site-packages --python=/opt/local/bin/python

prior to this using macports I install django py27-django, but after creating my virtualenv I thought its better that I install django on to virtualenv so I used pip install django==1.5
According to django tutorial I edited my settings.py file and then execute the python manage.py syncdb and I end up with following error:
[~/code/vdjango/newsite]$python manage.py syncdb
Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/Users/mac-pro/code/vdjango/lib/python2.7/site-packages/django/core/management/__init__.py", line 453, in execute_from_command_line
    utility.execute()
  File "/Users/mac-pro/code/vdjango/lib/python2.7/site-packages/django/core/management/__init__.py", line 392, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/Users/mac-pro/code/vdjango/lib/python2.7/site-packages/django/core/management/__init__.py", line 272, in fetch_command
    klass = load_command_class(app_name, subcommand)
  File "/Users/mac-pro/code/vdjango/lib/python2.7/site-packages/django/core/management/__init__.py", line 77, in load_command_class
    module = import_module('%s.management.commands.%s' % (app_name, name))
  File "/Users/mac-pro/code/vdjango/lib/python2.7/site-packages/django/utils/importlib.py", line 35, in import_module
    __import__(name)
  File "/Users/mac-pro/code/vdjango/lib/python2.7/site-packages/django/core/management/commands/syncdb.py", line 8, in <module>
    from django.core.management.sql import custom_sql_for_model, emit_post_sync_signal
  File "/Users/mac-pro/code/vdjango/lib/python2.7/site-packages/django/core/management/sql.py", line 9, in <module>
    from django.db import models
  File "/Users/mac-pro/code/vdjango/lib/python2.7/site-packages/django/db/__init__.py", line 40, in <module>
    backend = load_backend(connection.settings_dict['ENGINE'])
  File "/Users/mac-pro/code/vdjango/lib/python2.7/site-packages/django/db/__init__.py", line 34, in __getattr__
    return getattr(connections[DEFAULT_DB_ALIAS], item)
  File "/Users/mac-pro/code/vdjango/lib/python2.7/site-packages/django/db/utils.py", line 93, in __getitem__
    backend = load_backend(db['ENGINE'])
  File "/Users/mac-pro/code/vdjango/lib/python2.7/site-packages/django/db/utils.py", line 27, in load_backend
    return import_module('.base', backend_name)
  File "/Users/mac-pro/code/vdjango/lib/python2.7/site-packages/django/utils/importlib.py", line 35, in import_module
    __import__(name)
  File "/Users/mac-pro/code/vdjango/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 17, in <module>
    raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e)
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: dlopen(/Users/mac-pro/code/vdjango/lib/python2.7/site-packages/_mysql.so, 2): Library not loaded: libmysqlclient.18.dylib
  Referenced from: /Users/mac-pro/code/vdjango/lib/python2.7/site-packages/_mysql.so
  Reason: image not found

To confirm that I have install python-mysql package I ran the pip install again,
(vdjango)mac-pro@localhost:[~/code/vdjango/newsite]$pip install python-mysqldb
Downloading/unpacking python-mysqldb
  Could not find any downloads that satisfy the requirement python-mysqldb
No distributions at all found for python-mysqldb
Storing complete log in /Users/mac-pro/.pip/pip.log

So whats happening here? Looks like I have everything that I need to go further with the tutorial but some how python/django is complaining about not having mysqldb.

A: My libmysqlclient.18.dylib was located in /usr/local/mysql/lib/ but my system was looking for it in /usr/lib/.  I ended up creating a symbolic link of libmysqlclient.18.dylib in /usr/lib which fixed the problem.
1.) Make sure that libmysqlclient.18.dylib exists in /usr/local/mysql/lib/.
Open your shell.
sudo -s
ls /usr/local/mysql/lib/ | grep libmysqlclient.18.dylib

You should see the file:
libmysqlclient.18.dylib

If not, search your system for the location of the file:
find / -name libmysqlclient.18.dylib

2.) Create a symbolic link of libmysqlclient.18.dylib in /usr/lib
Enter the following command in your shell:
ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib

If your libmysqlclient.18.dylib file wasn't located in /usr/local/mysql/lib replace the first path with the proper path to libmysqlclient.18.dylib.
Hopefully that helps.


text:
Q: Can we limit the no. Of index linked to an alias in Elastic search In Elasticsearch we know that we can assign multiple no. Of index to an alias. So my question here ,is there a way by changing the configuration or something in Elasticsearch by which I can specify that a particular alias  can have this maximum number of index assigned to it.
I am looking at max no of index assigned to a alias be 1 only. Any suggestions and thought is this is most welcome.


text:
Q: Kerberos authentication fails when local password is expired I am using pam_krb5 with local accounts (Linux) for AD password authentication. Things are working great, users are able to authenticate with both AD and local passwords.
I am having a problem though, when the local password expires Kerberos authentication fails and prompts the user to change their local password. The issue is that most users cannot remember their local password, and my workaround so far has been to temporarily disable local password change enforcement.
Is there a way to have pam_krb5 ignore expired local passwords, or at least configure PAM to prioritize Kerberos passwords over local?
My research lead me to believe it has something to do with common-auth, which I have provided below:
auth    required        pam_env.so
auth    sufficient      pam_unix2.so
auth    requisite       pam_succeed_if.so user ingroup access_www
auth    sufficient      pam_krb5.so     use_first_pass
auth    required        pam_deny.so

A: Put pam_krb5 before pam_unix2 (and keep the use_first_pass on the latter entry).


text:
Q: Select specific columns not working LINQ Trying to get specific columns with Select in linq, its returning list of selected columns but when trying get in .cshtml page its create an error:

'object' does not contain a definition for 'Code'

In Controller:
ViewBag.Data= oDB.Table.Where(x => x.Type == 1).Select(x => new { x.Code, x.Desc }).ToList();

In View:
@foreach (var item in ViewBag.Data)
{

@item.Code

}

Working fine while remove column selection:
ViewBag.Data= oDB.Table.Where(x => x.Type == 1).ToList();

What the difference?

A: @foreach (var item in ViewBag.Cohorts)
{

@item.Code

}

This will not work directly. you have to typecast it to correct object first using typecast or using as keyword
var list = (ActualTypeGoesHere)ViewBag.Cohorts;
@foreach (var item in list)
{

@item.Code

}

but since you are using the 'anonymous' type you can't do anything. So you have to create a DTO and then map data to that DTO in the controller and send that DTO to View using model or ViewBag. Then cast the ViewBag to DTO as shown above.
It seems that my answer was not clear to the OP so I am adding EDIT
 In View:

@foreach (var item in ViewBag.Data)
{

@item.Code

}

The type of item in the foreach loop above is not List its of type dynamic and at runtime it will be -       item.GetType()  {Name = "<>f__AnonymousType12" Code = "<>f__AnonymousType12[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]"}  dynamic {System.RuntimeType}
you will get type if you do item.GetType(); So now you see that you cannot directly extract out the value of Code from item like you would expect to.
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/dynamic
https://www.codeproject.com/Tips/460614/Difference-between-var-and-dynamic-in-Csharp

A: the new { x.Code, x.Desc } gives you new data type an unknow type so in this case x.Type will be missing aslo and you don't know what type of object are you gettign back from viewbag.So if you use new Class1 {X.type=1,X.Code,X.Desc} it will pickup the Code property.
The order solution is to use dynamic instead of var in for each loop.


text:
Q: Azure Data Factory - Pipeline Copy from SQL to CRM - Error I am currently working on a Azure Data Factory Mapping.
SQL Server to CRM
There is a Entity Reference look up field that I am trying to update. Do not know how to. The field is: new_districtlink --> Territory/Territories
using JSON we use:
{\"new_districtlink@odata.bind\":\"/territories(c8a29516-4001-e311-98f3-78e3b5089b9d)\"}"

Don't know how to reference this field in AZURE DATA FACTORY so it updates correctly. Currently I have tried Mapping using newdistrictlink@EntityReference
I get the following error:

"errorCode": "2200",
"message": "Failure happened on 'Sink' side. ErrorCode=UserErrorDynamicsOperationFailed,'Type=Microsoft.DataTransfer.Common.Shared.HybridDeliveryException,Message=Dynamics operation failed with error code: -2147220891, error message: The real-time workflow named "ACCOUNT: Pull in Region and Division from District(Territory)" failed with the error "For a Vendor Account Type, select 199 as the district.".,Source=Microsoft.DataTransfer.ClientLibrary.DynamicsPlugin,''Type=System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=9.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]],Message=The creator of this fault did not specify a Reason.,Source=Microsoft.DataTransfer.ClientLibrary.DynamicsPlugin,'",
"failureType": "UserError",
"target": "CMA CRM VENDOR",
"details": []
}

The error I am getting is in Azure Data Factory. The JSON was just an example of how we are doing it in C# currently.
I am setting District as GUID and Mapping District to new_districtlink@EntityReference.
SELECT
ACCOUNTID,
'2EC67250-E3C4-E311-ABE1-6C3BE5BDA9AC' AS DISTRICT
FROM [dbo].[VendVendorV2Staging]
WHERE ADDRESSLOCATIONROLES = 'Business';

A: I see there's no issue with Json payload you used, it is correct to map an EntityReference (lookup).
I guess this is data validation message coming back from CRM Real time workflow which is validating the territory (district) against the created account type.
The error message clearly says - the value you passed (guid in district link Json payload for territory) is not expected value based on business logic validation in real time workflow. For vendor type account, 199 is the expected district and find out the guid of that territory record and update the Json.
Or change the account type to something else than vendor. Then it should work, or check with CRM dev team or BA for business rules before implementing and testing ADF integration for creating the account record.


text:
Q: Linear independence of solutions (sorry, there was a typo in my original post - it has been fixed now)
$$y''+\left(\frac{\sin x}{1+\cos x}\right)y'+\left(\frac{1}{1+\cos x}\right)y=0$$
I can see that both $A\sin x$ and $B\cos x+B$ are solutions. The Wronskian is:
$$W(x)=\text{det}\begin{pmatrix} 1+\cos x\quad \sin x\\ -\sin x\quad \cos x\end{pmatrix}=1+\cos x$$
This is $0$ at $\pi$; I am asked to comment on the solution set.
Thoughts: Despite $W$ being $0$ somewhere it is certainly not identically $0$. I put this down to $\pi$ being a singularity point of the equation, so it technically doesn't lie in the domain of $W$. Is this a good reason?
We know $\sin $ and $\cos $ are linearly independent so $A\sin x+B\cos x+B$ must in fact be the most general solution. Is this true/correct? Wolfram seems to disagree.

A: The equation
$$
   (1+\cos x)y''+\sin x\; y' + y = 0.
$$
has one solution $y=1+\cos x$ because $y'=-\sin x$, $y''=-\cos x$ gives
$$
         -(\cos x +\cos^{2}x) -\sin^{2}x + (1+\cos x) = 0.
$$
The second solution can be found by variation of parameters. Let $y_{1}=1+\cos x$ and $y_{2}=a(x)y_{1}$ for a function $a(x)$ to be found:
$$
            (1+\cos x)(ay_{1}''+2a'y_{1}'+a''y_{1})+\sin x(ay_{1}'+a'y_{1})+ay_{1}=0.
$$
Using $(1+\cos x)(ay_{1}'')+\sin x(ay_{1})+ay_{1}=0$ gives
$$
    (1+\cos x)(2a'y_{1}'+a''y_{1})+\sin x(a'y_{1})=0, \\
   a''y_{1}(1+\cos x)+a'\{2y_{1}'(1+\cos x)+y_{1}\sin x \}=0,\\
       \frac{a''}{a'}+\left(\frac{2y_{1}'}{y_{1}}+\frac{\sin x}{1+\cos x}\right)=0,\\
             \ln |a'| + \ln y_{1}^{2}-\ln|1+\cos x|= C,\\
              a' = D\frac{1+\cos x}{y_{1}^{2}}=D\frac{1}{1+\cos x}.
$$
So a second solution is $y_{2}=ay_{1}$, where $a=1+\cos x$:
$$
                   y_{2}=\int_{0}^{x}\frac{1}{1+\cos u}\,du\cdot (1+\cos x).
$$
The general solution is $Ay_{1}+By_{2}$, where $A$, $B$ are constants.
The Wronskian is
$$
     W(y_{1},y_{2})=W(y_{1},ay_{1})=y_1(a'y_1+ay_1')-y_1'(ay_1)=a'y_1^{2}=1+\cos x.
$$
As you stated, the Wronskian is not technically defined at $x=\pi$ because $y_{2}$ is not defined there. This is a limiting value of the Wronskian, and $0$ is okay as a limiting value.


text:
Q: C# render textfield characters as password dots I am using Ext-Net framework where there is not autocomplete property for a textfield.
So I have a textfield with the property InputType="Password" so it is recognized as password field from Chrome and it is autocompleted. If I remove the InputType property then the characters are not masked.
How I can mask the characters as password dots if I remove the InputType property?

A: Do you mean autocompletion as in the field's contents being cached, or autocompletion as being filled in by a password manager?
If the latter, this is actually good because it makes it easier for users to use a password manager to generate and use random and unique passwords (which is excellent security practice) and reduces the temptation for users to reuse passwords (which is poor security practice), so my recommendation would thus be to not inhibit this autocompletion.


text:
Q: Strange Limit - Average Speed of Car I've been working on a problem I came up with on my own. Long story short, the problem is:
What's the average speed of a car starting at $A$ mph and ending at $B$ mph assuming the car only travels at speed $x_k$ mph for $t(x_k)$ hours, where $\large  t(x_k)=\frac{M*(G_k-G_{k-1})}{x_k} $. Here, $M$ represents the mpg of the car, which is assumed to be constant and independent of speed with $M>0$. $G_k$ represents the amount of fuel remaining when the car is traveling at $x_k$ mph, with $G_0>0$ and $G_n=0$. Note that the units hash out: (gallons*mpg)/mph=hours.
Anyway, I've worked out the formulas and have come up with a final answer. That said, my derivation/proof is missing the final step: evaluating a certain limit.
The limit looks like:
$$\Large
\lim_{n\to\infty}\left(\frac{n}{\sum\limits_{k=0}^{n}\left( \frac{n}{Bk+A(n-k)} \right)}\right)\stackrel{?}{=}\frac{B-A}{ln(B)-ln(A)}
$$
Where A and B are constants such that B>A>0.
I guessed at the limit after noticing that the infinite sum in the denominator can be simplified as
$\large\sum\limits_{k=0}^{n} \frac{1}{x_k}
$ where $x_0=A$ and $x_n=B$ and all $x_k$ are just even "steps" from $x_0=A$ to $x_n=B$.
From there:
$$\lim_{n\to\infty}\large\sum\limits_{k=0}^{n} \frac{1}{x_k}=\int_{A}^{B} \frac{1}{x} dx = ln(B)-ln(A).
$$
So that gave us the limit of the denominator. What am I missing on how to get the $B-A$ in the numerator? After getting the denominator, I tried a lot of things until I found this limit and checked it against a lot of different numbers in Excel. I'm fairly certain this is the actual limit, but I don't know how to prove it as I'm stuck at the $B-A$ in the numerator...
Anyway, I think this is a really cool result since the answer is independent of however many gallons gas you start with $(G_0>0; G_n=0)$ and also independent of the car's mpg rating $(M>0)$.
Any help would be appreciated!

A: Observe you have
\begin{align}
\left(\frac{n}{\displaystyle\sum^n_{k=1}\left(\frac{n}{Bk+A(n-k)}\right)}\right) = \left(\frac{1}{\displaystyle\frac{1}{n}\sum^n_{k=1}\left(\frac{1}{B(k/n)+A(1-k/n)}\right)}\right)
\end{align}
So in the limit you get that
\begin{align}
\lim_{n\rightarrow \infty}\left(\frac{n}{\displaystyle\sum^n_{k=1}\left(\frac{n}{Bk+A(n-k)}\right)}\right)=\frac{1}{\displaystyle \int^1_0\frac{1}{Bx+A(1-x)}\ dx}.
\end{align}
Next, observe
\begin{align}
\int^1_0 \frac{1}{A+(B-A)x}\ dx = \frac{\log(A+(B-A)x)}{B-A}\bigg|^1_0 = \frac{\log B-\log A}{B-A}.
\end{align}


text:
Q: Split string into key-value pairs where a value can contain a delimiter I am trying to split a string into key-value pairs which is very straight forward, but I realized very late that I don't have any validation on my input. the string can contain same delimiter that I am using to split. Not sure if this is possible but can someone please help find a way to split this string into a valid key/value pairs?
The current logic:
    String key = "key1=value1,key2=value2,key3=value3,with,delimeter"
    Map<String, String> map = new HashMap<>();
    String[] entries = key.split(",");
    for(String entry : entries) {
      String[] keyValue = entry.split("=");
      map.put(keyValue[0], keyValue[1]);
    }

Expected output:
key1:value1
key2:value2
key3:value3,with,delimeter

But this code causes java.lang.ArrayIndexOutOfBoundsException as there are comma in the last value.
Note: I cannot convert , into a different delimiter as I need to process the string as-is and it can container any character.

A: Why not split it with =, and make the string after the last ,
the value?
String key = "key1=value1,key2=value2,key3=value3,with,delimeter";
Map<String, String> map = new HashMap<>();
String[] valueKeys = key.split("=");

// {"key", "value,key", "value"}
String lastKey = valueKeys[0];
for(int i = 1; i < valueKeys.length; i++) {
    String valueKey = valueKeys[i];
    if(i == valueKeys.length - 1) { // It must be the last item in the array
        map.put(lastKey, valueKey);
        break;
    }

    int lastComma = valueKey.lastIndexOf(",");
    map.put(lastKey, valueKey.substring(0, lastComma));
    lastKey = valueKey.substring(lastComma + 1);
}
printMap(map); // Display the map

Result:
key1: value1
key2: value2
key3: value3,with,delimeter

Note: It only works if the key does not contains commas.


text:
Q: Azure AD B2C getting oauthConnection Error: Bad Request While trying to integrate Azure AD B2C, I am stuck with an error "oauthConnection Error: Bad Request". Following their given sample app it all works fine. But after integrating the same copy paste code from the working sample app, and trying to log in with Facebook or Google Plus, it throws an error! I am pretty sure that every credential that I used in the sample app is the same for my app. Any idea about this will be highly appreciated. Here is my code,  AppDelegate.m
#import "AppData.h"
#import "NXOAuth2.h"
#import "AppDelegate.h"

@interface AppDelegate ()

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    [self setupOAuth2AccountStore];

    // Override point for customization after application launch.
    return YES;
}

- (void)setupOAuth2AccountStore {
    AppData *data = [AppData getInstance]; // The singleton we use to get the settings

    NSDictionary *customHeaders =
    [NSDictionary dictionaryWithObject:@"application/x-www-form-urlencoded"
                                forKey:@"Content-Type"];

    // Azure B2C needs
    // kNXOAuth2AccountStoreConfigurationAdditionalAuthenticationParameters for
    // sending policy to the server,
    // therefore we use -setConfiguration:forAccountType:
    NSDictionary *B2cConfigDict = @{
                                    kNXOAuth2AccountStoreConfigurationClientID : data.clientID,
                                    kNXOAuth2AccountStoreConfigurationSecret : data.clientSecret,
                                    kNXOAuth2AccountStoreConfigurationScope :
                                        [NSSet setWithObjects:@"openid", data.clientID, nil],
                                    kNXOAuth2AccountStoreConfigurationAuthorizeURL :
                                        [NSURL URLWithString:data.authURL],
                                    kNXOAuth2AccountStoreConfigurationTokenURL :
                                        [NSURL URLWithString:data.tokenURL],
                                    kNXOAuth2AccountStoreConfigurationRedirectURL :
                                        [NSURL URLWithString:data.bhh],
                                    kNXOAuth2AccountStoreConfigurationCustomHeaderFields : customHeaders,
                                    //      kNXOAuth2AccountStoreConfigurationAdditionalAuthenticationParameters:customAuthenticationParameters
                                    };

    [[NXOAuth2AccountStore sharedStore] setConfiguration:B2cConfigDict
                                          forAccountType:data.accountIdentifier];
}

LoginViewController.m
#import "AppData.h"
#import "LoginViewController.h"
#import "NXOAuth2.h"

@interface LoginViewController ()

@end

@implementation LoginViewController {

    NSURL *myLoadedUrl;
    bool isRequestBusy;
}

// Put variables here

- (void)viewDidLoad {
    [super viewDidLoad];

    // OAuth2 Code
    self.loginView.delegate = self;
    [self requestOAuth2Access];
    [self setupOAuth2AccountStore];
    NSURLCache *URLCache =
    [[NSURLCache alloc] initWithMemoryCapacity:4 * 1024 * 1024
                                  diskCapacity:20 * 1024 * 1024
                                      diskPath:nil];
    [NSURLCache setSharedURLCache:URLCache];

}

- (void)resolveUsingUIWebView:(NSURL *)URL {
    // We get the auth token from a redirect so we need to handle that in the
    // webview.

    if (![NSThread isMainThread]) {
        [self performSelectorOnMainThread:@selector(resolveUsingUIWebView:)
                               withObject:URL
                            waitUntilDone:YES];
        return;
    }

    NSURLRequest *hostnameURLRequest =
    [NSURLRequest requestWithURL:URL
                     cachePolicy:NSURLRequestUseProtocolCachePolicy
                 timeoutInterval:10.0f];
    isRequestBusy = YES;
    [self.loginView loadRequest:hostnameURLRequest];

    NSLog(@"resolveUsingUIWebView ready (status: UNKNOWN, URL: %@)",
          self.loginView.request.URL);
}

- (BOOL)webView:(UIWebView *)webView
shouldStartLoadWithRequest:(NSURLRequest *)request
 navigationType:(UIWebViewNavigationType)navigationType {
    AppData *data = [AppData getInstance];

    NSLog(@"webView:shouldStartLoadWithRequest: %@ (%li)", request.URL,
          (long)navigationType);

    // The webview is where all the communication happens. Slightly complicated.

    myLoadedUrl = [webView.request mainDocumentURL];
    NSLog(@"***Loaded url: %@", myLoadedUrl);

    // if the UIWebView is showing our authorization URL or consent URL, show the
    // UIWebView control
    if ([request.URL.absoluteString rangeOfString:data.authURL
                                          options:NSCaseInsensitiveSearch]
        .location != NSNotFound) {
        self.loginView.hidden = NO;
    } else if ([request.URL.absoluteString rangeOfString:data.loginURL
                                                 options:NSCaseInsensitiveSearch]
               .location != NSNotFound) {
        // otherwise hide the UIWebView, we've left the authorization flow
        self.loginView.hidden = NO;
    } else if ([request.URL.absoluteString rangeOfString:data.bhh
                                                 options:NSCaseInsensitiveSearch]
               .location != NSNotFound) {
        // otherwise hide the UIWebView, we've left the authorization flow
        self.loginView.hidden = YES;
        [[NXOAuth2AccountStore sharedStore] handleRedirectURL:request.URL];
    } else {
        self.loginView.hidden = NO;

    }

    return YES;
}

#pragma mark - UIWebViewDelegate methods
- (void)webViewDidFinishLoad:(UIWebView *)webView {
  // The webview is where all the communication happens. Slightly complicated.
}
- (void)handleOAuth2AccessResult:(NSURL *)accessResult {
    // parse the response for success or failure
    if (accessResult)
        // if success, complete the OAuth2 flow by handling the redirect URL and
        // obtaining a token
    {
        [[NXOAuth2AccountStore sharedStore] handleRedirectURL:accessResult];
    } else {
        // start over
        [self requestOAuth2Access];
    }
}
- (void)setupOAuth2AccountStore {
    [[NSNotificationCenter defaultCenter]
     addObserverForName:NXOAuth2AccountStoreAccountsDidChangeNotification
     object:[NXOAuth2AccountStore sharedStore]
     queue:nil
     usingBlock:^(NSNotification *aNotification) {
         if (aNotification.userInfo) {
             // account added, we have access
             // we can now request protected data
             NSLog(@"Success!! We have an access token.");
         } else {
             // account removed, we lost access
         }
     }];

    [[NSNotificationCenter defaultCenter]
     addObserverForName:NXOAuth2AccountStoreDidFailToRequestAccessNotification
     object:[NXOAuth2AccountStore sharedStore]
     queue:nil
     usingBlock:^(NSNotification *aNotification) {
         NSError *error = [aNotification.userInfo
                           objectForKey:NXOAuth2AccountStoreErrorKey];

        // Always got stuck here while trying to login with any credentials
         NSLog(@"Error!! %@", error.localizedDescription);
     }];
}

- (void)requestOAuth2Access {
    AppData *data = [AppData getInstance];

    [[NXOAuth2AccountStore sharedStore]
     requestAccessToAccountWithType:data.accountIdentifier
     withPreparedAuthorizationURLHandler:^(NSURL *preparedURL) {

         NSURLRequest *r = [NSURLRequest requestWithURL:preparedURL];
         [self.loginView loadRequest:r];
     }];
}

ViewController.m
#import "ViewController.h"
#import "AppData.h"
#import "LoginViewController.h"
#import "NXOAuth2.h"
// Login Action
    - (IBAction)login:(id)sender {
        LoginViewController *userSelectController =
        [self.storyboard instantiateViewControllerWithIdentifier:@"login"];
        [self.navigationController pushViewController:userSelectController
                                             animated:YES];
    }

A: In case if anybody stumbles in this, Here is the solution
Go to pod, NXOAuth2Client.m and replace the method
- (void)requestTokenWithAuthGrant:(NSString *)authGrant redirectURL:(NSURL *)redirectURL; with the below code
- (void)requestTokenWithAuthGrant:(NSString *)authGrant redirectURL:(NSURL *)redirectURL;
{
    NSAssert1(!authConnection, @"authConnection already running with: %@", authConnection);

    NSMutableURLRequest *tokenRequest = [NSMutableURLRequest requestWithURL:tokenURL];
    [tokenRequest setHTTPMethod:self.tokenRequestHTTPMethod];
    [authConnection cancel];  // just to be sure

    self.authenticating = YES;

    NSMutableDictionary *parameters = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                       @"authorization_code", @"grant_type",
                                       clientId, @"client_id",
                                      // clientSecret, @"client_secret",
                                       [redirectURL absoluteString], @"redirect_uri",
                                       authGrant, @"code",
                                       nil];
    if (self.desiredScope) {
        [parameters setObject:[[self.desiredScope allObjects] componentsJoinedByString:@" "] forKey:@"scope"];
    }

    if (self.customHeaderFields) {
        [self.customHeaderFields enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSString *obj, BOOL *stop) {
            [tokenRequest addValue:obj forHTTPHeaderField:key];
        }];
    }

    if (self.additionalAuthenticationParameters) {
        [parameters addEntriesFromDictionary:self.additionalAuthenticationParameters];
    }

    authConnection = [[NXOAuth2Connection alloc] initWithRequest:tokenRequest
                                               requestParameters:parameters
                                                     oauthClient:self
                                                        delegate:self];
    authConnection.context = NXOAuth2ClientConnectionContextTokenRequest;
}

Commenting clientSecret solved the issue


text:
Q: How to add Quick Create Forms and Pre-Populating Fields I have two entity account and contact..i want to add Quick Create Forms of contact entity inside account entity...and i want to pre-Poulating the fields based on selected record of account...

A: *

*You do not need Javascripting. You can do so without code.

*From Account to Contact MS CRM gives out of Box Relationship

*This you can see from Account to Contact in 1:N see Image below

*Now when you open this relationship you can see mapping i.e Fields which can be moved from Account to contact when you create a new contact. You can add your fields as well.

*Now In Account add a subgrid for contact.

*you have to also check if your contact Entity allows Quick create. If not allow quick create

*If you follow all the steps you get desired result


text:
Q: WPF: Canvas, animating rectangle I want to animate, a rectangle in my canvas to go up. This should happen in the coder behind. In the end, I want to let the rectangle go up and down in while loop, but I can't even get it to go in one direction.
Xaml:
<Window x:Class="WpfApp.View.CPR"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp.View"
        mc:Ignorable="d"
        Title="CPR" Height="250" Width="210">
    <Grid Background="Black">
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="0.5*"/>
        </Grid.ColumnDefinitions>

        <StackPanel Grid.Column="1">
            <TextBlock Text="Counter" HorizontalAlignment="Center" Grid.Column="1" Grid.Row="0" Background="Black" Foreground="White"/>
            <TextBlock Text="" FontSize="20" FontWeight="Bold" HorizontalAlignment="Center" Grid.Column="1" Grid.Row="0" Background="Black" Foreground="White"/>
        </StackPanel>

        <Canvas Grid.Column="0" Grid.Row="0" Grid.RowSpan="2">
            <Rectangle Fill="Red" Height="2" Width="110" Canvas.Top="20" Canvas.Left="23.75"/>
            <Rectangle Fill="LawnGreen" Height="20" Width="5" Canvas.Top="170" Canvas.Left="76.25" x:Name="line"/>
            <Rectangle Fill="Red" Height="2" Width="110" Canvas.Top="190" Canvas.Left="23.75"/>
        </Canvas>
        <StackPanel Grid.Row="1"/>

    </Grid>
</Window>

In my code, I tried something from the internet. I actually have no clue.
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace WpfApp.View
{
    /// <summary>
    /// Interaktionslogik für CPR.xaml
    /// </summary>
    public partial class CPR : Window
    {
        public CPR()
        {
            InitializeComponent();

            var translation = new TranslateTransform(0, -170);
            var animation = new DoubleAnimation();
            animation.Duration = new Duration(new TimeSpan(625));
            animation.RepeatBehavior = RepeatBehavior.Forever;
            animation.From = 76.25;
            animation.To = 20;
            var board = new Storyboard();
            board.Children.Add(animation);
            Storyboard.SetTarget(board, translation);
            Storyboard.SetTargetProperty(board, new PropertyPath(Rectangle.Y));
            line.Loaded += delegate (object sender, RoutedEventArgs e)
            {
                line.BeginStoryboard(board);
            };
        }
    }
}

Thanks for your help!

A: You would simply animate the Canvas.Top property.
The following example would animate the Top value from 100 to 200 within 1 second, then back from 200 to 100, forever.
<Canvas>
    <Rectangle x:Name="rectangle" Canvas.Left="100" Canvas.Top="100"
               Width="100" Height="100" Fill="Red"/>
</Canvas>

In code behind:
var topAnimation = new DoubleAnimation
{
    From = 100,
    To = 200,
    Duration = TimeSpan.FromSeconds(1),
    AutoReverse = true,
    RepeatBehavior = RepeatBehavior.Forever
};

rectangle.BeginAnimation(Canvas.TopProperty, topAnimation);


text:
Q: String pyramid transition matrix Hi just saw a problem related NFA to DFA
Problem: given a list of leaf nodes in a pyramid ,and a map which indicates what's the possible parent node given a left and right node. Return true if the one of leaf node could turn into the root node, Otherwise, return false.
Example:
     root
     / \
    X   X
   /\  /\
   X  X  X
  / \/ \/ \
 A   B  C  D

Map:
        left: A |  B   |   C | D
right---------------------------------
A             B |A or C|   D | A
B             D |B or C|   A |
C                              B
D

Note:1. If left child is B, right child is A, the parent node could be B or C

A: def generate_status(all_status, matrix):
#  print all_status
if len(all_status) == 1:
    return all_status[0]

next_all_status = []
for i in xrange(len(all_status) - 1):
    cur_status = set()
    for first_status in all_status:
        for second_status in all_status[i+1]:
            cur_status |= set(list(matrix[first_status][second_status]))
    next_all_status.append(cur_status)

return generate_status(next_all_status, matrix)

def is_legal_status(expression, status, matrix):
    all_status = [set(s) for s in expression]

return status in generate_status(all_status, matrix)


text:
Q: Deploying ASP.NET MVC 5 Application to IIS 7.5 on Windows Server 2008 R2. when will browse its showing the root folders not routing to home page I have done the following

*

*app pool configuration as .Net framework 4.0

*Folder security (allow access for the app pool user)

*Website security (anonymous access is needed for my site)

*Re-register ASP.Net by running aspnet_regiis ad nauseam

*Added the section in web config file as
<system.webServer>
  <modules>
    <remove name="UrlRoutingModule-4.0"/>
    <add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" preCondition=""/>
  </modules>
</system.webServer>

I'd appreciate any pointers or personal experience.


text:
Q: Asymmetrical Border Image in CSS How would one create the following 'paintbrush' effect as a border around a div in CSS? The div in this case would be the red box.

Here is another example of a similar situation. The div in this case would be the blue box.

A: I would say that your best bet is to go with the border-image property
You can find some more info/examples here http://www.css3.info/preview/border-image/ You just need to find the stroke effect that you like and apply it in your case to the border-image
Heres a example
Codepen http://codepen.io/noobskie/pen/EVgaQL


text:
Q: Consider only files being pushed in pre-push hook git I want to run lint on code for pre-push without considering the local changed files the user has. for example change in file A is being pushed and the same got changed in the local changes I want to consider the code being pushed by user.
How to implement this using hit-hooks.
Alternate ways I tried:
Limiting the user to reset the changes in pre-push - The functionality is limited in this case

A: There are several ways to get files from git storage and write them to disk, but I don't know of a direct command to say straight away "checkout files A, B and C from commit xxx to that directory on disk".

The simplest way is probably to use git worktree add (but this checks out all files, not just the ones you want) :
git worktree add /tmp/myhook.xyz <commit-sha>

The most direct way is to use git --work-tree=... (or GIT_WORK_TREE=...) to target some other directory on disk :
git --work-tree=/tmp/myhook.xyz checkout <commit-sha> -- file1 file2 path/to/file3

How to use this in a pre-push hook:
for each pushed reference, you can :

*

*compare the local commit and remote commit to list files that were modified,

*use the above trick to checkout the files from local commit in a specific destination on disk :

# pre-push:
#!/bin/bash

zero=$(git hash-object --stdin </dev/null | tr '[0-9a-f]' '0')

list_modified_files () {
        local $local_commit=$1
        local $remote_commit=$2

        if [ "$local_commit" = "$zero" ]; then
                return
        fi

        if [ "$remote_oid" = "$zero" ]; then
                git ls-tree -r --name-only $local_oid
        else
                git diff --no-renames --diff-filter=AM --name-status $remote_oid $local_oid
        fi
}

while read local_ref local_oid remote_ref remote_oid
do
        echo "'$local_ref' '$local_oid' '$remote_ref' '$remote_oid'"
        tmpdir=$(mktemp -d /tmp/myprepushhook.XXXXXX)
        list_modified_files | xargs -r git --work-tree "$tmpdir" checkout "$local_oid" --

        # run linter on files in $tmpdir ...

        rm -rf "$tmpdir"
done


text:
Q: How to solve Type Error occurred when creating object: Webkul\MpBlog\Block\Account\Navigation? 1 exception(s):
Exception #0 (Magento\Framework\Exception\RuntimeException): Type Error occurred when creating object: Webkul\MpBlog\Block\Account\Navigation
Exception #0 (Magento\Framework\Exception\RuntimeException): Type Error occurred when creating object: Webkul\MpBlog\Block\Account\Navigation
#1 Magento\Framework\ObjectManager\Factory\Compiled->create('Webkul\MpBlog\Bl...', array('data' => array())) called at [vendor/magento/framework/ObjectManager/ObjectManager.php:56]
#2 Magento\Framework\ObjectManager\ObjectManager->create('Webkul\MpBlog\Bl...', array('data' => array())) called at [vendor/magento/framework/View/Element/BlockFactory.php:46]
#3 Magento\Framework\View\Element\BlockFactory->createBlock('Webkul\MpBlog\Bl...', array('data' => array())) called at [vendor/magento/framework/View/Layout/Generator/Block.php:272]
#4 Magento\Framework\View\Layout\Generator\Block->getBlockInstance('Webkul\MpBlog\Bl...', array('data' => array())) called at [vendor/magento/framework/View/Layout/Generator/Block.php:252]
#5 Magento\Framework\View\Layout\Generator\Block->createBlock('Webkul\MpBlog\Bl...', 'seller_mpblog', array('data' => array())) called at [vendor/magento/framework/View/Layout/Generator/Block.php:229]
#6 Magento\Framework\View\Layout\Generator\Block->generateBlock(&Magento\Framework\View\Layout\ScheduledStructure#0000000050651092000000005113cb26#, &Magento\Framework\View\Layout\Data\Structure#00000000506515ef000000005113cb26#, 'seller_mpblog') called at [vendor/magento/framework/View/Layout/Generator/Block.php:134]
#7 Magento\Framework\View\Layout\Generator\Block->process(&Magento\Framework\View\Layout\Reader\Context#0000000050651516000000005113cb26#, &Magento\Framework\View\Layout\Generator\Context#000000005065108a000000005113cb26#) called at [vendor/magento/framework/View/Layout/GeneratorPool.php:81]
#8 Magento\Framework\View\Layout\GeneratorPool->process(&Magento\Framework\View\Layout\Reader\Context#0000000050651516000000005113cb26#, &Magento\Framework\View\Layout\Generator\Context#000000005065108a000000005113cb26#) called at [vendor/magento/framework/View/Layout.php:352]
#9 Magento\Framework\View\Layout->generateElements() called at [vendor/magento/framework/Interception/Interceptor.php:58]
#10 Magento\Framework\View\Layout\Interceptor->___callParent('generateElements', array()) called at [vendor/magento/framework/Interception/Interceptor.php:138]
#11 Magento\Framework\View\Layout\Interceptor->Magento\Framework\Interception\{closure}() called at [vendor/magento/framework/Interception/Interceptor.php:153]
#12 Magento\Framework\View\Layout\Interceptor->___callPlugins('generateElements', array(), array(array('layout-model-cac...', 'core-session-dep...', 'customer-session...', 'catalog-session-...', 'persistent-sessi...', 'checkout-session...', 'tax-session-depe...'))) called at [generated/code/Magento/Framework/View/Layout/Interceptor.php:39]
#13 Magento\Framework\View\Layout\Interceptor->generateElements() called at [vendor/magento/framework/View/Layout/Builder.php:129]
#14 Magento\Framework\View\Layout\Builder->generateLayoutBlocks() called at [vendor/magento/framework/View/Page/Builder.php:55]
#15 Magento\Framework\View\Page\Builder->generateLayoutBlocks() called at [vendor/magento/framework/View/Layout/Builder.php:65]
#16 Magento\Framework\View\Layout\Builder->build() called at [vendor/magento/framework/View/Page/Config.php:224]
#17 Magento\Framework\View\Page\Config->build() called at [vendor/magento/framework/View/Page/Config.php:237]
#18 Magento\Framework\View\Page\Config->publicBuild() called at [vendor/magento/framework/View/Result/Page.php:242]
#19 Magento\Framework\View\Result\Page->render(&Magento\Framework\App\Response\Http\Interceptor#00000000506514dc000000005113cb26#) called at [vendor/magento/framework/View/Result/Layout.php:171]
#20 Magento\Framework\View\Result\Layout->renderResult(&Magento\Framework\App\Response\Http\Interceptor#00000000506514dc000000005113cb26#) called at [vendor/magento/framework/Interception/Interceptor.php:58]
#21 Magento\Framework\View\Result\Page\Interceptor->___callParent('renderResult', array(&Magento\Framework\App\Response\Http\Interceptor#00000000506514dc000000005113cb26#)) called at [vendor/magento/framework/Interception/Interceptor.php:138]
#22 Magento\Framework\View\Result\Page\Interceptor->Magento\Framework\Interception\{closure}(&Magento\Framework\App\Response\Http\Interceptor#00000000506514dc000000005113cb26#) called at [vendor/magento/framework/Interception/Interceptor.php:153]
#23 Magento\Framework\View\Result\Page\Interceptor->___callPlugins('renderResult', array(&Magento\Framework\App\Response\Http\Interceptor#00000000506514dc000000005113cb26#), array(array('result-messages', 'result-builtin-c...', 'result-varnish-c...'))) called at [generated/code/Magento/Framework/View/Result/Page/Interceptor.php:39]
#24 Magento\Framework\View\Result\Page\Interceptor->renderResult(&Magento\Framework\App\Response\Http\Interceptor#00000000506514dc000000005113cb26#) called at [vendor/magento/framework/App/Http.php:120]
#25 Magento\Framework\App\Http->launch() called at [vendor/magento/framework/App/Bootstrap.php:261]
#26 Magento\Framework\App\Bootstrap->run(&Magento\Framework\App\Http\Interceptor#00000000506514de000000005113cb26#) called at [index.php:39]


text:
Q: Moodle - Mudar estrutura da home de acordo com o usuario e manter diferente em relação as outras paginas Boa tarde,
Minha dúvida é o seguinte:
Preciso mudar a estrutura da home somente da home, em vez de deixar 3 colunas (navegação,conteúdo e aside-right) vou deixar apenas uma coluna que é do conteúdo, gostaria de saber se tem como eu deixar SOMENTE a home com essa estrutura e nas demais paginas internas eu manter a estrutura padrão de 3 colunas.
Outra dúvida:
Preciso criar duas homes, na estrutura citada acima, porem cada home vai exibir um conteúdo diferente de acordo com o login do usuário, ex: ADMIN vai ter acesso a uma home e Educador vai ter acesso a outra home, é possível? Alguma ideia de como fazer?
Estou conhecendo o moodle agora, ja criei um child theme e estou modificando ele, mas essas modificações acima achei mais complicada.
Obrigado

A: Veja o arquivo config.php do seu theme e configura conforme sua necessidade.
Tenho um theme que configurei da seguinte forma:
// The site home page.
    'frontpage' => array(
        'file' => 'frontpage.php',
        'regions' => array('side-post', 'middle'),
        'defaultregion' => 'side-post',
        'options' => array('nonavbar' => true),
    ),

// My dashboard page.
    'mydashboard' => array(
        'file' => 'columns2.php',
        'regions' => array('side-post'),
        'defaultregion' => 'side-post',
        'options' => array('langmenu' => true),
    ),

// Server administration scripts.
    'admin' => array(
        'file' => 'columns2.php',
        'regions' => array('side-post'),
        'defaultregion' => 'side-post',
    ),

dessa maneira você poderá configurar sua página inicial.
Em relação a segunda dúvida, você poderá resolver utilizando o arquivo renderers.php, fiz algo mais ou menos assim no meu tema:
protected function render_user_menu(custom_menu $menu) {
        global $CFG, $USER, $DB, $OUTPUT;

        $addlangmenu = true;
        $addmessagemenu = true;

        if (!isloggedin() || isguestuser()) {
            $addmessagemenu = false;
        }
        if (!$CFG->messaging) {
            $addmessagemenu = false;
        } else {
            // Check whether or not the "popup" message output is enabled
            // This is after we check if messaging is enabled to possibly save a DB query.
            $popup = $DB->get_record('message_processors', array('name' => 'popup'));
            if (!$popup) {
                $addmessagemenu = false;
            }
        }
...
}


text:
Q: Problema de escopo em namespace e classe, C++ Eu tentei criar uma classe de complexos em um namespace do C++ por exercício, mas quando tento definir alguns métodos da minha classe, o compilador retorna erro.
Meu código:
complex.h:
#ifndef COMPLEX_N_H
#define COMPLEX_N_H
#include <iostream>
#include <math.h>

using namespace std;

namespace complex_number{
    class complex_N{
    public:
        virtual double real() const;
        virtual double imag() const;
        virtual double module() const;
        virtual double arg() const;
        virtual const complex_N operator +(const complex_N& z);
        virtual const complex_N operator -(const complex_N& z);
        virtual const complex_N operator *(const complex_N& z);
        virtual const complex_N operator /(const complex_N& z);
        virtual const bool operator ==(const complex_N& z);
        ostream& operator <<(ostream& outputStream);
    };
}

#endif // COMPLEX_H

complex_e.h:
#ifndef COMPLEX_E_H
#define COMPLEX_E_H
#include "complex.h"

namespace complex_number{
    class complex_e : public complex_N {
    public:
        complex_e();
        complex_e(double a);
        complex_e(double a, double b);
        double real() const;
        double imag() const;
        double module() const;
        double arg() const;
        complex_e conj() const;
        const complex_e operator +(const complex_e& z);
        const complex_e operator -(const complex_e& z);
        const complex_e operator *(const complex_e& z);
        const complex_e operator /(const complex_e& z);
        const bool operator ==(const complex_e& z);
    private:
        double re_;
        double im_;
    };
}

#endif

complex_e.cpp:
#include "complex_e.h"

complex_number::complex_e::complex_e():re_(0), im_(0){

}

complex_number::complex_e::complex_e(double a):re_(a), im_(0){

}

complex_number::complex_e::complex_e(double a, double b):re_(a), im_(b){

}

double complex_number::complex_e::real(){
    return re_;
}

double complex_number::complex_e::imag(){
    return im_;
}

double complex_number::complex_e::module(){
    return sqrt(re_*re_+im_*im_);
}

double complex_number::complex_e::arg(){
    return atan(im_/re_);
}

complex_number::complex_e complex_number::complex_e::conj(){
    return complex_number::complex_e(re_,-im_);
};

const complex_number::complex_e operator+(const complex_number::complex_e& z){
    return(complex_number::complex_e(z.re_+re_, z.im_+im_));
}

const complex_number::complex_e operator-(const complex_number::complex_e& z){
    return(complex_number::complex_e(re_-z.re_, im_-z.im_));
}

Quando eu tento compilar esse código eu recebo erros como:

Erro 1: no declaration matches 'double
complex_number::complex_e::real()'

Erro 2: no declaration matches
'double complex_number::complex_e::imag()'

Para todas as funções definidas no complex_e.cpp, exceto os construtores e operadores.
Enquanto isso, nos operadores que eu defini eu recebo erros como:

error: 're_' was not declared in this scope
error: 'im_' was not declared in this scope

Quando re_ e im_ deveriam ser os atributos privados do objeto que chama os construtores.


text:
Q: How to extend primary partition? Linux My primary partition is running out of space (/dev/sda1). The main partition (/dev/sda) having much more free space. I want to transfer space from (/dev/sda) and extend to (/dev/sda1) partition which is my primary partition and have all linux boot, kernel etc files.
sudo fdisk -l
Disk /dev/sda: 204.8 GB, 204803670016 bytes,400007168 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size(logical/physical): 512 bytes / 512 bytes
I/O size(minimum/optimal): 512 bytes / 512 bytes

Device Boot      Start         End      Blocks   Id  System
/dev/sda1            2048   199997439    99997696     Linux

A: There are several things that need doing: re-size partition, then re-size file-system.
To make this easier there is gparted. It is a GUI, it will do both. You can not do it when the file-system is in use, so boot off of a live CD/USB. You can download the gparted OS. A small live OS with just a minimal tool kit, including gparted.
Alternatively
You have a root partition that is large (mine is only 20G).
Add a /home partition. This could fill the rest of the disk, you will not have to reboot. Just create the new partition, and mount it (gparted can do all of this, but you will have to install it first). Next copy you old /home to the new /home. You can use bind mount, to expose the, possiblyhidden/home`. (you probably want to logout of any account with data that could be lost, while doing this).
With the command line
It is a long time since I did it this way, as I always have to look it up (I don't do it enough. I use the command line for most things, but I don't do this much so use the GUI).
You have to do two things:
 - resize the partition.
 - resize the file-system (with the command that you have found).
You should not be using the file-system, when you re-size it. So will need a live CD/USB.
What I would do.
I would add a /home. I always to this, as it makes upgrades to new OS easier (replace OS, keep /home). You can also make links from other parts of / into /home E.g. /opt → /home/system/opt,/usr/local → /home/system/usr-local …

A: I think your are using your physical device as physical without any logical layer.
It is better to use logical volumes as it will help you manage your devices without touching the partition part.
When defining volume group, it give you possibilities to add physical devices to the group making abstraction to your logical partitions.
Later you can extend the logical volume with space available on volume group.


text:
Q: how to efficiently rename a lot of blobs in GCS Lets say that on Google Cloud Storage I have bucket: bucket1 and inside this bucket I have thousands of blobs I want to rename in this way:
Original blob:
bucket1/subfolder1/subfolder2/data_filename.csv
to: bucket1/subfolder1/subfolder2/data_filename/data_filename_backup.csv
subfolder1, subfolder2 and data_filename.csv - they can have different names, however the way to change names of all blobs is as above.
What is the most efficient way to do this? Can I use Python for that?

A: You can use whatever programming language you want where Google offers an SDK for working with Cloud Storage.  There is not going to be much of an advantage to any particular language you choose.
There is not really an "efficient" way of doing this.  What you will end up doing in your code is pretty standard:

*

*List the objects that you want to rename.

*Iterate that list.

*For each object, change the name.

You will get better performance overall if you run the code in a Google Cloud Shell or other Google Cloud compute environment in the same region as your bucket.

A: If you have a lot of rename to perform, I recommend to perform the operation concurrently (use several thread and not perform the rename sequentially).
Indeed, you have to know how works CLoud Storage. rename doesn't exist. You can go into the Python library and see what is done: copy then delete.
The copy can take time if your files are large. Delete is pretty fast. But in both case, it's API call and it take time (about 50ms if you are in the same region).
If you can perform 200 or 500 operations concurrently, you will significantly reduce the processing time. It's easier with Go or Node, but you can do the same in Python with await key word.


text:
Q: What are the pieces used to fill in a template called? If I have a template (say a generic letter) that is filled in with various pieces of data (say, the name of the addressee), what is a general term for those pieces of data?
For example:
Dear {firstname},
This is just a friendly reminder that the book {booktitle} will be due on {duedate}.
Thank you.

What would I refer to {firstname}, {booktitle} and {duedate} as?

A: You could refer to {firstname}, {booktitle} and {duedate} as placeholders or variables.

A: {firstname}, etc. would be 'fieldnames' and their instantiations might be "values" or "field-values".  The correct answer will depend on the context and as presented the context is apparently some sort of artificial language or text macro processor. The term 'form field' is more be correct in the context of an MS Word template. Arguably, this question is not really about English at all.

A: Since you're obviously looking for an abstract term I would suggest parameter.

A: When I was a child, I was asked to fill in the blanks on English class execises. I've seen it called fields too (though this reminds most of spreadsheet fields) and placeholders.

A: "Field names" is the term used in the Microsoft line of products for this kind of placeholder. The examples you posted in {brackets} are "field codes".
Quoting from a Microsoft help page for Office 2007:

When you view a field code in your document, the syntax looks like this:
{ FIELD NAME   Properties Optional switches }

*

*FIELD NAME     This is the name that appears in the list of field names in the Field dialog box.

*Properties    These are any instructions or variables that are used in a particular field. Not all fields have parameters, and in some fields, parameters are optional instead of required.

*Optional switches    These are any optional settings that are available for a particular field. Not all fields have switches available, other than those that govern the formatting of the field results.

I hope this helps.
In general, the Microsoft language and terminology site can be very helpful to find IT-related English words, especially if you are not a native speaker of English.
Link: http://www.microsoft.com/Language/en-US/Terminology.aspx

A: Nomenclature varies, but it is common to refer to the entire process as a mail merge, and to call the placeholders in the document variables. The values used by the merge process are taken from fields or columns (depending on the type of database) which are bound to the variables.
See for example "Writer/Mail Merge" at LibreOffice Help.


text:
Q: setting annotation attributes in spring xml I have been trying to set the logTime attribute in my annotation in the spring xml. I am seeing that this is not as easy as I first thought.
@Component
@Retention(RetentionPolicy.RUNTIME)
public @interface LogExecTime {

public boolean logTime() default true;
}

I have tried to use the @Value annotation with the interface with no luck:
I)

  @Component
  @Retention(RetentionPolicy.RUNTIME)
  public @interface LogExecTime {
    @Value("#{ConfigureAnnotation.doLogging}")
public boolean logTime() default true;
  }

and also
II)
 @LogExecTime(logTime=@Value("#{ConfigureAnnotation.doLogging}"))

Any ideas how I can do this at xml level or is this not possible with annotation dependency injection?

A: Yeah -- that's not ever going to work.
@LogExecTime(logTime=@Value("#{ConfigureAnnotation.doLogging}"))

will never even compile.  Annotations are not executable code, they're just markers -- extra bit of information that are inserted into the class file whole sale.
You could either put this:
@Value("#{ConfigureAnnotation.doLogging}")
boolean logTime = true;

As a real field on a spring managed bean somewhere, or have  change your annotation to be like:
@Component
@Retention(RetentionPolicy.RUNTIME)
public @interface LogExecTime {

    public String logTime() default "true";
}

and have whatever is processing that annotation at run time also accept a spring EL expression and resolve it appropriately, and your component would look like this:
@LogExecTime(logTime = "#{ConfigureAnnotation.doLogging}")
public class SomeComponent {

    // blah blah blah
}


text:
Q: Spring API Resource URIs wrong in Docker Environment I have an issue with my Spring Boot API, which I use in combination with Docker and Nginx as a reverse proxy.
At the moment I am setting up a website together with a REST webservice. The webserver and the REST webservice (Spring Boot) are running in two different Docker containers. In order to provide HTTPS (encryption) I use NGINX as a reverse proxy (which is also running as a Docker-Container).
Now I am using the following setup in my nginx.conf to enable outside access to my Spring API.
upstream spring-backend {
    server spring:8081;
}

# ... some other configuration stuff

server {
    listen               7332;
    ssl                  on;

    #   ... ssl-config

    # all other traffic
    location / {
        # Specify the fields added/redefined to the request header passed to the proxied server.
        proxy_set_header        Upgrade $http_upgrade;
        proxy_set_header        Connection $connection_upgrade;
        # Timeout for reading a response from the proxied server.
        proxy_read_timeout      3600; # keep open even without any transmission
        proxy_pass              http://spring-backend;
    }
}

While this works well, I am encountering the issue that API URIs Spring creates for the created entities look as follows: http://spring-backend/{entity}/{id}.
This apparently cannot be accessed from another computer consuming the website and it's associated webservice. Instead I would need the entries to be https://{the-url-of-the-webserive}:7332/{entity}/{id}.
However I am not sure whether it is possible to get this resolution from the name-resolution NGINX uses (as it should replace server-backend with spring:8081) and the one of Docker (should replace at least the spring part with the actual adress).

A: Actually this can be solved by adding X-Forward-* headers to the location part of server.
This should than look as follows:
location / {
    # Specify the fields added/redefined to the request header passed to the proxied server.
    proxy_set_header        Upgrade $http_upgrade;
    proxy_set_header        Connection $connection_upgrade;

    #--------------------------------- SOLUTION -------------------------------------------
    proxy_set_header        Host               $host;
    proxy_set_header        X-Real-IP          $remote_addr;
    proxy_set_header        X-Forwarded-For    $proxy_add_x_forwarded_for;
    proxy_set_header        X-Forwarded-Host   $host:443; #or $host:7332 in my case
    proxy_set_header        X-Forwarded-Server $host;
    proxy_set_header        X-Forwarded-Port   443; #or 7332 in my case
    proxy_set_header        X-Forwarded-Proto  https;
    #------------------------------- SOLUTION-END -----------------------------------------

    # Timeout for reading a response from the proxied server.
    proxy_read_timeout      3600; # keep open even without any transmission
    proxy_pass              http://spring-backend;
}

That code snippet has been taken from plone.lucidsolutions.co.nz where you can also find further information on this solution.


text:
Q: How to send a mail in PHP and MySQL on a particular date? I am using PHP and MySQL. I am trying to send a mail but it is not working. I want to check two dates and send a mail on a particular date.
   if (isset($_POST['mail_sub']))
          {
            $selectDate  = "select * from insurance_data";
            $querydate   =  mysql_query($selectDate) or die (mysql_error());
            while ($roedate = mysql_fetch_array($querydate))
            {
                $date1 = $roedate['duedate'];
                $date=date('Y-m-d',strtotime($date1.' -3 days'));
                echo '
';
                echo  $date;
                echo $today = date('Y-m-d');

                if ($date==$today)
                {
                          $to           =   "2606ankit@gmail.com";  //put email address on which mail send
                        $subject        =   "Query Mail";                   //Put subject of mail here
                       $from        =   "2606ankit@gmail.com";      //put email address from
                   //email body start
                       $body        .=  "Alert";
                   // Always set content-type when sending HTML email

                        $headers  = 'MIME-Version: 1.0' . "\r\n";
                        $headers .= 'Content-type: text/html; charset=UTF-8' . "\r\n";

                    // More headers
                    $headers .= 'From: '.$from. "\r\n";

                    //if you need to send cc mail then uncomment below line and change email address
                    //$headers .= 'Cc: myboss@example.com' . "\r\n";

                     mail($to,$subject,$body,$headers);

                    //echo 'asdfasdf';
                }
                else
                {
                    echo 'nahi';
                }

            }}

A: Ok, Please check the following solution:--
 if (isset($_POST['mail_sub']))
          {
            $selectDate  = "select * from insurance_data";
            $querydate   =  mysql_query($selectDate) or die (mysql_error());
            while ($roedate = mysql_fetch_array($querydate))
            {
                $date1 = $roedate['duedate'];
                $date=strtotime($date1.' -3 days'); // Remove the date
                echo '
';
                echo  $date;
                echo $today = strtotime(date('Y-m-d')); // User strtotime

                if ($date==$today)
                {


text:
Q: Is there a function like onChange which will also listen to a change by JavaScript? When I use onChange(), it triggers only when user changes something in an input field. I want it to trigger even when JavaScript changes something in an input field. How can I achieve this?

A: You can add an event listener.

  document.getElementById("fooId").addEventListener("change", func);
    function func(e){
     alert(e.target.value)
    }
<input type="text" id="fooId"/>

A: You need to add EventListener() method

A: Update:
So user https://www.webdeveloper.com/u/Sempervivum helped me and found this script originaly posted by Shawn Regan here: detect value change in input tag with vanilla javascript and MutationObserver which does exactly what I was looking for.
You can find working demo here: https://jsfiddle.net/zyx54/hdn4txry/
That script here:
let registered = [];
let setDetectChangeHandler = function(field) {
  if (!registered.includes(field)) {
    let superProps = Object.getPrototypeOf(field);
    let superSet = Object.getOwnPropertyDescriptor(superProps, "value").set;
    let superGet = Object.getOwnPropertyDescriptor(superProps, "value").get;
    let newProps = {
      get: function() {
        return superGet.apply(this, arguments);
      },
      set: function (t) {
        let _this = this;
        setTimeout( function() { _this.dispatchEvent(new Event("change")); }, 50);
        return superSet.apply(this, arguments);
      }
    };
    Object.defineProperty(field, "value", newProps);
    registered.push(field);
  }
}

A: this should help.
https://www.w3schools.com/jsref/event_onchange.asp
else if you have more specific need, then share that

A: This way to add eventlistner to input.

var sampleFunction = function(values){
  document.getElementById("sample").value = "New text";
}

var input = document.getElementById("sample");

input.addEventListener('change', (event) => {

  console.log("afafaf");
});

 <input type="text" id="sample" onchange="sampleFunction(this.value)"/>


text:
Q: How to remove custom action/link from list item menu? In SharePoint 2013, using Designer 2013, I created a custom action for a list while creating a new form for it.

Then I scrapped the new form. I actually did this twice.
Now, in the list's item menu, the custom actions show up, but I don't want them to. They don't correlate to anything.

How do I remove them?
I want to truly remove them. I've seen forum chatter across the interwebs about hiding list actions with various methods like JavaScript, but this just seems silly to me. I'm in the middle of tinkering with custom forms and actions, etc. for this list. While I'm definitely going to be more careful about creating custom actions, it's bound to happen again that I'll create a custom action for testing/experimenting while I try to perfect this list. So it would make so much more sense to just know how to actually delete custom actions altogether. Beyond that, understanding how to heal the wound seems infinitely more valuable to me than having to find and rely on Band Aids. In other words, I'm wholly unimpressed and uninterested in any answers that explain how to hide. Instructions for removal are the only thing I'm interested in.

A: *

*Open site in SharePoint Designer

*From left navigation choose Lists and Libraries

*Open the list in question

*Now from right pane - Look under "Custom Actions"

*Select the action to delete

*Use Ribbon "Delete" button OR press Delete key


text:
Q: Get git repository .git from remote into an existing working copy I have a project that's managed via git and I deleted the .git folder.  Is it possible to grab only the .git only from the remote repository instead of cloning the entire repo again?

A: clone to an empty directory, then move the .git to your existing working copy.
You can use git clone -n to avoid the checkout of the HEAD after the clone, but you'll have to move the .git anyway, because there doesn't seem to be a way to clone into a non-empty directory.


text:
Q: mysql questions variable I have a web server which is quite heavy on the mysql server:
Here is a graph of questions being executed on the database:

Is there a way to increase the max questions allowed?  You see how the graph tops off and stays around 5K while the web server is active?
Yes, other things are being done on the code side of things, just wondering what we can do in my.cnf.  All tables are already being served from /dev/shm.
Thanks!

A: It is possible that there is a limit set on the number of queries a particular user is able to run per minute, and if your web service logs in to the database using the same user id for all queries, you may be hitting that limit.
Check this page out for more information, it will show you how to check and alter those limits on your system.
https://dev.mysql.com/doc/refman/5.5/en/user-resources.html
Hope it helps!


text:
Q: didExitRegion not being called, loops didEnterRegion I am fairly new to iOS Development and I am trying to create an App that allows region monitoring. Similar to that of the iOS Reminders App.
I have my code to the point where I am starting monitoring for regions and it should notify me when I enter and leave a region. However, it only tells me when I am in the region. When I leave, it does not tell me.
Just so you know, I am testing this on my iPhone and definitely went outside of the 100m radius (I drove my car for 10 minutes away from my house). It kept looping messages saying I was in the region but never changed when I exited the region. I am really stumped as to where I am going wrong. Can anyone help? Also, just out of curiosity, as I am new to iOS development, am I going about this the correct way? Or is there a more efficient way of accomplishing this? Any advise, tutorials, howto's would be very much appreciated. Thanks guys! My code to start the region monitoring and methods are below. Let me know if you need any other code.
(IBAction)addRegion:(id)sender {
    if ([CLLocationManager isMonitoringAvailableForClass:[CLBeaconRegion class]]) {
        // Create a new region based on the center of the map view.
        CLLocationCoordinate2D coord = CLLocationCoordinate2DMake(_mapView.centerCoordinate.latitude, _mapView.centerCoordinate.longitude);
        region = [[CLCircularRegion alloc] initWithCenter:coord
                                           radius:Radius
                                       identifier:[NSString stringWithFormat:@"%f, %f", _mapView.centerCoordinate.latitude, _mapView.centerCoordinate.longitude]];

        // Start monitoring the newly created region.
        [_locationManager startMonitoringForRegion:(CLRegion *)region];
    }
    else {
     NSLog(@"Region monitoring is not available.");
    }
}

(IBAction)stopMonitoringRegion:(id)sender {
   [_locationManager stopMonitoringForRegion:(CLRegion *)region];
}

(void)locationManager:(CLLocationManager *)manager
     didDetermineState:(CLRegionState)state forRegion:(CLRegion *)reg {

   if (state == CLRegionStateInside) {
       //call didEnterRegion
       //[_locationManager stopMonitoringForRegion:region];
       [self locationManager:_locationManager didEnterRegion:region];
   }
   if (state == CLRegionStateOutside) {
       //call didExitRegion
       //[_locationManager stopMonitoringForRegion:region];
       [self locationManager:_locationManager didExitRegion:region];
   }
}

(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    NSLog(@"didFailWithError: %@", error);
}

(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {

//requestStateForRegion
if (region == nil) {
    //do nothing
    NSLog(@"didUpdateToLocation %@ from %@", newLocation, oldLocation);
}else{
[_locationManager requestStateForRegion:region];
    NSLog(@"didUpdateToLocation %@ from %@", newLocation, oldLocation);
}
}

(void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region  {
    NSLog(@"didEnterRegion %@ at %@", region.identifier, [NSDate date]);
}

(void)locationManager:(CLLocationManager *)manager didExitRegion:(CLRegion *)region {
    NSLog(@"didExitRegion %@ at %@", region.identifier, [NSDate date]);
}

(void)locationManager:(CLLocationManager *)manager monitoringDidFailForRegion:(CLRegion *)region withError:(NSError *)error {
    NSLog(@"monitoringDidFailForRegion %@: %@ Error: %@", region.identifier, [NSDate date], error);
}


text:
Q: extend derivations of ore domain to its quotient field I wonder whether someone knows a good reference(textbook or paper) for the following result:
Any derivation of ore domain may be extended unqiuely to a derivation of its quotient field.
Thanks.


text:
Q: Continuous data acquisition with a PyQt GUI I am building an application where I acquire data continuously from a National Instruments device and do some real time processing on it. I am trying to hook the acquisition part to a PyQt GUI so that the user can start, stop and configure the data acquisition and see the data. I have one class for the data acquisition and one class for the GUI. I start the data acquisition process as a thread within the GUI:
# data acquisition class
class intensimetre():
   #initialize the data acquisition
   def __init__(self,app=None,l1=None,l2=None,l3=None):

       #...

   #start the data acquisition
   def demarrer(self,fs=51200.,sensibilite0=12.2,sensibilite1=10.7, rho=1.21, espaceur=0.012, c=343):

       #start the acquisition task
       nidaq.DAQmxStartTask(tache)

    #if i add this line it works
    #raw_input(u'appuyez sur entree pour continuer')

#gui class
class GUI_acquisition(QtGui.QWidget):
   def __init__(self, app=None):

       super(GUI_acquisition, self).__init__()

       #create the gui
       #...

       #create an instance of the data acquisition class
       self.intensimetre=
       intensimetre(app=self.app,l1=self.l1,l2=self.l2,l3=self.l3)

   def demarrer(self):

       #start the data acquisition in a thread
       t = threading.Thread(target=self.intensimetre.demarrer)
       t.start()

The problem is that the application crashes as soon as I start the data acquisition. If I add the raw_input line after starting the acquisition, then it works as it should. However, it doesn't feel like the right way to do it. It seems that once the acquisition is started, the thread returns and the callbacks from the acquisition are not processed properly. Any idea of how to fix this?
Update
I've replaced the raw_input line by an infinite loop polling the state  a status attribute:
while self.isRunning:
    sleep(0.1)

I set the isRunning to True attribute when the user presses the start button and to False upon pressing of the stop button. While this works, I don't like polling as I think it can have a negative impact on the performance of my app.


text:
Q: Difference between rebooting and stop-starting an amazon EC2 instance I noticed that calling ec2.rebootInstances on an Amazon EC2 instance was much much faster than stopping and starting it again (ec2.stopInstances ec2.startInstances).
It also preserved the IP address of the instance (I dont have elastic IP on it)
What does ec2.rebootInstance do that is different from stopping and starting an instance?

A: When you stop an EBS boot instance you are giving up the physical hardware (or slice of it) that the server was running on and EC2 is free to start somebody else's instance there.
Your EBS boot volume (and other attached EBS volumes) are still preserved, though they aren't really tied to a physical or virtual server.  They are just associated with an instance id that isn't running anywhere.
When you start the instance again, EC2 picks some hardware to run it on, ties in the EBS volume(s) and boots it up again from the root volume.
Things that change when you stop/start include:

*

*New internal IP address (though could randomly be the same).

*New external IP address (though could randomly be the same).

*If an Elastic IP address was associated with the instance before it was stopped, then you'll need to re-associate it after the start.

*Any contents on the instance's former ephemeral storage were wiped and you are given fresh ephemeral storage.

*You can leave an instance stopped for as long as you like and not get charged for run time (though you do get charged at a much lower rate for the EBS volume storage).  See the next point.

*A fresh billing hour is started for the instance when you start it again. E.g., if you start a new instance and then stop/start it 3 times within the first 60 minutes, you'll get charged for 4 hours instead of 1.

*There is a small chance that EC2 will not have available slots of the correct instance type to run your instance when you want to start it again. I've had this happen and temporarily switched to a different, available instance type to get it running again.
When you reboot, it's a simple reboot at the OS level and the instance stays running on the same hardware, with the same private and public IP addresses, keeps the same Elastic IP address (if associated), and keeps the same ephemeral storage without getting wiped.  No new billing hour is started on a reboot and you do not give up the instance hardware.
While an instance is stopped, you can do some cool things before starting it again.  Here's an article I wrote on changing the instance type of an instance while it's stopped:

Moving an EC2 Instance to a Larger Size
http://alestic.com/2011/02/ec2-change-type

Here's an article I wrote on how to change the size of an EBS boot disk of an instance while it's stopped:

Resizing the Root Disk on a Running EBS Boot EC2 Instance
http://alestic.com/2010/02/ec2-resize-running-ebs-root

Here's an article I wrote on how to examine the root disk of an instance (while it's stopped) when you can't connect to it while it's runnning:

Fixing Files on the Root EBS Volume of an EC2 Instance
http://alestic.com/2011/02/ec2-fix-ebs-root

Since the stop/start cycle has a good chance of moving your instance to new hardware, it's an easy way to replace your instance hardware if you suspect that the current platform might be going bad and causing problems.  Here's an article I wrote about that:

A Simpler Way To Replace Instance Hardware on EC2
http://alestic.com/2011/02/ec2-move-hardware


text:
Q: Testing multiple scanner inputs with different variable types So I have this method that requires multiple inputs from the console.
public void inputBook(Scanner scan){

    String author = null;
    System.out.println("Enter the book author: ");
    author = scan.next();

    String title = null;
    System.out.println("Enter the book title: ");
    title = scan.next();

    String type = null;
    int typeBook = 0;
    System.out.println("Enter 1 for fiction, 2 for non-fiction, or 3 for a comic: ");
    while(true){
        try {
            typeBook = scan.nextInt();
            switch (typeBook){
                case 1:
                    type = "fiction";
                case 2:
                    type = "non-fiction";
                case 3:
                    type = "comic";
            }
            break;
        }catch (InputMismatchException e){
            System.out.println("Enter 1 for fiction, 2 for non-fiction, or 3 for a comic: ");
        }
    }

    Book book = new Book(author,title, type);
    scan.close(); //close scanner
}

I'm not sure how I would test it in JUnit with the following variables as inputs. I've seen solution about Bytestreams, but I don't recall seeing anything that requires the types to remain the same. Should I rewrite the method to only take string inputs and then cast those?
            String author = "N.K Jemisin";
            String title = "The Fifth Season";
            Integer type = 1;


text:
Q: ffmpeg - error message "Invalid data found when processing input" when trying to convert a video file but video is playable I'm using ffmpeg version
ffmpeg version 4.2.1 Copyright (c) 2000-2019 the FFmpeg developers
  built with Apple clang version 11.0.0 (clang-1100.0.33.8)
  configuration: --prefix=/usr/local/Cellar/ffmpeg/4.2.1_1 --enable-shared --enable-pthreads --enable-version3 --enable-avresample --cc=clang --host-cflags='-I/Library/Java/JavaVirtualMachines/adoptopenjdk-13.jdk/Contents/Home/include -I/Library/Java/JavaVirtualMachines/adoptopenjdk-13.jdk/Contents/Home/include/darwin -fno-stack-check' --host-ldflags= --enable-ffplay --enable-gnutls --enable-gpl --enable-libaom --enable-libbluray --enable-libmp3lame --enable-libopus --enable-librubberband --enable-libsnappy --enable-libtesseract --enable-libtheora --enable-libvidstab --enable-libvorbis --enable-libvpx --enable-libx264 --enable-libx265 --enable-libxvid --enable-lzma --enable-libfontconfig --enable-libfreetype --enable-frei0r --enable-libass --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-librtmp --enable-libspeex --enable-libsoxr --enable-videotoolbox --disable-libjack --disable-indev=jack
  libavutil      56. 31.100 / 56. 31.100
  libavcodec     58. 54.100 / 58. 54.100
  libavformat    58. 29.100 / 58. 29.100
  libavdevice    58.  8.100 / 58.  8.100
  libavfilter     7. 57.100 /  7. 57.100
  libavresample   4.  0.  0 /  4.  0.  0
  libswscale      5.  5.100 /  5.  5.100
  libswresample   3.  5.100 /  3.  5.100
  libpostproc    55.  5.100 / 55.  5.100

When I try to process this video using this command
ffmpeg -i IMG_0029.mp4 -y newvideo2.mp4

I get this output
[mov,mp4,m4a,3gp,3g2,mj2 @ 0x7f8a1f008200] could not find corresponding trex (id 1)
[mov,mp4,m4a,3gp,3g2,mj2 @ 0x7f8a1f008200] could not find corresponding track id 0
[mov,mp4,m4a,3gp,3g2,mj2 @ 0x7f8a1f008200] trun track id unknown, no tfhd was found
[mov,mp4,m4a,3gp,3g2,mj2 @ 0x7f8a1f008200] error reading header
IMG_0029.mp4: Invalid data found when processing input

I don't understand what is the problem as the video is playable.
Would appreciate any help.

A: Update to FFmpeg 4.3 or newer, or use a build from the current git master branch.
Relevant commit: mov: Support fake moov boxes disguised as hoov.


text:
Q: How can I get HttpServletRequest and HttpServletResponse object in Spring AOP I want to get the response object in spring AOP before advice. If the session is invalidate I want to redirect to the login page, but unable to get the HttpServletResponse object in the Before advice method.
Tried with the following way.
    @Autowired
    private HttpServletResponse response;

    public void setResponse(HttpServletResponse response) {
        this.response = response;
    }

Stacktrace:
caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: javax.servlet.http.HttpServletResponse com.****.****.aspect.LogProvider.response; nested exception is

org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [javax.servlet.http.HttpServletResponse] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:506)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:284)
    ... 33 more

Any help will be appreciated.

A: Basically we do redirect from a jsp page i.e. from UI layer we handle such kind of operation(redirection). So, I hope you will be using some restful services in your application. And for most of the restful services we go for Asynchronous request. If it is combination of Asynchronous and restful services; and I am sure you will be using this in your application. If your session is invalid and you try to access perform any operation on 'session' then it will land you in 'IllegalStateException'. For such type of scenario please follow the below centralized 'Exception Handling' mechanism provided by JAX-RS: javax.ws.rs.ext.ExceptionMapper.
Please follow below steps:
step-1: Create a user-defined unchecked exception like MyApplicationException:
public class MyApplicationException extends RuntimeException {
  public MyApplicationException() {super();}

  // implement other methods of RuntimeException as per your requirement
}

step-2: Create a user-defined type of ExceptionMapper
public class MyApplicationExceptionHandler implements ExceptionMapper<MyApplicationException>
{
    @Override
    public Response toResponse(MyApplicationException exception)
    {
        return Response.status(Status.FORBIDDEN).entity(exception.getMessage()).build();
// set any Status code of 4XX as this is client side error not server side
    }
}

step-3: In all your ajax request in the UI code check this Status Code and redirect to the login page.
That's it and you are done with a finer implementation. Guaranteed...

A: You can get response by under method:
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
HttpServletResponse response = ((ServletRequestAttributes)requestAttributes).getResponse();

A: /**
 * @return the HttpServletResponse handled by the current thread
 */
public static Optional<HttpServletResponse> getThreadLocalResponse() {
    return Optional.ofNullable(RequestContextHolder.getRequestAttributes())
            .filter(ra -> ra instanceof ServletRequestAttributes)
            .map(ServletRequestAttributes.class::cast)
            .map(ServletRequestAttributes::getResponse);
}

A: To get the response object you can use this code:
ServletWebRequest servletWebRequest=new ServletWebRequest(request);
HttpServletResponse response=servletWebRequest.getResponse();

To get the request object:
HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.currentRequestAttributes()).getRequest();

If you get a null response then I can see the response is not yet formed when the control is returned. Then the only way ahead is to go with interceptors.


text:
Q: Running process in parallel for data collection I am collecting data from two pieces of equipment using serial ports (scale and conductivity probe). I need to continuously collect data from the scale which I average between collection points of the conductivity probe (roughly a minuet).
Thus I need to run two processes at the same time. One that collects data from the scale, and other which waits for data from the conductivity probe, once it gets the data it would send a command to the other process in order to get the collected scale data, which is then time stamped and saved into .csv file.
I looked into subprocess but it I cant figure out how to reset a running script. Any suggestions on what to look into.

A: Instead of using threads you could also implementing your data sources as generators and just loop over them to consume the incoming data and do something with it. Perhaps using two different generators and zipping them together, actually would be a nice experiment I'm not entirely sure it can be done...


text:
Q: Prove that $\mathbb{Q}(r+s\sqrt{t})=\mathbb{Q}(\sqrt{t})$.
Let $r,s,t\in\mathbb{Q}$. Prove that
  $\mathbb{Q}(r+s\sqrt{t})=\mathbb{Q}(\sqrt{t})$.

Ok. So I've fallen a little behind in my algebra class, and I'm a bit confused on how to approach this problem. I know that $\mathbb{Q}(\sqrt{t})=\{a+b\sqrt{t}\mid a,b\in\mathbb{Q}\}$. So I'm assuming that I need to show $\mathbb{Q}(r+s\sqrt{t})\subseteq\mathbb{Q}(\sqrt{t})$ and $\mathbb{Q}(\sqrt{t})\subseteq\mathbb{Q}(r+s\sqrt{t})$. However, I'm unsure of how to go about defining $\mathbb{Q}(r+s\sqrt{t})$ as a set.
Another approach I am considering is to show that $\sqrt{t}$ and $r+s\sqrt{t}$       have the same minimal polynomial in $\mathbb{Q}[x]$. This would prove that $\mathbb{Q}(r+s\sqrt{t})\cong\mathbb{Q}(\sqrt{t})$, which may get me some where closer to where I need to be.
Please steer me in the correct direction. I prefer advice to answers. Thank you in advance for your help.
Additional info: If $K$ is a field and $F$ is a subfield of $K$ and $u\in K$, then $F(u)$ is the simple extension of $F$ - the intersection of all subfields of $K$ that contain both $u$ and $F$. So, in my problem, I'm assuming that $K=\mathbb{C}$ and $F=\mathbb{Q}$. I also know that $u$ is the root of a unique monic irreducible polynomial (called the minimal polynomial of $u$) in $F[x]$- the set of all polynomials with coefficients in $F$.

A: The question is false when $s = 0$ and $t$ is not a square, for obvious reasons. So suppose $s\neq 0$.
By definition, $\mathbb{Q}(r+s\sqrt{t})$ is some field (actually, the smallest) containing both $\mathbb{Q}$ and $r+s\sqrt{t}$. But if it contains $\mathbb{Q}$, then in particular it contains $r$ and $s$. Now:

*

*as it contains $r+s\sqrt{t}$ and $r$ and it's a field, we may subtract one from the other to show that it contains $s\sqrt{t}$;

*as it contains $s\sqrt{t}$ and $s\neq 0$, we may divide one by the other to show that it contains $\sqrt{t}$.

To sum up, it's a field, and it contains $\mathbb{Q}$ and $\sqrt{t}$: that is, it must feature somewhere in the big intersection of fields that defines $\mathbb{Q}(\sqrt{t})$, so we have $\mathbb{Q}(\sqrt{t}) \subseteq \mathbb{Q}(r+s\sqrt{t})$.
The converse is basically identical. $\mathbb{Q}(\sqrt{t})$ contains $\sqrt{t}$, which I can multiply by $s$ and then add $r$ to to show that it contains $r+s\sqrt{t}$.
(Sorry for writing up a full answer, but I felt that any hint I could give would give all the details away anyway!)

A: Taking $s\neq 0$
$r+s\sqrt t \in \mathbb Q(r+s\sqrt t) \implies s\sqrt t\in \mathbb Q(r+s\sqrt t)\implies \sqrt t\in \mathbb Q(r+s\sqrt t)$ since $s\neq 0$
Now $\mathbb Q(\sqrt t)$ is the smallest field containing $\mathbb Q$ and $\sqrt t$
Thus $\mathbb Q(\sqrt t)\subset \mathbb Q(r+s\sqrt t)$
similarly $r,s,\sqrt t\in \mathbb Q(\sqrt t)\implies r+s\sqrt t \in \mathbb Q(\sqrt t)\implies \mathbb Q(r+s\sqrt t)\subset \mathbb Q(\sqrt t)$


text:
Q: Java - String array null pointer exception I get a null pointer exception. Why? I tried and debugged the code...Java says the String array is filled. But when i start the program without debugging mode, Java says nullpointerexception...
BufferedReader quelle = new BufferedReader(new FileReader(file));
    String auftrag = quelle.readLine();
    String[] daten = auftrag.split(";");
//...
String test;

    for(int i = 3;i<=daten.length-1;i+=3)
    {

        test = daten[i-3] + " " + daten[i-2] + " " + daten[i-1];
        g.drawString(daten[i-3] + " " + daten[i-2] + " " + daten[i-1],x,y);
        y += 16;
    }


text:
Q: AWS Data Pipeline didn't showing EC2 instance role I am trying to get data from S3 to Dynamodb using AWS Data Pipeline. The issue I am facing is that my "Data Pipeline" wasn't showing EC2 instance role even though I have created one in the IAM. I have created default roles for Pipeline and EC2.

You can see in the picture that Pipeline Role is showing but the EC2 role didn't appear. I have refreshed several times and recreated Pipeline but didn't get the expected result.

A: I ran into this problem too.
I think you need to create an instance profile.
Data Pipeline's doc says that you should choose EC2 Role for Data Pipeline use case to create a resource role. But if you do that, instance profile won't be created.
Instead, you need to choose EC2 use case and attach policies to the role. Instance profile will be created automatically.

A: I resolved this issue by creating a standard EC2 role for the Instance Role and not using the Data Pipeline option while making the Resource role. Creating the EC2 Resource role using the Data Pipeline option seems to be deprecated.


text:
Q: C# Web Service Impersonation If I enable impersonation in a web service with identity="someID"... As web service is MTA application the impersonation that is applied may be applied to a worker thread and not the thread that actually call the method... I guess you might get an access denied error...Without problematically doing impersonation .. just by enabling it in webconfig .. what changes will i have to make to my function which does some clever stuff?
<identity impersonate="true" userName="DomainName\UserName"
                         password="ClearTextPassword" />

The <identity> element within Web.config supports optional user name and password attributes which allows you to configure a specific fixed identity for your Web service to impersonate. This is shown in the following configuration file fragment...
what else do i need to write?
System.Diagnostics.Process[] p = System.Diagnostics.Process.GetProcesses();
p.GetExccutiong();
Console.WriteLine();

A: IMO, the best way to configure the identity of a web-service is via the host - IIS, for example. In IIS, you can configure this via the app-pool identity (like in this answer). No need for plain-text passwords, and no need for hacky code.