text:
Q: I am new to LDAP and C# coding, wanted to validate the given user password in LDAP server using c# I am new to LDAP and C# coding, wanted to validate the given user password in LDAP server using c#. I am using ApacheDS 2.0.0 for Open LDAP server and I have following code to access the server. I am trying to use the method to validate the password of the user from the Ldap server end. Could anyone suggest what method can I use for the validation.
 using System;
 using System.Net;
 using System.Security.Permissions;
 using System.DirectoryServices;
 using System.DirectoryServices.Protocols;
 using System.DirectoryServices.AccountManagement;

namespace LdapConnection
{
[DirectoryServicesPermission(SecurityAction.LinkDemand, Unrestricted = true)]
public class LdapConnect
{

    public static void Main(string[] args)
    {
        try
        {
            // Create the new LDAP connection
            LdapDirectoryIdentifier ldi = new LdapDirectoryIdentifier("localhost",
            10389); // _msdcs.cc.ebs.corp:389
            System.DirectoryServices.Protocols.LdapConnection ldapConnection =
            new System.DirectoryServices.Protocols.LdapConnection(ldi);
            Console.WriteLine("LdapConnection is created successfully.");
            ldapConnection.AuthType = AuthType.Basic;
            ldapConnection.SessionOptions.ProtocolVersion = 3;
            NetworkCredential nc = new NetworkCredential("uid=admin,ou=system",
            "password"); //password
            ldapConnection.Bind(nc);
            Console.WriteLine("LdapConnection authentication success");

            var request = new SearchRequest("o=Company", "
            (objectClass=inetOrgPerson)",
            System.DirectoryServices.Protocols.SearchScope.Subtree, null);
            var response = (SearchResponse)ldapConnection.SendRequest(request);
            foreach (SearchResultEntry entry in response.Entries)
            {
                if (entry is null)
                {
                    continue;
                }
                Console.WriteLine($"entry {entry.DistinguishedName}");
                Console.WriteLine($"entry {entry.GetHashCode()}");

                foreach (var name in entry.Attributes.AttributeNames)
                {
                    Console.WriteLine($"Attributes Names ->{name}");
                }

                foreach (DirectoryAttribute value in entry.Attributes.Values)
                {
                    Console.WriteLine($"Attributes Values ->{value}");
                }
            }

        }

        catch (LdapException e)
        {
            Console.WriteLine("\r\nUnable to login:\r\n\t" + e.Message);
        }
        catch (Exception e)
        {
            Console.WriteLine("\r\nUnexpected exception occured:\r\n\t" + e.GetType()
         + ":" + e.Message);
        }
      }
     }
 }


text:
Q: how to use pointer to pointer to access pointer element in struct? #include<stdlib.h>
typedef struct
{
    int *member;
} mystruct;

void main(int argc, char *argv)
{
    mystruct **data;
    data = (mystruct**)malloc(sizeof(mystruct*));
    int c = 5;
    printf("%x", data);
    (*data)->member = &c;
    printf("Member: %d", *((*data)->member));
}

Error: Segmentation fault
I expected it would print "5" in the source code

A:
Error: Segmentation fault
I expected it would print "5" in the source code

It is because you have only allocated a pointer to your struct and this pointer is not referencing a valid memory location. It invokes Undefined Behaviour (UB). You need to allocate the space for the structure itself.
int main(int argc, char *argv)
{
    mystruct **data;
    data = malloc(sizeof(*data));
    *data = malloc(sizeof(**data));
    int c = 5;
    printf("%p %p", (void *)data, (void *)*data);
    (*data)->member = &c;
    printf("Member: %d", *((*data)->member));  //or*data[0]->member))
}

*

*void main(.... is invalid

*do not cast the result of malloc. If it does not compile - you use C++ compiler to compile C code which is wrong

*use objects instead of types in sizeof

*you have to use %p format to print pointers. Pointers have to be converted to void *

A: In this statement
data = (mystruct**)malloc(sizeof(mystruct*));

you allocated memory for one pointer of the type mystruct *. That is uninitialized.
Thus dereferencing this uninitialized pointer obtained by the expression *data
(*data)->member = &c

invokes undefined behavior.
At least you should write
data = (mystruct**)malloc(sizeof(mystruct*));
*data = malloc( sizeof( mystruct ) );

That is you need to allocate memory for an object of the type mystruct the data member member of which will be assigned.
Also pay attention to that using the conversion specifier %x to output a pointer
printf("%x", data);

also invokes undefined behavior. Instead you need to write
printf("%p\n", ( void * )data);

Or you could include header <inttypes.h> and write
#include <inttypes.h>

//...

printf("%" PRIxPTR "\n", ( uintptr_t )data);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Prevent body's onclick function inside div?

How do I prevent clicks inside of the div from carrying out the body's onclick function?

A: Try substituting

A: If you only need to support modern browsers (>=IE11), use pointer-events:
div { pointer-events: none; }

Note that this will also inhibit all kinds of mouse-related effects, including hover.


text:
Q: Replace a word in a string if it belongs to a list of words in pandas I have a pandas dataframe with a column sent, which contains strings. Now if the string contains a word from a given list, it needs to be replaced with a new word, say "new_word". But I am not sureee how eexactly this can be done without iterating through the rows in the Dataframe. Is there an efficient method to do so.
For finding a word in a sstring, where the word belongs to a lissst can be achieved by:
wordList = ["word1","word2","word3","word4"]
filtStr = "\s"+"\s|\s".join(wordList)+"\s"
print(list(df[df["sent"].str.lower().str.contains(filtStr)].index))

Similarly, word replacement can. be done if all I need to search for is a single word
print(list(df[df["sent"].str.lower().str.replace("word1","new_word")))

But I am not usree how exactly the word repalcement can be done, if it is a list of words, withoutiterating through the rows.

A: Another way of doing this using regular expression is:
import pandas as pd

test_df = pd.DataFrame(columns=["sent"], index=["x", "y", "z", "p"])
test_df.loc['x', 'sent'] = "I'm a superman; word1"
test_df.loc['y', 'sent'] = "I'm a superwoman; word2"
test_df.loc['z', 'sent'] = "I'm a spiderman; word3"
test_df.loc['p', 'sent'] = "I'm a batman; noword"
print(test_df)

wordList = ["word1","word2","word3","word4"]
regx = r'({})'.format('|'.join(wordList))
test_df['sent'] = test_df['sent'].str.replace(regx, "new_word").fillna(test_df['sent'])

A: Apparently, replace works similar to contains.
The solution is
wordList = ["word1","word2","word3","word4"]
filtStr = "\s"+"\s|\s".join(wordList)+"\s"
print(list(df[df["sent"].str.lower().str.replace(filtStr,"new_word")))


text:
Q: Xcode keyboard shortcuts for go to class from xib and from xib to class? Is there a keyboard shortcut for jumping from the current xib file to it's class (ViewController)?  And back from it's class to it's xib file again?
I use ctrl-command-up/down all the time to to jump between header and source, be great to have one for the view xib also.

A: There are a couple of quick ways to get to the XIB associated with a class.
CTRL-5-↓-enter
This will open the jump bar to the current file. Assuming your XIB is named the same as your class -- which is usually good practice to do -- the matching XIB will be the next item in the list if you are in your implementation file, or two down if you are in your header file.

Alternately, you can open the XIB or StoryBoard associated with the file with one mouse-click if you have an IBOutlet.
See the outlet indicator next to the IBOutlet?

Click on it!

For additional Xcode shorcuts, a great resource is this PDF maintained in github:
http://cloud.github.com/downloads/Machx/Xcode-Keyboard-Shortcuts/Xcode_Shortcuts.pdf

A: I don't know if there's a keyboard shortcut for jumping from xib to corresponding class header file. But you can do that easily with a few mouse clicks:

*

*Select a UI object in storyboard

*Select "Identity inspector" in Utility Panel (3rd tab from left)

*Click right-pointed arrow in the class name text field on top, which will take you to the header file

*You can always go back and forth with two-finger swipe in Editor panel

A: Most shortcuts can be seen here:
http://cocoasamurai.blogspot.com/2011/03/xcode-4-keyboard-shortcuts-now.html
And although that would be an awesome one, don't think it exists.


text:
Q: JTabbedPane tabs Alright, so I have a JTabbedPane in an application and it has several panels. Is it possible to assign a JPopupMenu to the actual tabs themselves instead of the JPanel? If it is possible, how would I do this?

A: See
http://www.java-forums.org/awt-swing/20810-how-can-i-add-popup-menu-tab-tabbedpane.html
for an example.
I think you would first call setTabComponentAt([each index], [a label with a popup attached])
then you would need to add a method in to change each of the tabs when they are clicked.


text:
Q: When executing configure-ng.py for PyQt4 get "Qt qmake not in path" I have already loaded SIP and I think I installed it correctly.  Then downloaded PyQt4 and when I try to execute the Configure-ng.py get the error that the qmake file is not in the path of my Python36-32 directory.  Where is the qmake file or executable so that I can move the file to the path and run configure-ng.py?

A: On Windows "make" is "nmake" instead, and you have to have a Visual Studio and open a cmd from the visual studio to use nmake.
Check out this webpage for nmake information: https://msdn.microsoft.com/en-us/library/dd9y37ha.aspx
I recently had this problem, and solved SIP installation following these steps. However I still could not run the configure.py for PyQt4 due to "Qt qmake not in path" error. I don't know why... I did have Qt installed, and the path was included in the system configuration...


text:
Q: jQuery $.post needs JSON response parsed manually all of a sudden I'm calling to the server using jQuery's $.post method and assigning the JSON response to a variable called result. The response is an array in PHP's json_encode() function.
Up until now I've always just used the properties of result directly, as the JSON gets parsed into an object automatically. But now, after some debugging, I've found that my code only works when I use JSON.parse(result) first.
What could've caused this sudden change?
Solution: Adding header("Content-Type: application/json") serverside when echoing a JSON encoded response.

A: Either:

*

*Your server stopped setting the correct Content-Type response header (application/json). PHP will claim anything it sends to the browser is text/html unless you use the header() function to override that.

*You didn't say type: 'json' to make jQuery (a) set an Accept header and (more relevantly) (b) ignore the response's Content-Type header and try to parse it as JSON regardless.


text:
Q: how to do other jquery thing after some jquery ajax I am using PHP. I want finish the jQuery AJAX process, (finish process and after data back to the main page) .
Then do the next jQuery thing. Any ideas on how to do it?
$.ajax({
  url: "page1.php",
  dataType: "html",
  type: 'POST',
  data: "value=" + value,
  success: function(data){
    //some process
  }
});//ajax1
$.ajax({
  url: "page2.php",
  dataType: "html",
  type: 'POST',
  data: "value=" + value,
  success: function(data){
    //some process
  }
});//ajax2
$.ajax({
  url: "page3.php",
  dataType: "html",
  type: 'POST',
  data: "value=" + value,
  success: function(data){
    //some process
  }
});//ajax3

// finish all the 3 ajax process, do the below code
$(".page").css('display','block');

A: If you have an arbitrary number of ajax operations, you can do something like this:
var arr = [];
arr.push($.ajax(...));
arr.push($.ajax(...));
/* put as many ajax operations as you want into arr */
$.when.apply(arr).then(function() { /* on success */ },
                       function() { /* on error */ });

This is my favorite technique for synchronizing multiple ajax calls.

A: If you are using jQuery 1.5 or better, you can use the heavenly $.when construct, which uses the $.Deferred concept first implemented in that version of jQuery.  You can run a function (or several functions) when all of several AJAX requests have completed.
So your code would look like this:
$.when($.ajax({
    url: "page1.php",
    dataType: "html",
    type: 'POST',
    data: "value=" + value,
    success: function (data) {
        //some process
    }
}), $.ajax({
    url: "page2.php",
    dataType: "html",
    type: 'POST',
    data: "value=" + value,
    success: function (data) {
        //some process
    }
}), $.ajax({
    url: "page3.php",
    dataType: "html",
    type: 'POST',
    data: "value=" + value,
    success: function (data) {
        //some process
    }
})).then(function () {

});

A: Just for the record so that the pre-jQuery-1.5 answer is here, too:
$.ajax({
  url: "page1.php",
  dataType: "html",
  type: 'POST',
  data: "value=" + value,
  success: function(data){
    $.ajax({
      url: "page2.php",
      dataType: "html",
      type: 'POST',
      data: "value=" + value,
      success: function(data){
        $.ajax({
          url: "page3.php",
          dataType: "html",
          type: 'POST',
          data: "value=" + value,
          success: function(data){
            // finish all the 3 ajax process, do the below code
            $(".page").css('display','block');
          }
        });//ajax3
      }
    });//ajax2
  }
});//ajax1

Hopefully, if nothing else this illustrates the value of the new jQuery 1.5 way of doing things :-)


text:
Q: Why is this definition of differential for manifolds correct? The book we are using in class is Frank Warner Foundation of Differential Manifold and Lie Group. Let $M,N$ be two smooth $d$-dim manifold, the differential of a $C^\infty$ function $\phi:M\rightarrow N$ is defined by
$$d\phi: M_m \rightarrow N_{\phi(m)}$$
For $v\in M_n$, and $g:N \rightarrow \mathbb{R}$ a smooth function, they define
$$d\phi(v)(g) = v(g\circ \phi).$$
I fail to see why $d\phi(v)\in N_{\phi(m)}$. Since for example $v(g\circ \phi)$ would be a function from M to $\mathbb{R}$ instead of from N to $\mathbb{R}$, which would mean $d\phi(v)\in M_{m}$.$$$$Any help on understanding why $$d\phi(v)\in N_{\phi(m)}$$

A: For $v\in M_m$, $g\in C^{\infty}(N)$ and $\phi:M\to N$ you have that $v(g\circ\phi)$ is already just a number in $\mathbb{R}$, so if you define $[d\phi(v)](g)=v(g\circ\phi)$, you can see $d\phi(v)$ is a map $C^{\infty}(N)\to\mathbb{R}$.


text:
Q: Issue with the alarm manager class. I'm setting the alarm but it is not triggered on that time I'm working on an app that will put phone on silent on a specific time and on ringer mode on a specific time. But when I set the time for the silent it is triggered in the next minute and ringer mode is triggered just after that silent mode trigger. Here is the code.
     long sdl = calendar.getTimeInMillis();// here calendar has the time on which it should trigger
    mgrAlarm[number]= (AlarmManager) this.getSystemService(ALARM_SERVICE);
    Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
    intent.putExtra("Id",id);
    final int _id = (int) System.currentTimeMillis();
    PendingIntent appIntent = PendingIntent.getBroadcast(getBaseContext(), id,intent, PendingIntent.FLAG_CANCEL_CURRENT);
    mgrAlarm[number].set(AlarmManager.RTC_WAKEUP, sdl, appIntent);

A: Yes! Use setExact(int, long, PendingIntent)Method Instead set method.
please attention to android developer documentation:

Note: Beginning with API 19 (KITKAT) alarm delivery is inexact: the OS
  will shift alarms in order to minimize wakeups and battery use. There
  are new APIs to support applications which need strict delivery
  guarantees; see setWindow(int, long, long, PendingIntent) and
  setExact(int, long, PendingIntent). Applications whose
  targetSdkVersion is earlier than API 19 will continue to see the
  previous behavior in which all alarms are delivered exactly when
  requested.

See  following link for more information: https://developer.android.com/reference/android/app/AlarmManager.html
Please Vote and mark this answer if it work!


text:
Q: How to get model values or class values of a kendo dropdown in js I have a kendo dropdown which have class or model
public class AttributeValue
{
    public int type1 { get; set; }
    public int type2 { get; set; }
    public int type3 { get; set; }
    public int type4 { get; set; }
}

i want to loop the datasource item how?


text:
Q: get minute bar historical data from Google finance? I can get daily data easily using this link:
https://www.google.com/finance/getprices?q=LHA&x=ETR&i=60&p=1d&f=d,c,h,l,o,v

But when I try to change "1d" to "1y" I still get 1 day's data.
I am trying to get 2 years' worth.
Is there a way to do this? yahoo or bing finance would be fine too.

A: You need to use '1Y', not '1y' on your query to get a time period stretching back 1 year. However, you will also need to change the granularity of your query, as minute data is only available for the previous 5 days.
This query will provide you with minute data for the previous 5 days.
https://www.google.com/finance/getprices?q=LHA&x=ETR&i=60&p=5d&f=d,c,h,l,o,v
The following query will provide you with the last two years of prices at the close.
https://www.google.com/finance/getprices?q=LHA&x=ETR&i=86400&p=2Y&f=d,c,h,l,o,v

A: google API "getprices" is NO more fetching intraday data of any interval (say 1 minute or 5 minute or 60 minutes .....). It is now fetching data in 1 day interval only irrespective of interval set.

A: I tried getting intraday data before, the furthest back I can get is 15 days, i.e. 15d
Using 2w or 1y did not work for me.
references:
http://www.mathworks.com/matlabcentral/fileexchange/32745-get-intraday-stock-price/content/getHistoricalIntraDayStockPrice.m
http://www.codeproject.com/Articles/221952/Simple-Csharp-DLL-to-download-data-from-Google-Fin

A: Update [2020]
Google and Yahoo deprecated their APIs so only direct website access works. However, the max resolution you can get is 1 day (end-of-day).
For historical high-resolution data Tickdata.com is a good source for tick-level data.
If 1-min bars are sufficient FirstRateData.com has 1-min data for most stocks and fx going back 20 years.


text:
Q: orderBy sum of related table If i have a post type post which hasMany votes that looks somehting like this:
post:   [id, title, content]
votes:  [my_vote, post_id, user_id]

where my_vote can be say -1, 0 or 1.
How do i list all posts ordered by the sum of my_vote? Can i do this in eloquent or do i have to use JOINS with fluent? Im looking to do something like
->orderBy(sum("votes-for-the-idea"))

Also i still need to access individual votes (specifically the votes of the current user).

A: select post.*,
sum(votes.my_vote) as vote_num,
count(distinct votes.user_id) as user_vote_num
from post
left join votes
on post.id = votes.post_id
group by post.id
order by vote_num desc


text:
Q: how to pass pointer to a method as another method argument All!
I have some class hierarchy
class A {public: virtual void foo(int, T*) = 0; virtual void foo1(int, T*) = 0;};
class B : public A {public: void foo(int, T*) override; void foo1(int, T*) override;};
class C : public B {public: void foo(int, T*) override; void foo1(int, T*) override;};

In client code
class D{void client_foo(A* pA, bool, T*);};
void D::client_foo(A* pA, bool b, T* pT)
{
    if (b) pA->foo(1050, pT);
    else pA->foo1(5010, pT);
}

I want to introduce new function void D::client_helper(???) which will achieve pA, int value, pT and pointer to method of class A to be called.
So, D::client_foo(...) could be rewritten as:
void D::client_foo(A* pA, bool b, T* pT)
{
    if (b) client_helper(pA, 1050, pT, std::mem_fn(&A::foo));
    else client_helper(pA, 5010, pT, std::mem_fn(&A::foo1));
}

the question is: what signature should D::client_helper() have?

A: Since both A::foo and A::foo1 have the same signature, there's no need for std::mem_fn, or another abstraction, just have client_helper take a plain pointer to member function of A.
void client_helper(A* pA, int i, T* pT, void(A::*memfn)(int, T*))
{
    (pA->*memfn)(i, pT);
}

And call it as
void client_foo(A* pA, bool b, T* pT)
{
    if (b) client_helper(pA, 1050, pT, &A::foo);
    else client_helper(pA, 5010, pT, &A::foo1);
}

Live demo

A: For passing functions as arguments, you have std::function.

A: I've used std::function<ret_type(arg_1)> and std::bind instead of std::mem_fn
e.g.
client function:
void client_helper(std::function<void (T*)> fnFoo, T* pT)
{
     nfFoo(pT);
}

call of the function:
usign namespace std::placeholders;
A* pA;
T* pT;
client_helper(std::bind(&A::foo, pA, 1050, _1), pT);


text:
Q: maximum and minimum number of tuples in natural join I came across a question that states
Consider the following relation schema pertaining to a students

*

*database: Student (rollno, name, address)

*Enroll (rollno, courseno, coursename)

where the primary keys are shown underlined. The number of tuples in the
    Student and Enroll tables are 120 and 8 respectively. What are the maximum
    and minimum number of tuples that can be present in (Student * Enroll),
    where '*' denotes natural join ?
I have seen several solutions on Internet like this  or this
As per my understanding. maximum tuples should be 8 and minimum should be 8 as well, since for each (rollnum,course) there should be a roll num in Students. Anyone who can help in this regard

A: I hope, you understood what Natural Join exactly is. You can review here.
If the tables R and S contains common attributes and value of that attribute in each tuple in both tables are same, then the natural join will result n*m tuples as it will return all combinations of tuples.
Consider following two tables
Table R (With attributes A and C)

 A  |  C
----+----
 1  |  2
 3  |  2
Table S (With attributes B and C)

 B  |  C
----+----
 4  |  2
 5  |  2
 6  |  2
Result of natural join R * S (If domain of attribute C in the two tables are same )

 A | B |  C
---+---+----
 1 | 4 |  2
 1 | 5 |  2
 1 | 6 |  2
 3 | 4 |  2
 3 | 5 |  2
 3 | 6 |  2
You can see both R and S contain the attribute C whose value is 2 in each and every tuple. Table R contains 2 tuples, Table S contains 3 tuples, where Result table contains 2*3=6 tuples.
Moreover, while performing a natural join, if there were no common attributes between the two relations, Natural join will behave as Cartesian Product. In that case, you'll obviously have m x n as maximum number of tuples.
Consider following two tables
Table R (With attributes A and B)

 A  |  B
----+----
 1  |  2
 3  |  2
Table S (With attributes C and D)

 C  |  D
----+----
 4  |  2
 5  |  2
Result of natural join R * S

 A | B |  C |  D
---+---+----+----
 1 | 2 |  4 |  2
 1 | 2 |  5 |  2
 3 | 2 |  4 |  2
 3 | 2 |  5 |  2
Hope this helps.

A: If there was a referential constraint in place ensuring that every rollno in Enroll must also appear in Student then your answer of 8 for both minimum and maximum would be correct. The question doesn't actually mention any such constraint however. There's no need to assume that the RI constraint exists just because the rollno attribute appears in both tables. So the best answer is 0 minimum and 8 maximum. If it's a multiple-choice question and 0,8 isn't one of the given answers then answer 8,8 instead - and tell your teacher that the question is unclear.

A: If you are asking about the maximum number of tuple that could appear in the natural join of R and S
the its the Cartesian product of both the tuples

A: Yes answer should be 8,8 .
Because Rollno is key in Student table  and rollno,courseno  are compound key .
Relationships between Student and enrol table is 1:M .
So maximum number of tuples is same as many side ie. 8
And minimum number of tuples is 8 if Foreign key exist other wise 0.
So answer is 8,8 .


text:
Q: How to use where condition in fetch URL in javascript? I am using third party api in their sdk they have given option to fetch data on the base of where condition like this
    Ordering.users.all({
            mode: 'dashboard',
            params: 'id,name,lastname',
            where: [
                {
                    attribute: 'level',
                    value: {
                        condition: '=',
                        value: 4,
                    }
                }
            ]
        },function (res) {
            if (!res.error) {
                $scope.drivers_filter = res.result
            } else MyAlert.show(res.result)
        })

in the console it seems like this
Request URL: https://apiv4.ordering.co/v400/es-419-1/devyv4/users?mode=dashboard&params=id,name,lastname&where=[{%22attribute%22:%22level%22,%22value%22:{%22condition%22:%22=%22,%22value%22:4}}]

but when i use this url in fetch() it doesn't work
fetch("https://apiv4.ordering.co/v400/en/devyv4/users&where[{%22attribute%22:%22level%22,%22value%22:{%22condition%22:%22=%22,%22value%22:4}}]", {
            method: "GET",
            headers: {
              "x-api-key": ""
            }
        }).then(r =>  r.json().then(data => (alert(JSON.stringify(data.result)))))

How i can use this in url ?

A: You need a ? after users to start the searchParams, atm you have a & not sure if you missed part of the URL or what.

A: Look closely at the URL you're passing. You need to define the start of your search string with ?
fetch("https://....co/v400/path?mode=dashboard&params=id,name,lastname&where...")


text:
Q: AWS CLI command works on Bash, but not with PHP shell_exec() I would like to trigger the following command:
aws route53 change-resource-record-sets --hosted-zone-id XXX
 --change-batch '{ "Comment": "2018-06-19-11:31", "Changes":
[ { "Action": "CREATE", "ResourceRecordSet": { "Name": "example.com",
"Type": "TXT", "TTL": 60, "ResourceRecords":
[ { "Value": "\"something\"" } ] } } ] }'

It works when I trigger it on bash, but not when I run it in PHP:
$json = trim(shell_exec($cmd_aws_submit));
// or:
$json = trim(shell_exec("{$cmd_aws_submit}"));

AWS expects, that the value ("\"something\"") for the TXT record is quoted. I tried to quote it like this:
$value = "\\\"" . $textvalue . "\\\"";
$value = "\"" . $textvalue . "\"";
$value = "\\'" . $textvalue . "\\'";
$value = "'" . $textvalue . "'";

None of it works, I always get the following error:

Error parsing parameter '--change-batch': Invalid JSON:
      Invalid \escape: line 12 column 23 (char 246) JSON received:
      { "Comment": "2018-06-19-11:54", "Changes": [ { "Action":
      "CREATE", "ResourceRecordSet": { "Name": "example.com",
      "Type": "TXT", "TTL": 60, "ResourceRecords":
      [ { "Value": "\"something\"" } ] } } ] }

With other aws UNQUOTED dns record values, PHP shell_exec() works perfectly.
If I trigger it on Bash, it works perfectly using "\"something\"" - why is it not working with PHP shell_exec()?

A: You should use the native escapeshellarg method to escape arguments you pass through to the command line. This will also protect you against argument injection attacks if you decide to include potentially unsafe data in your JSON string at some stage.
$json = '{ "Comment": "2018-06-19-11:31", "Changes":
[ { "Action": "CREATE", "ResourceRecordSet": { "Name": "example.com",
"Type": "TXT", "TTL": 60, "ResourceRecords":
[ { "Value": "\"something\"" } ] } } ] }';

$command = "aws route53 change-resource-record-sets --hosted-zone-id XXX
 --change-batch " . escapeshellarg($json);

$result = trim(shell_exec($command));

You could also choose to build up the JSON string as an array then use json_encode() to construct your string for you.


text:
Q: Relation between field of subsets, monotone class, $\lambda$ and $\pi$ systems
*

*For a field of subsets, the monotone class generated by the field is
the same as the $\sigma$ algebra generated by the field.

*Since a class of subsets is both a monotone class and a field of
subsets if and only if it is a $\sigma$ algebra, it follows that,
for a class of subsets, taking monotone class "closure" doesn't
change being a field.

*Any $\lambda$ system containing the $\pi$ system contains the $\sigma$ algebra generated by the $\pi$ system. (Dynkin's π-λ Theorem)
Questions:

*

*Are the statements true when switching "filed of subsets" and
"monotone class"?
I.e.
For a monotone class, is the field generated by the monotone class
same as the $\sigma$ algebra generated by the monotone class?
For a class of subsets, does taking monotone class "closure" change being a field?
For a monotone class, does any field containing the monotone class contains the $\sigma$ algebra generated by the monotone class? (Analogous to Dynkin's $π-λ$ Theorem)

*Are the statements true when replacing "filed of subsets" with
"$\lambda$ system" and "monotone class" with "$\pi$ system"?
I.e.
For a $\pi$ system, is the $\lambda$ system generated by the $\pi$
system same as the $\sigma$ algebra generated by $\pi$ system?
For a class of subsets, does taking $\pi$ system "closure" change
being a $\lambda$ system?

*Are the statements true when switching "$\lambda$ system" and "$\pi$
system" in the previous part?
I.e.
For a $\lambda$ system, is the $\pi$ system generated by the
$\lambda$ system same as the $\sigma$ algebra generated by $\lambda$
system?
For a class of subsets, does taking $\lambda$ system "closure"
change being a $\pi$ system?
For a $\lambda$ system, does any $\pi$ system containing the $\lambda$ system contains the $\sigma$ algebra generated by the $\lambda$ system? (Analogous to Dynkin's $π-λ$ Theorem)
Thanks and regards!

A: The following example will be useful:
Let $P$ be a countably infinite set of vectors in $\mathbb{R}^2_+$ with norm $1$. The family $$\{\mathbb{R}^2,\emptyset\}\cup\big\{\{x\in\mathbb{R}^2\}:px\geq 0:p\in P\}\big\}\cup\big\{\{x\in\mathbb{R}^2\}:px< 0:p\in P\}\big\}$$ is both a countably infinite $\lambda$-system and monotone class on $\mathbb{R}^2$.

*

*Take some countably infinite monotone class. The field generated by a countably infinity family is countably infinite, but no $\sigma$-algebra is countably infinite. The field generated thus also contains the monotone class but not the $\sigma$-algebra generated.  Since the monotone class generated by a field is a $\sigma$-algebra, it is trivially a field.

*Your first question is directly answered by the $\pi-\lambda$-Theorem of Dynkin. For the second, take a countably infinite $\lambda$-system. The $\pi$-system generated by $\lambda$ is countably infinite too. If it were still a $\lambda$-system, it would be a $\sigma$-algebra.

*Your first and third question can again be answered by a countability argument, the second by the $\pi-\lambda$-Theorem of Dynkin.


text:
Q: Why does the angular expression in the directive template execute twice? Its a simple directive:
app.directive('ngFoo', function($parse){

  var controller = ['$scope', function ngNestCtrl($scope) {

    $scope.getCanShow = function() {
      console.log('show');
      return true;
    };

  }];

  var fnPostLink = function(scope, element, attrs) {
    console.log('postlink');
  };

  var fnPreLink = function(scope, element, attrs) {
    console.log('prelink');
  };

  var api = {
    template: '
foo
',
    link: {
      post: fnPostLink,
      pre: fnPreLink
    },
    restrict: 'E',
    controller:controller
  };

  return api;

});

My goal was to find when "show" gets output to console. At this moment I figure it happens after linking (pre & post).
This makes sense. Since the template is rendered after those phases. (Correct me if I am wrong).
But then again, why would the template be rendered twice?
http://plnkr.co/edit/JNhON2lY9El00dzdL39J?p=preview

A: Angular has multiple digest cycles and you're seeing two of them. This is totally normal and perfectly ok.


text:
Q: Joomla plugin to override table prefix Overview:
I have a single Joomla website that have various copies of the database tables all in the same database, but with different table prefixes.
Depending on which user is accessing the site, i need to alter which joomla table prefix is used in order to display the relevant tables.
This has to be site wide.
Problem:
with a core code hack i can alter the prefix as needed, but would prefer this as a plugin.
With the plugin i can get the prefix, using $db->getPrefix(), and i can set an immediate instance of the connection using $db = JDatabaseDriver::getInstance( $option ). But this is not site wide and is overwritten by the standard $db = JFactory::getDbo().
So i need a system plugin that will repalce every instance of a table prefix as it is run.
Any ideas?

A: Sorry but if you install a new component or module you have many problem to synchronize this changes on all DB. I think the best for you is to redirect each user to his real site (many joomla file with many db).
Otherwise you can create a personal component and read table prefix of that user and display only date that you want, in this way just duplicate the tables you need and not all the joomla structure.


text:
Q: java.lang.NullPointerException - selenium java testng yesterday my test works ok, bust i want to use testng and then appeared a problem.
My main class leadTest:
public class leadTest {
    WebDriver driver;
  @Test
  public void f() {

 ..
...
...
            /*------------------------Go to leads page-------------------------------*/
        LeadsPage ldsP = new LeadsPage(driver);

        dbp.gotoLeadsPage();

        ldsP.findLeadByName("nameToFind");

    }

  @BeforeClass
  public void beforeClass() {
        driver = new FirefoxDriver();
        driver.get("http://getbase.com");
        driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
  }

and my class LeadsPage:
public class LeadsPage {
    WebDriver driver;
String expStatus = "new";

@FindBy(id="leads-new")
WebElement addLead;

@FindBy(className = "lead-status")
WebElement UserStatus;

public void addNewLead(){
    addLead.click();
}

public void checkUsrStat(){
    String stat = UserStatus.getText().toLowerCase();
    Assert.assertEquals(stat, expStatus.toLowerCase());

}

public void findLeadByName(String leadName){

    driver.findElement(By.partialLinkText(leadName)).click();
}

public LeadsPage(WebDriver driver){
        PageFactory.initElements(driver, this);

}

I have problem with this part from above:
public void findLeadByName(String leadName){

    driver.findElement(By.partialLinkText(leadName)).click();
}

I have error
    AILED: f
java.lang.NullPointerException
    at leadTest.LeadsPage.findLeadByName(LeadsPage.java:38)
    at leadTest.leadTest.f(leadTest.java:101)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:84)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:714)
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:901)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1231)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:127)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111)
    at org.testng.TestRunner.privateRun(TestRunner.java:767)
    at org.testng.TestRunner.run(TestRunner.java:617)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:334)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:329)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:291)
    at org.testng.SuiteRunner.run(SuiteRunner.java:240)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1224)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1149)
    at org.testng.TestNG.run(TestNG.java:1057)
    at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:111)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:204)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:175)

When i use
@FindBy(partialLinkText="nameToFind")
WebElement ntf;

and
ntf.click();

its works, but i cant do that, becouse in place nameToFind will be variable.
And i dont know what is wrong... Please help me

A: Driver variable not initialized: you try to call findElement() method on a null object.
One way to confirm that is to print the driver value:
System.out.println("driver=" + driver); just before the exception is thrown
public void findLeadByName(String leadName){

System.out.println("driver=" + driver);
    driver.findElement(By.partialLinkText(leadName)).click();
}

also i am noticing ,
LeadsPage ldsP = new LeadsPage(driver);

        dbp.gotoLeadsPage();

        ldsP.findLeadByName("nameToFind");

gotoLeadsPage(); and findLeadByName(); both functions are in same class LeadsPage but using different objects dbp and ldsp
May be below changes will work.
in LeadsPage class change your findLeadByName(); function as follows,
public void findLeadByName(WebDriver driver, String leadName){

    this.driver.findElement(By.partialLinkText(leadName)).click();
}

and in your class leadTest call function findLeadByName() as follows,
LeadsPage ldsP = new LeadsPage(driver);
ldsP.findLeadByName(driver ,"nameToFind");


text:
Q: How to save changes in a BackTrack virtual machine? Is there any way to save changes in a BackTrack virtual machine using VirtualBox?
I've tried every way, but on every next boot the settings
(changes like changing the background wallpaper or such) revert to the default.

A: Install backtrack to the VM - don't just use the Live CD option when starting.


text:
Q: Metadata information from kafka I am new to Confluent/Kafka and I want to find metadata information from kafka
I want to know

*

*list of producers

*list of topics

*schema information for topic

Confluent version is 5.0
What are classes (methods) that can give this information?
Are there any Rest API's for the same
Also is zookeeper connection necessary to get this information.

A: 1) I don't think that Kafka brokers are aware of producers that produce messages in topics and therefore there is no command line tool for listing them. However, an answer to this SO question suggests that you can list producers by viewing the MBeans over JMX.

2) In order to list the topics you need to run:
kafka-topics --zookeeper localhost:2181 --list

Otherwise, if you want to list the topics using a Java client, you can call listTopics() method of KafkaConsumer.
You can also fetch the list of topics through ZooKeeper
ZkClient zkClient = new ZkClient("zkHost:zkPort");
List<String> topics = JavaConversions.asJavaList(ZkUtils.getAllTopics(zkClient));

3) To get the schema information for a topic you can use Schema Registry API
In particular, you can fetch all subjects by calling:
GET /subjects HTTP/1.1
Host: schemaregistry.example.com
Accept: application/vnd.schemaregistry.v1+json, application/vnd.schemaregistry+json, application/json

which should give a response similar to the one below:
HTTP/1.1 200 OK
Content-Type: application/vnd.schemaregistry.v1+json

["subject1", "subject2"]

You can then get all the versions of a particular subject:
GET /subjects/subject-name/versions HTTP/1.1
Host: schemaregistry.example.com
Accept: application/vnd.schemaregistry.v1+json, application/vnd.schemaregistry+json, application/json

And finally, you can get a specific version of the schema registered under this subject
GET /subjects/subject_name/versions/1 HTTP/1.1
Host: schemaregistry.example.com
Accept: application/vnd.schemaregistry.v1+json, application/vnd.schemaregistry+json, application/json

Or just the latest registered schema:
GET /subjects/subject-name/versions/latest HTTP/1.1
Host: schemaregistry.example.com
Accept: application/vnd.schemaregistry.v1+json, application/vnd.schemaregistry+json, application/json

In order to perform such actions in Java, you can either prepare your own GET requests (see how to do it here) or use Confluent's Schema Registry Java Client. You can see the implementation and the available methods in their Github repo.

Regarding your question about Zookeeper, note that ZK is a requirement for Kafka.

Kafka uses ZooKeeper so you need to first start a ZooKeeper server if
  you don't already have one. You can use the convenience script
  packaged with kafka to get a quick-and-dirty single-node ZooKeeper
  instance.


text:
Q: Powershell Command for retrieving the second pattern values I am facing problem while using multiple patterns to retrieve the values from the second pattern.
The file contains data like below

Explore/CommonServices/AlertService.Folder
Explore/CommonServices/CIHLogger.Folder

What I am trying to do is find the text between two forward slashes i.e CommonServices and find the text between one forward slash and the dot i.e AlertService
I am able to find them using the patterns '/(.+)/' and '/([^/]+)\.' respectively. Now the challenge is how to get them into a single line
My Command is
((get-content "test2.txt") | Select-String -pattern '/(.+)/','/([^/]+)\.' -context 0,2 | foreach {"iics export --podHostName dm-us.informaticacloud
.com -r us -u xxxxxx -p xxxxxxxxx --artifacts " + $_ + " --zipFilePath `"C:\Users\breddy002\Documents\NJR\SVN\" + $_.Matches[0].Groups[1].Value + "\" +  $($_.Matches[1].Groups[1].value)
})

I am not sure how to get the second pattern output in the second output
Powershell version is : echo $PSVersionTable
Name                           Value
----                           -----
PSVersion                      5.1.17763.771

A: You could do something like the following:
switch -regex -file 'text2.txt' {
    '/(?<Slash>[^/]+)/(?<Dot>[^/\.]+)\.' {
        $Slash = $Matches.Slash
        $Dot = $Matches.Dot
        "First: {0}, Second: {1}" -f $Slash,$Dot
    }
}

Explanation:
The switch statement is a robust if statement. With the -regex and -file parameters, you can efficiently read in each line of a file and apply regex pattern matches. Each successful match is stored in the automatic variable $Matches.
The regex pattern /(?<Slash>[^/]+)/(?<Dot>[^/\.]+)\. matches as follows:

*

*/ is a literal match of /

*(?<Slash>[^/]+) matches one or more (+) characters that are not / ([^/]). That match is stored as capture group Slash (using syntax (?<Slash>)). It can later be accessed by using the syntax $Matches.Slash.

*(?<Dot>[^/\.]+) matches one or more characters that are not / and . ([^/\.]+). That match is stored as capture group Dot. It can later be accessed by using the syntax $Matches.Dot.

*\. is a literal . match, which requires escaping with backslash.


text:
Q: Unable to access my web2py app login page by running docker container using gae I am new to docker, I'm trying to run my web2py app using docker container in gae, my Dockerfile create the docker image, below is my dockerfile
FROM ubuntu:trusty
MAINTAINER john
#install python
RUN apt-get install -y -qq wget python unzip
#install GAE
RUN wget https://dl.google.com/dl/cloudsdk/channels/rapid/google-cloud-sdk.zip && unzip google-cloud-sdk.zip && rm google-cloud-sdk.zip
RUN google-cloud-sdk/install.sh --usage-reporting=true --path-update=true --bash-completion=true --rc-path=/.bashrc --additional-components app-engine-python
ENV PATH /google-cloud-sdk/bin:$PATH
WORKDIR Testapp
COPY Testapp .
RUN pwd
#Expose the ports
EXPOSE 8080
CMD ["dev_appserver.py", "--host=0.0.0.0", "."]

the above dockerfile is created the image and its running by using
$ docker run -it --rm -p 9090:9090 registry.local/python
INFO     2015-12-17 10:54:47,049 devappserver2.py:769] Skipping SDK update check.
WARNING  2015-12-17 10:54:47,248 simple_search_stub.py:1126] Could not read search indexes from /tmp/appengine.testapp.root/search_indexes

and I'm tried to access the my application using http://localhost:8080 but i got the This webpage is not available so i change the port number as 9090 and CMD ["dev_appserver.py", "--host=10.10.10.60", "."]
as per my ip r but i got the google.appengine.tools.devappserver2.wsgi_server.BindError: Unable to bind 10.10.10.60:8080 what is the issue here

A: It sounds like you're probably not binding the port to your host -- try running the container with -p 8080:8080 and then hitting http://localhost:8080 again (otherwise localhost:8080 won't be hitting your container).


text:
Q: How to display R data frame in generated PowerPoint ---
title: "Untitled"
output: powerpoint_presentation
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```

## Table

```{r table, echo=FALSE, message=FALSE, warning=FALSE}
library(tidyverse)
library(kableExtra)
mtcars %>%
  count(cyl) %>%
  ungroup()  # %>%
  # kable() %>%
  # kable_styling()
```

I'm working off the repro above. I'd like to present the mtcars calculated data frame in a kable or kableExtra fashion, like this:

Instead the table outputs in the following console format:
## # A tibble: 3 x 2
##     cyl     n
##   <dbl> <int>
## 1     4    11
## 2     6     7
## 3     8    14

How do I make my R PowerPoint tables pretty, and even better, editable in PowerPoint?

A: You can use flextable package. It's support powerpoint_presentation output with R Markdown. You will find below an example :
---
title: "Untitled"
output: powerpoint_presentation
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```

## Table

```{r table, echo=FALSE, message=FALSE, warning=FALSE}
library(magrittr)
library(flextable)
mtcars[1:5,1:4] %>%
  tibble::rownames_to_column() %>%
  flextable() %>%
  set_header_labels(rowname = "") %>%
  add_header_row(values = c("", "Group 1", "Group 2"),
                 colwidths = c(1, 2, 2)) %>%
  theme_zebra() %>% autofit()
```


text:
Q: Tabula does not detect some tables with pdfs built with the same software I´m trying to automate the sorting of my expenses in the report of the credit card that my bank provides.
I found tabula which worked like a miracle in many pdfs making it really easy to convert to csv and then process it as I want, with just two lines of code:
https://tabula-py.readthedocs.io/en/latest/tabula.html#high-level-interfaces
    from tabula import convert_into_by_batch

    convert_into_by_batch('movements', output_format='csv', pages='all')

But i´m having troubles because in some pdfs I do not obtain results at all and it does not look logical to me. Because:

*

*The pdfs apparently look the same. For obvious reasons I can not show the original file, but I can share two blurred screenshots where you can see that the files are almost identical. The one from february is detected perfectly by tabula but the other one is not:

*I don´t have access to how those pdfs are generated but I would guess that they always follow the same procedure. As this is not something that happens in new pdfs or old pdfs, just randomly in others in between.

Is there anything I can do to change how tabula detects the tables to make it more accuarate?

A: Well I give an answer to myself how I worked around the issue, although is not a clean solution and I still don´t understand why tabula fails randomly in some pdfs.
I changed the method of batch to process them one by one given the area parameter.
I used foxit reader to get approximately the pixels where the table is located, which lucky in my case is always the same:

And then I wrote the code like this:
from tabula import convert_into
import os
import re
import sys

directory=sys.argv[0]
output=sys.argv[1]
files = [f for f in os.listdir(directory) if re.match(r'.+\.pdf', f)]
for file in files:
    print(os.path.join(directory, file))
    convert_into(os.path.join(directory, file), output_path=os.path.join(output, file.replace(".pdf",".csv" )), pages='all', area=[[409,39,750,590]])

I still have to do some more testing but seems quiet robust for my scenario, although quiet ugly I would be open to see another solution which does not require this measuring system.


text:
Q: If $\int_\mathbb{R} |f_n| \le \frac{1}{n^2}$, then $f_n \to 0 \lambda$-a.e. Assume that $f_n : \mathbb{R}\to \mathbb{R}$ is a sequence of Lebesgue measurable functions such that $\int_\mathbb{R} |f_n|d\lambda \le \frac{1}{n^2}$.
Show that $f_n \to 0 \lambda$-a.e.
My attempt :
Choose $\delta>0$ and denote the set $E^\delta_n = \{x\in \mathbb{R} : |f_n|\ge \delta\}$
$$\frac{1}{n^2}\ge\int_\mathbb{R} |f_n|d\lambda \ge  \int _{E^\delta_n}|f_n|d\lambda \ge \delta \lambda\Big(\{x\in \mathbb{R} : |f_n|\ge \delta\}\Big)$$
taking limit as $n\to\infty$;
$$\lim_{n\to\infty}\lambda(E^\delta_n) =\lim_{n\to\infty}\lambda\Big(\{x\in \mathbb{R} : |f_n|\ge \delta\}\Big)=0$$
so $f_n \to 0 \lambda$-a.e

A: Another way, by Monotone Convergence Theorem or Tonelli:
\begin{align*}
\int_{\mathbb{R}}\sum_{n}|f_{n}|=\sum_{n}\int_{\mathbb{R}}|f_{n}|\leq\sum_{n}\dfrac{1}{n^{2}}<\infty,
\end{align*}
so for a.e. $x$,
\begin{align*}
\sum_{n}|f_{n}(x)|<\infty,
\end{align*}
and hence $f_{n}(x)\rightarrow 0$.

A: Another way, but somehow it is more complicated:
Let $S$ be the set defined by
\begin{align*}
S=\bigcap_{N}\bigcup_{m}\bigcap_{n\geq m}\left\{x\in\mathbb{R}:|f_{n}(x)|<\dfrac{1}{N}\right\}.
\end{align*}
This set collects those points $x$ such that $f_{n}(x)\rightarrow 0$. We are to show that $\lambda(S^{c})=0$, this means that $f_{n}(x)\rightarrow 0$ $\lambda$-a.e.
The set $S^{c}$ can be written as
\begin{align*}
S^{c}=\bigcup_{N}\bigcap_{m}\bigcup_{n\geq m}\left\{x\in\mathbb{R}:|f_{n}(x)|\geq\dfrac{1}{N}\right\}
\end{align*}
Fix $N$ and $m$, then for all $n\geq m$, we have
\begin{align*}
\dfrac{1}{N}\lambda\left(\left\{x\in\mathbb{R}:|f_{n}(x)|\geq\dfrac{1}{N}\right\}\right)\leq\int_{\mathbb{R}}|f_{n}|d\lambda\leq\dfrac{1}{n^{2}},
\end{align*}
so
\begin{align*}
\dfrac{1}{N}\lambda\left(\bigcup_{n\geq m}\left\{x\in\mathbb{R}:|f_{n}(x)|\geq\dfrac{1}{N}\right\}\right)\leq\dfrac{1}{N}\sum_{n\geq m}\lambda\left(\left\{x\in\mathbb{R}:|f_{n}(x)|\geq\dfrac{1}{N}\right\}\right)\leq\sum_{n\geq m}\dfrac{1}{n^{2}},
\end{align*}
and hence
\begin{align*}
\lambda\left(\bigcap_{m}\bigcup_{n\geq m}\left\{x\in\mathbb{R}:|f_{n}(x)|\geq\dfrac{1}{N}\right\}\right)\leq\lambda\left(\bigcup_{n\geq m}\left\{x\in\mathbb{R}:|f_{n}(x)|\geq\dfrac{1}{N}\right\}\right)\leq N\sum_{n\geq m}\dfrac{1}{n^{2}}.
\end{align*}
Since this is valid for all $m=1,2,...$ and we know that $\displaystyle\sum_{n\geq m}\dfrac{1}{n^{2}}\rightarrow 0$ as $m\rightarrow\infty$, it follows that
\begin{align*}
\lambda\left(\bigcap_{m}\bigcup_{n\geq m}\left\{x\in\mathbb{R}:|f_{n}(x)|\geq\dfrac{1}{N}\right\}\right)=0.
\end{align*}
Note that this is also valid for all $N=1,2,...$, it follows that
\begin{align*}
\lambda(S^{c})\leq\sum_{N}\lambda\left(\bigcap_{m}\bigcup_{n\geq m}\left\{x\in\mathbb{R}:|f_{n}(x)|\geq\dfrac{1}{N}\right\}\right)=0,
\end{align*}
we are done.


text:
Q: Finding nonzero elements in an array I'd like to form a piece of code that gives a print statement if there is a detection of a nonzero number in an array. The attempt I have is as follows:
if numpy.where(array != 0):
    print "NonZero element detected!"
elif numpy.where(array ==0):
    print "All elements are zero"

I also know of the numpy.nonzero command but I'd really like to get this if, else style of printed statements working and I'm not sure how to incorporate the python logic properly. I'm more interested in getting the logic working than I am finding zeroes. What I have seems to produced the "NonZero element detected!" statement regardless of whether or not there are non-zeroes in the array. Any there any ideas on how to implement this?

A: You can use the any built-in:

Return True if any element of the iterable is true. If the iterable is empty, return False.

if any(elt != 0 for elt in array):
    print("Non zero detected")
else:
    print("All elements are zero")

As a bonus, if the only elements that evaluates to False Boolean-wise is 0, you can simply do:
if any(array):
    print("Non zero detected")
else:
    print("All elements are zero")

A: You can create a mask using conditionals:
mask = array == 0
print(mask)
array([ True, False, False,  True], dtype=bool)

You can chain this with a .all or .any call, depending on your use case. If you want to check whether all elements are zero, you'd do:
if (array == 0).all():
    print('All elements are 0!')

Or,
if (array != 0).any():
    print('Non-zero elements detected!')

And so on.

You can do the same thing using np.mask as long as you provide two additional arguments:
mask = np.where(array == 0, True, False)
print(mask)
array([ True, False, False,  True], dtype=bool)

A: If you're looking purely for detection of non-zero element in array, why not doing something like this.. or am I missing something?
arr_1 = (1,2,4,6,7,88,9)
arr_2 = (1,2,4,6,0,7,88,9)

print if 0 in arr_1 'Non zero detected' else 'There is no zero in array'


text:
Q: 'ion-option' is not a known element I'm dabbling in Ionic for the first time, learning from the beginning using the components documentation, and I got stuck with this error:
    Template parse errors:
    'ion-option' is not a known element:
When using a select component in this way:
<ion-select [(ngModel)]="gaming">
 <ion-option value="nes">NES</ion-option>
</ion-select>

I have searched and found solutions like this: Ionic button showing 'ion-button' is not a known element
however, using something like <option ion-option value="nes">NES</option> doesn't work.
Even, I include the schemas: [CUSTOM_ELEMENTS_SCHEMA] line in my module, but no options are showed.
I'm using:
ionic (Ionic CLI) : 4.5.0
Ionic Framework   : @ionic/angular 4.0.0-beta.16

I'll be grateful if someone can help me.

A: I used below code and got it working.
Ionic 4
 <ion-item>
      <ion-select value="brown" ok-text="Okay" cancel-text="Dismiss">
      <ion-select-option value="brown">Brown</ion-select-option>
      <ion-select-option value="blonde">Blonde</ion-select-option>
      <ion-select-option value="black">Black</ion-select-option>
      <ion-select-option value="red">Red</ion-select-option>
    </ion-select>
</ion-item>

A: Use 'ion-option' instead of 'ion-select-option'.
<ion-item>
  <ion-label>Gender</ion-label>
  <ion-select [(ngModel)]="this.gender">
    <ion-option value="f">Female</ion-option>
    <ion-option value="m">Male</ion-option>
  </ion-select>
</ion-item>

It works for me as expected.
Thank You

A: <ion-item>
  <ion-label>Hair Color</ion-label>
  <ion-select value="brown" ok-text="Okay" cancel-text="Dismiss">
    <ion-select-option value="brown">Brown</ion-select-option>
    <ion-select-option value="blonde">Blonde</ion-select-option>
    <ion-select-option value="black">Black</ion-select-option>
    <ion-select-option value="red">Red</ion-select-option>
  </ion-select>
</ion-item>

ionic 4 has changed its syntax.

A: Remember to use as the documentation suggest, if you're new just follow the examples.
<ion-item>
  <ion-label>Gender</ion-label>
  <ion-select [(ngModel)]="gender">
    <ion-option value="f">Female</ion-option>
    <ion-option value="m">Male</ion-option>
  </ion-select>
</ion-item>

Also if you need modify or a complex behavior, the Api Docs is your best ally.

*

*API Select Ionic

https://ionicframework.com/docs/api/components/select/Select/


text:
Q: Are "Application Client Container" and "Embedded Enterprise Bean Container" the same? Is the "Application Client Container" (see here) the same as the "Embedded Enterprise Bean Container" (see here)?
The two descriptions sound like the same thing to me, but I was wondering whether I am missing something. Or why are two different terms used? How are these two terms related?

A: Though it's not immediately apparent, they're quite different.

*

*Application Client Container (ACC)

...The ACC manages the execution of Java EE application client components (application clients), which are used to access a variety of Java EE services...outside the Oracle GlassFish Server. ACC communicates with the GlassFish Server using RMI-IIOP

*Embedded Enterprise Bean Container

... The container and the client code are executed within the same virtual machine

The difference
ACC only enables connectivity between a client application (a consumer of Java EE components) in a remote JVM. That is, you'll have a Client A running in JVM A1, connecting to Glassfish Server, running in JVM B1. By itself, ACC doesn't have ability to support the goodies of JavaEE (EJBs, Security, Interceptors Transactions etc).
The EEC on the other hand is basically an API that will provide all that functionality within a single JVM. That is you can develop a small Java class with a main method and provide all those goodies within that single main method.
Have a look at the code sample from Oracle
    //Adding this line to a main method effectively puts a Java EE container within that JVM, without having to install anything
    EJBContainer ec = EJBContainer.createEJBContainer();

In summary, ACC - Connect to JavaEE container in a remote JVM, EEC, provide JavaEE container functionality within a local JVM


text:
Q: Detecting HTTP connection closure in Rails When using Nginx there are times then HTTP 499 is recorded in the error log when the client has prematurely closed their connection (for example, the connection timed out, the user reloaded their browser or pressed Stop or otherwise).
I understand that Nginx is able to detect this because they are the end which will receive the SIGPIPE signal indicating the socket has been closed, however I am wondering if it is possible to get this notice back to Rails at all?
Shopify recently used a very novel approach to detect this in Unicorn before sending the request on to Rails to be processed, however I would like to be able to detect this within the Rails app, such as during a long-running transaction.

A: After Rails's dispatcher had already started processing the request - there is no connection to the http client anymore, only when the processing is done - the response is headed back to the client.
So basically, there is no way you can tell if the client (e.g: browser) had shutdown the connection while you are already processing it.


text:
Q: Convert stream to object? Newbie question for you. I have the following code. I get an error because a object has to be passed to ClientRequest. But am unsure how pass the stream as a object.

TcpClient _client = _listener.AcceptTcpClient();
NetworkStream _clientStream = _client.GetStream();
ThreadPool.QueueUserWorkItem(ClientRequest, _clientStream);

Thanks

A: There's nothing wrong with that code as long as ClientRequest is declared like so:
public void ClientRequest(Object state) {
 ...
}

A: The problem is probably not that you can't pass the stream as an object -- Everything in .net is an object, so casting to object (which is a "widening" conversion, and thus doesn't need to be specified) shouldn't be an issue.
My guess is your ClientRequest is expecting to be passed a NetworkStream or something, which it's not going to get -- it's going to get an object, which you'll then need to cast to a NetworkStream in order to use it properly.


text:
Q: Django - How to filter dropdown based on user id? I'm not sure how to filter dropdown based on user id.
Not I want for user id 2.

I want exactly like this for user id 2.

Model
@python_2_unicode_compatible  # only if you need to support Python 2
class PredefinedMessage(models.Model):
    user = models.ForeignKey(User)
    list_name = models.CharField(max_length=50)
    list_description = models.CharField(max_length=50)

    def __str__(self):
        return self.list_name

class PredefinedMessageDetail(models.Model):
    predefined_message_detail = models.ForeignKey(PredefinedMessage)
    message = models.CharField(max_length=5000)

View
class PredefinedMessageDetailForm(ModelForm):
    class Meta:
        model = PredefinedMessageDetail
        fields = ['predefined_message_detail', 'message']
        exclude = ('user',)

def predefined_message_detail_update(request, pk, template_name='predefined-message/predefined_message_detail_form.html'):
    if not request.user.is_authenticated():
        return redirect('home')
    predefined_message_detail = get_object_or_404(PredefinedMessageDetail, pk=pk)
    form = PredefinedMessageDetailForm(request.POST or None, instance=predefined_message_detail)
    if form.is_valid():
        form.save()
        return redirect('predefined_message_list')
    return render(request, template_name, {'form':form})

html file
{% extends "base.html" %}
{% load i18n %}

{% block content %}
<form method="post">{% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Submit" />
</form>
{% endblock %}

A: You can do it in view itself using
form = PredefinedMessageDetailForm(request.POST or None, instance=predefined_message_detail)
form.fields["predefined_message_detail"].queryset= PredefinedMessage.objects.filter(user=request.user)

But filtering happens based on request.user so it should be logged in.Consider that also. Hope this helps


text:
Q: VBA to Count the value in column and fill the table in another sheet I am having two Sheets , sheet1 and sheet2.
I have a table with the weekno, delay , Ok, percenatage of Delay and Percentage of OK.
In sheet 1, i am looking for the column T, and Count the number of '1' in the column. Similarly i look for column U and Count the number of '0' in the column.
the Count value has to be filled in sheet2 of the table looking into the week. I have my week in the column AX of sheet1.
I used formula like Countif for calculating the number of 1 in both the column.
could someone guide me how we can do it in VBA, to Count the value in column and pasting the result in a table in another sheet.I am struck how to start with coding. This is my sheet1, i have to Count the number of 1 in column t and u

A: To solve this problem, we have to use a couple of loops.  First, we have to do an outer loop to go through the week numbers in sheet2, then imbedded in that loop we have to look at each row in sheet1 to see if it matches the week from sheet2 and to see if column T = 1 and if column U = 0.  The code creates a counter that increase T by one every time a row in T is equal to 1 and does the same for U every time a row in U = 0.
Sub test()
Dim col As Range
Dim row As Range
Dim sh1 As Worksheet
Dim sh2 As Worksheet
Dim T As Integer
Dim U As Integer
Dim wk As String

Set sh1 = Sheets("Sheet1")
Set sh2 = Sheets("Sheet2")

For Each col In sh2.Columns 'This loops through all populated columns in row one
    If sh2.Cells(1, col.Column).Value = "" Then
        Exit For
    End If

    wk = sh2.Cells(1, col.Column).Value

    For Each rw In sh1.Rows
        If sh1.Cells(rw.row, 50).Value = "" Then
            Exit For
        End If

        If sh1.Cells(rw.row, 50) = wk And sh1.Cells(rw.row, 20) = 1 Then
            T = T + 1
        End If

        If sh1.Cells(rw.row, 50) = wk And sh1.Cells(rw.row, 21) = 0 Then
            U = U + 1
        End If
    Next rw

sh2.Cells(2, col.Column) = T 'put counters into 2nd and 3rd row under each week, you can adjust this to put the number in a different cell.
sh2.Cells(3, col.Column) = U

T = 0 'reset counters to start looking at next week.
U = 0

Next col

End Sub

For some reason I wasn't able to view the images that you just uploaded.  You may have to adjust my code to adapt to the specifics of your excel file.  It will be good VBA practice for you.  My code assumes the sheet2 has the week numbers going across the columns without any blank cells in between them.  The vba drops the code in the 2nd and 3rd row under the corresponding week number.  You can change this by changing the code that is indicated in the comments.


text:
Q: How do i read data from my inputreader.read()? public static boolean sendRequest(String request) {
    InputStream inputStream = null;
    try {
        URL url = new URL(request);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setReadTimeout(TIMEOUT);
        connection.setConnectTimeout(TIMEOUT);
        connection.setRequestMethod("POST");
        connection.connect();
        inputStream = connection.getInputStream();
        while (inputStream.read() != -1);
        return true;
    } catch (IOException error) {
        return false;
    } finally {
        try {
            if (inputStream != null) {
                inputStream.close();
            }
        } catch (IOException secondError) {
            Log.w(RequestManager.class.getSimpleName(), secondError);
        }
    }
}

how do i read data from inputreader.read()? i want to read the data that is sent back from a server

A: This might be useful.
import java.net.*;
import java.io.*;

public class URLConnectionReader {
    public static void main(String[] args) throws Exception {
        URL oracle = new URL("http://www.oracle.com/");
        URLConnection yc = oracle.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(
                                yc.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null)
            System.out.println(inputLine);
        in.close();
   }
}

For reference you can lookup from link https://docs.oracle.com/javase/tutorial/networking/urls/readingWriting.html.

A: int iReadSize;
byte[] buffer = new byte[4096];

try (InputStream inputStream = connection.getInputStream();) {
    while ((iReadSize = inputStream.read(buffer)) != -1) {
        System.out.println(new String(buffer, 0, iReadSize));
    }
} catch (IOException error) {
}


text:
Q: Remove double quotes around space and null on a output tsv file from copyMerge on Scala Spark When I am merging part files via FileUtil.copyMerge function from a Dataframe created from an HQL I am getting "" around spaces and nulls on my final text file on HDFS. Here is what I am doing.
import org.apache.hadoop.fs._
import org.apache.spark.sql._
import org.apache.hadoop.conf.Configuration

val dir = "your/output/folder"

val selectedData= hiveContext.sql(executeHQL)

// Pick the header
val selectedDataHeader = selectedData.limit(0)

// write header to a file for merging
selectedDataHeader.write
  .format("csv")
  .option("header", "true").option("delimiter", "\t")
  .save(dir + "/header")

// create the part files
selectedData.write
  .format("csv")
  .option("header", "false").option("delimiter", "\t")
  .save(dir + "/parts")

val configuration = new Configuration()
val fs = FileSystem.get(configuration)

// merge header and all part files to one
FileUtil.copyMerge(
  fs, new Path(dir +  "/header"),
  fs, new Path(dir  +"/parts/header"),
  false, configuration, "")

// Write extracts to file
FileUtil.copyMerge(
  fs, new Path(dir + "/parts/"),
  fs, new Path(dir + "/destination.txt"),
  false, configuration, null)

So problem is on /destination.txt it looks like below
""    ABC  XYZ PQR  ""  XYZ2
ROW2  ABC2 XYZ PQR2 ""  XYZ3

How do I remove the "" around spaces or null values? Note the part files do not show the "" though.


text:
Q: getting force closes when integrating with proguard? I am using  three libraries in my app
    AndroidsupportV4.
    Picasso
    ActionBarSherlock

in project properties i added this
  proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt

       # Project target.
  target=android-18
android.library=false
android.library.reference.1=../JakeWharton-

ActionBarSherlock-e5c2d1c/library
in proguard-project.txt i added this
       -dontwarn com.squareup.picasso.**

My log cat
09-11 12:25:06.695: E/AndroidRuntime(26629): FATAL EXCEPTION: main
09-11 12:25:06.695: E/AndroidRuntime(26629): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.phoneix.allu/com.phoneix.allu.HomeActivity}: java.lang.RuntimeException: java.lang.NoSuchMethodException: <init> [class android.app.Activity, int]
09-11 12:25:06.695: E/AndroidRuntime(26629):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1967)
09-11 12:25:06.695: E/AndroidRuntime(26629):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1992)
09-11 12:25:06.695: E/AndroidRuntime(26629):    at android.app.ActivityThread.access$600(ActivityThread.java:127)
09-11 12:25:06.695: E/AndroidRuntime(26629):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1158)
09-11 12:25:06.695: E/AndroidRuntime(26629):    at android.os.Handler.dispatchMessage(Handler.java:99)
09-11 12:25:06.695: E/AndroidRuntime(26629):    at android.os.Looper.loop(Looper.java:137)
09-11 12:25:06.695: E/AndroidRuntime(26629):    at android.app.ActivityThread.main(ActivityThread.java:4441)
09-11 12:25:06.695: E/AndroidRuntime(26629):    at java.lang.reflect.Method.invokeNative(Native Method)
09-11 12:25:06.695: E/AndroidRuntime(26629):    at java.lang.reflect.Method.invoke(Method.java:511)
09-11 12:25:06.695: E/AndroidRuntime(26629):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
09-11 12:25:06.695: E/AndroidRuntime(26629):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
09-11 12:25:06.695: E/AndroidRuntime(26629):    at dalvik.system.NativeStart.main(Native Method)
09-11 12:25:06.695: E/AndroidRuntime(26629): Caused by: java.lang.RuntimeException: java.lang.NoSuchMethodException: <init> [class android.app.Activity, int]
09-11 12:25:06.695: E/AndroidRuntime(26629):    at com.actionbarsherlock.a.a(Unknown Source)
09-11 12:25:06.695: E/AndroidRuntime(26629):    at com.actionbarsherlock.a.f.a(Unknown Source)
09-11 12:25:06.695: E/AndroidRuntime(26629):    at com.actionbarsherlock.a.f.setContentView(Unknown Source)
09-11 12:25:06.695: E/AndroidRuntime(26629):    at com.phoneix.allu.HomeActivity.onCreate(Unknown Source)
09-11 12:25:06.695: E/AndroidRuntime(26629):    at android.app.Activity.performCreate(Activity.java:4465)
09-11 12:25:06.695: E/AndroidRuntime(26629):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
09-11 12:25:06.695: E/AndroidRuntime(26629):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1931)
09-11 12:25:06.695: E/AndroidRuntime(26629):    ... 11 more
09-11 12:25:06.695: E/AndroidRuntime(26629): Caused by: java.lang.NoSuchMethodException: <init> [class android.app.Activity, int]
09-11 12:25:06.695: E/AndroidRuntime(26629):    at java.lang.Class.getConstructorOrMethod(Class.java:460)
09-11 12:25:06.695: E/AndroidRuntime(26629):    at java.lang.Class.getConstructor(Class.java:431)
09-11 12:25:06.695: E/AndroidRuntime(26629):    ... 18 more

A: Also add the following to your proguard-android.txt file:
-keep class com.actionbarsherlock.** {*;}


text:
Q: Grails: Why doesn't session correctly save my list of maps? I have list that I push params wnen certain pages are visited. However some items of the list don't have action and controller keys. Why isn't session keeping my data with full integrity?
I'm doing things like session.setAttribute('my.key', [params])

A: Do this before saving the params object to explicitly force action & controller into the params object:
params.action = actionName
params.controller = controllerName


text:
Q: Equivalence between two definitions of left-invariant vector fields I have the following definition in my notes
If $M$ is a manifold, we denote by $\mathscr{V}(M)$ the real linear space of smooth vector fields on $M$: A vector field $v \in  \mathscr{V}(G)$ is called left invariant, if
$T(l_x)v\equiv(l_x)_*v=v$, for all $x\in G$ ; or, equivalently if
$v(xy)=  T_y(l_x) v(y) ,x,y \in G$...(2)
where $T(\phi)\equiv\phi_*$ is the diferential
Can someone  exlain why is (2)  equivalent to the initial definition?
If I try  to prove it I arrive to another expresion. I have that
$T(l_x)v\equiv(l_x)_*v=v$, for all $x\in G$
If I evaluate both sides of the equality (which are vector fields) in a point $y\in G$, I get
$(T(l_x)v)(y)=v(y)$
$T_y(l_x)v(y)=v(y)$
instead of
$T_y(l_x)v(y)=v(xy)$
Why is this not correct and how do I get (2)?


text:
Q: Setting different app icons depends upon the configurations in iOS I want to set different app icons depends upon the configurations like Debug, Release in iOS.
Any help would be much appreciated.
Thanks!

A: Finally got the answer from below question.
Look this: How can I configure my iPhone project to use a seperate application icon for beta releases
Thanks


text:
Q: HttpContext.Current.Request.Files.Count returning null every time. I want to upload a file to a folder in the server
This is the request payload I get.
 fileChange(event) {
debugger;
let fileList: FileList = event.target.files;
if (fileList.length > 0) {
  let file: File = fileList[0];
  let formData: FormData = new FormData();
  formData.append('uploadFile', file, file.name);
  let httpHeaders = new HttpHeaders()
  .set('Authorization', 'Bearer ' + this.access_token)
  .set('Content-Type', 'multipart/form-data');

  let endpoint = "Online/UploadImage";
  this.httpClient
  .post(this.host + endpoint, formData, { headers: httpHeaders, responseType: 'json' })
  .subscribe(data => {
        // do something, if upload success
        console.log(data);
        }, error => {
          console.log(error);
        });
}

}
Above is my ts file in Angular
                        <input type="file" (change)="httpService.fileChange($event)" name="uploadFile"/>

Above is my HTML file
 [HttpPost]
    [Route("api/Online/UploadImage")]
    public string UploadFile()
    {
        var file = HttpContext.Current.Request.Files.Count > 0 ?
            HttpContext.Current.Request.Files[0] : null;

        if (file != null && file.ContentLength > 0)
        {
            var fileName = Path.GetFileName(file.FileName);

            var path = Path.Combine(
                HttpContext.Current.Server.MapPath("~/Resources/Images/"),
                fileName
            );

            file.SaveAs(path);
        }

        return file != null ? "~/Resources/Images/" + file.FileName : null;
    }

And here is my web API in ASP.Net.
I'm really stuck as to why the current request is returning null? I can see that the front-end seems to be working okay.. But really I'm quite confused as to how to upload a file to my server. Please recommend what I should do to achieve that.

A: fileChange(event) {
// debugger;
let fileList: FileList = event.target.files;
if (fileList.length > 0) {
  let file: File = fileList[0];
  let formData: FormData = new FormData();
  formData.append('uploadFile', file, file.name);
  let httpHeaders = new HttpHeaders()
  // .set('Authorization', 'Bearer ' + this.access_token)
  // .set('Content-Type', 'multipart/form-data');

  let endpoint = "Online/UploadImage";
  this.httpClient
  .post(this.host + endpoint, formData)
  .subscribe(data => {
        // do something, if upload success
        console.log(data);
        }, error => {
          console.log(error);
        });
}

I managed to figure it out thanks to jdweng pointing out the headers. All I did was comment them out and it seemed to give me the desired response. Hopefully, this helps someone.


text:
Q: Discord.js multi role check so ive been trying to find a better way to check multiple roles for commands on my discord bot so far the best i can do is }else{
run(message) {
    if(message.member.roles.find("name", "Pheonix")){

        return message.say('These are dark times. . .', {files: ["./resources/videos/darktimes.mp4"]});
    }else{
        if(message.member.roles.find("name", "Renowned Wizard")){
        return message.say('These are dark times. . .', {files: ["./resources/videos/darktimes.mp4"]});
    }else{

  return message.say('*Patreon restricted.*');

And i was wondering is there some way i could chuck this in an array and use whatever is in the array as a checker for roles is there any ways to go about this?
okay so i tried to add onto with an array but i cant get that to function
    var morsmordreRoles = [
        'Dev',
        'Renowned Wizard',
        'Pheonix',
        'Moderator'
    ]
    if(message.member.roles.find("name", morsemordreRoles)){

    return message.say('*You mark the sky with the presence of The Dark Lord* ', {files: ["./resources/gifs/morsmordre.gif"] });
}else{
    return message.say('*Death Eater restricted.*');
}

}
}

A: If you want to use an array, you can use a foreach and a bool check to check if the user has any of the roles in the array, also you should use .cache.some instead of find in discord.js v12 as seen here
Example:
var morsmordreRoles = [
        'Dev',
        'Renowned Wizard',
        'Pheonix',
        'Moderator'
    ]
    var hasRole = false;
    morsmordreRoles.forEach(findrole =>{
        if(message.member.roles.cache.some(role => role.name === findrole)) hasRole = true; //if user has role, sets bool to true
    })

    if(hasRole === true){
        //code when has role
    }
    else{
        //code when has no role
    }


text:
Q: Illegal mix of collations for operation 'concat' after replace chinese Before:
set extrainfo =concat('{"from":"carpool","table":"Block",
"key_field":"b_index","key_value:"',b_index,'","infoid":"',info_id,'",
"code":"0","message":"This trip is valid"}');

run success.
I replaced "This trip is valid" with "行程符合规范" :
set extrainfo =concat( '{"from":"carpool","table":"Block","key_field":
"b_index","key_value:"',b_index,'","infoid":"',info_id,'",
"code":"0","message":"行程符合规范"}');

show me:
(node:30849) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1):
`enter code here`Error: ER_CANT_AGGREGATE_NCOLLATIONS:
`enter code here`Illegal mix of collations for operation 'concat'

Can you help me?

A: I changed Codes:
set extrainfo =concat( '{"from":"carpool","table":"Block","key_field":
   "b_index","key_value:"',convert(b_index,char),'","infoid":"',convert(info_id,char),'",
"code":"0","message":"行程符合规范"}');

replace b_index with convert(b_index,char). It works well.


text:
Q: Four dimension equivalent of a triangle and a tetrahedron, obtained *by translation*? If a straight line is given, and its copy is created and translated (for conveniently choosen amount), we get a square. If the analogous thing is done with a square, we get a cube. Further, we get a hypercube.
But what about triangle instead of square? What happens if we do same process starting from triangle? What are properties and names for such geometric bodies?
Clarification note: I am not talking about adding a vertex in higher dimension, but translating the whole body. In such scheme, a tetrahedron is not 3-dimensional extension of a triangle, for example.
The same question for a tetrahedron as a starting point.

A: The name for the $n$-dimensional analogue of triangles and tetrahedrons is a simplex.

A: Such objects are called $n$-simplices.
The so-called standard $n$-simplex $\Delta_n$ can be described as $\Delta_n = \{ x \in \Bbb R^{n+1}: x_0 + ... + x_n = 1, x_i \geq 0 \}$

A: In dimension $3$ your object is called a triangular prism.
Extended to $n$ dimensions, there is no special shorthand name. Instead, your object is best described as the Cartesian product of a triangle with a cube of dimension $n-2$.
And if you want to start with a tetrahedron in $3$ space and carry out your process extended to $n$ dimensions, then the resulting object is the Cartesian product of a tetrahedron with a cube of dimension $n-3$.


text:
Q: homogenous 2nd order ode with exponential in LHS I've come across a type of homogeneous 2nd order ode that I haven't seen before and isn't covered in the book I have. I've also tried googling it but haven't been able to find anything similar since I don't know the name for this type of problem. Any help in how to solve it would be much appreciated. Question is below.
Find general solutions with the replacement $x= e^t$ to the following differential equations, in each of which a function $y(x)$ is defined for $x>0$. Here, $y^{\prime}$ denotes the derivative of first order with respect to $x$ for a function $y(x)$.
1.)$$x^2y^{\prime\prime}-xy^{\prime}-x-3y=0$$
2.)$$x^3y^{\prime\prime\prime}+6x^2y^{\prime\prime}+4xy^{\prime}-4y=0$$

A: Since you need to express as a function of $t$ using $x=e^t$ (that is to say $t=\log(x)$), start with $$\frac{dy}{dx}=\frac{dy}{dt}\times \frac{dt}{dx}=\frac 1 x\frac{dy}{dt}=e^{-t}\frac{dy}{dt}$$ Deriving a second time $$\frac{d^2y}{dx^2}=\frac d{dt}\big(\frac{dy}{dx}\big)\frac{dt}{dx}=\frac d{dt}\big(e^ {-t}\frac{dy}{dt}\big)\frac{dt}{dx}=e^{-t} \left(\frac{d^2y}{dt^2}-\frac{dy}{dt}\right)e^{-t}=e^{-2t} \left(\frac{d^2y}{dt^2}-\frac{dy}{dt}\right)$$ So, the differential equation $$x^2y^{\prime\prime}-xy^{\prime}-x-3y=0$$ write $$e^{2t}e^{-2t} \left(\frac{d^2y}{dt^2}-\frac{dy}{dt}\right)-e^te^{-t}\frac{dy}{dt}-e^t-3t=0$$ that is to say $$\frac{d^2y}{dt^2}-2\frac{dy}{dt}-3y=e^t$$ which looks simple.
Continue the same way to get $\frac{d^3y}{dx^3}$ for the second problem.

A: The key point point about these differential equations is that the coefficient of each derivative of order $n$ is $x^n$. I know that the second order ODE the you wrote is named Euler differential equation. You can use the special property I mentioned to find the general solution of the corresponding homogeneous ODE namely ${y_h}$ and then find a particular solution ${y_p}$ for the non-homogeneous ODE. Finally, summing the two solutions ${y_h} + {y_p}$ will give you the general solution of the ODE. I will work out the first example, leaving the second for you. we have
$${x^2}y'' - xy' - 3y = x$$
fist consider the corresponding homogeneous ODE
$${x^2}y'' - xy' - 3y = 0$$
Now we guess that $y(x) = {x^r}$ can be a solution. This is motivated by the special property of this ODE that was pointed out. Now put it into the homogeneous ODE to get
$$\left( {{r^2} - r - 3} \right){x^r} = 0$$
so $x^r$ can be a solution if and only if
$${r^2} - r - 3 = 0\,\,\,\,\,\, \to \,\,\,\,\,\,\,{r_{1,2}} = {{1 \pm \sqrt {13} } \over 2}$$
so we have
$${y_h} = {c_1}{x^{{r_1}}} + {c_2}{x^{{r_2}}}$$
for finding a particular solution since the RHS is a polynomial we consider
$${y_p} = Ax + B$$
putting into the non-homogeneous ODE leads to
$$0 - Ax - 3\left( {Ax + B} \right) =  - 4Ax - 3B = x\,\,\,\,\,\,\, \to \,\,\,\,\,\,\left\{ \matrix{
   - 4A = 1 \hfill \cr
   - 3B = 0 \hfill \cr}  \right.\,\,\,\,\, \to \,\,\,\,\,\,\left\{ \matrix{
  A =  - {1 \over 4} \hfill \cr
  B = 0 \hfill \cr}  \right.$$
and hence
$${y_p} =  - {1 \over 4}x$$
and the general solution of the whole problem will be
$$y = {y_h} + {y_p} = {c_1}{x^{{r_1}}} + {c_2}{x^{{r_2}}} - {1 \over 4}x$$


text:
Q: How would you prove that $mLet $M,m,a,b\in\Bbb R$. How would you prove that $m<a,b<M$ then $|a-b|<M-m$? This little question came from a part of an exercise in analysis. Of course, this is quite simple to see if we draw these points on a number line. But how can we show this rigorously and simply?
PS: By triangle inequality, we can show that $|a-b|\leq|a-m|+|m-M|+|M-b|$, but this does not show that $|a-b|<M-m$.

A: We have $$a - b < M - m$$ and $$-(M - m) = m - M < a - b$$ Hence together $$|a - b| < M-m$$ By using that $$|x| < c \quad \Leftrightarrow \quad -c < x < c$$ for $x \in \mathbb{R}$ and $c > 0$.

A: Pf I: (A super easy proof)
Note that $\begin{cases}m<a<M\\m<b<M\end{cases}$, then $a-b<M-m$, since $M-m$ is the greatest possible value minus the lowest possible value. By the same reason we also  have $b-a<M-m$.
Pf II:
No matter $a$ or $b$ is the bigger, since $a<M$ and $m<b$, then $-b<-m$,
Add these two expression, we have $a+(-b)<M+(-m)$, namely $a-b<M-m$.
Since the choice of $a,b$ is arbitrary, then $b-a<M-m$ also holds.
Hence no matter $|a-b|=a-b$ or $b-a$, we have $|a-b|<M-m$.

A: Inequalities of real numbers like the one in your question follow easily from the properties of order relations of real numbers, but they are not obvious / self evident unless visualized on the number line. Also note that using number line is rigorous enough because of the assumption that to each point on the number line corresponds a unique real number and vice versa and the linear order from left to right on the number line is equivalent to the ordering of real numbers.
But in case you wish to avoid the number line here is a simple argument. Without any loss of generality we can assume $a<b$ because the case $a=b$ is trivial and the case $a>b$ can be obtained by reversing the roles of $a, b$. We then have $$m<a<b<M$$ and clearly $$M-m=(M-b) + b -  a + (a-m) $$ The terms in parentheses on the right side of the above equation are positive and hence $M-m>b-a=|a-b|$. The technique of splitting an expression into multiple terms by adding and subtracting the same quantity is heavily used in analysis mainly to establish inequalities like these.


text:
Q: Why isn't my Google +1 button code working? I can't figure out why my code for the Google +1 button isn't working as I expected.
http://jsfiddle.net/DerekL/EF8eE/
When you press the +1 button, an alert should pop up.
Here I got a callback function:
function cb(obj) {
    alert();              //alert
    console.log(obj);     //Then show obj in console
}

But never the callback never gets fired. I followed every single step according to the spec, and the funniest thing is that I got it working before... But now it just does not work at all. Strange!

A: From the docs (emphasis added),

you can use this HTML5-valid +1 tag (the class attribute must be set to g-plusone, and any button attributes must be prefixed with data-).

So change

to

Ta-da! http://jsfiddle.net/mattball/FtETf ♫


text:
Q: What kind of function would I have to use in this question? I have a question something like this:
Write a program to allocate and display Block and Floor No on the basis of Customer Number. Assuming there are 10 Blocks ('A' to 'J') with 5 floors (0 to 4) each and allocated to customers sequentially as per their Customer Number. For example Customer no 1 gets [Block A Floor 0], Customer no 3 gets [Block A Floor 2], Customer no 7 gets [Block B Floor 1]
Note: This program has to be done only using arithmetic operations and type conversions (i.e., without the use of if-else)
Hint: ASCII codes for 'A','B'.. are 65,66,... & chr(65) in python is 'A'
I have tried this program:
Customer = int(input("Customer number : "))
X = (Customer - 1 % 5)
Y = (Customer // 5)
Z = Y + 65
print("\n\nYour Floor Will Be: ",X)
print("Your Block Will Be: ",chr(Z))

Can someone please just tell what Have I Done Wrong? If possible, please also tell The Right answer.
I am currently in 11th Grade and have just started learning Python.
I know most of the Basic functions

A: just put a bracket
X = ((Customer - 1) % 5)
because acc to sequence of operations mod function will work first


text:
Q: Is there an equivalent of jQuery infinite drag for React? I am trying to create an app that will have an infinite wall interface, i.e., a div that opens onto a background that the user can drag around and that will expand forever wherever the user goes.
I found a cool jquery plugin called jquery infinite drag to do this, but I am having trouble using it with react. Is there a library with a component like this?


text:
Q: How to build the project to specific folder with visual studio command line tools? I've got this simplified folders structure for c++ project named project_name.
project_name
    -build
    -headers
    -sources
    -resources

If I do cl /EHsc /W4 sources/source1.cpp sources/source2.cpp /link /out:project_name ... it creates build files in current directory only which is project_name, resulting this:
project_name
    -build
    -headers
    -sources
    -resources
     project_name.exe
     source1.obj
     source2.obj
     etc

What I want is to specify the folder where all the build files have to be placed, in my case in a build folder.
What options are needed for cl or link to do that that from project_name directory ?

A: Place a .bat file in your project directory and use that to build your project.
pushd %~dp0/build
cl %~dp0/sources/source1.cpp %~dp0/sources/source2.cpp
popd

%~dp0 automatically expands to full path of your project directory so you can execute this .bat file from anywhere.


text:
Q: How to use multiple check-box values to work in a function and insert values in database I am working on a custom theme where there is option to upload images . I have certain check-boxes in the form which the users select as per where the image has to go. My form code is as follows :
<input type="checkbox" class="input" name="vtype[]" value="3"/>
<input type="checkbox" class="input" name="vtype[]" value="4" />
<input type="checkbox" class="input" name="vtype[]" value="5" />
<input type="checkbox" class="input" name="vtype[]" value="6" />

function for using the values is :
$image_category = implode(',', $_POST['vtype']);

if i echo this then the result is fine e.g. 3,4,5 . but if i try to use this value to insert values in database then the value is updated in only the 1st category and nothing happens for the remaining.
main function is inserting values in database is :
$post = array(
      'ID' => '',
      'post_author' => $image_author,
      'post_category' => array($image_category),
      'post_content' => $image_to_attach,
      'post_title' => $image_title,
      'post_status' => 'publish'
        );
    }
    // Insert the values in DB
    $id = wp_insert_post($post);

A: Currently you are passing on this value:
'post_category' => array('3,4,5') // This is a single string

While you should be doing this:
'post_category' => array(3,4,5) // Three separate values

Don't forget to sanitize the POST values neither:
// Initialize categories
$post_category = array();

// Prevent "undefined variable" error notices
if (isset($_POST['vtype']))
{
  // Loop over selected categories
  foreach ((array) $_POST['vtype'] as $vtype)
  {
    // Validate vtype (only numbers allowed)
    if (ctype_digit((string) $vtype))
    {
      // Add category
      $post_category[] = (int) $vtype;
    }
  }
}

// Save the post with $post_category in database as you did before...

You can shorten this whole block to a oneliner as well, if you like. Just for fun:
$post_category = (isset($_POST['vtype'])) ? array_filter((array) $_POST['vtype'], 'ctype_digit') : array();

A: another way for submitting multiple values using checkbox, enjoy :)
                'day'=> $days

            );
    $format=array( '%s');
    $succes=$wpdb->insert( $table, $data, $format );
    if($succes){
         echo 'Your values has been submitted';
    }
    else{
        echo "error in submitting";
    }
}

?>

            Day:
            Any Day:
            Sun:
            Mon:
            Tue:
            Wed:
            Thu:
            Fri:
            Sat:


text:
Q: Web Application doesn't work after publish I have create a web application. Also I create a controller named person, when I'm deploy my project and running example http://localhost:1392/api/Person
I'm getting return value from controller.
public IEnumerable<string> Get()
{
    return new string[] { "value1", "value2" };
}

// GET: api/Person/5
public string Get(int id)
{
    return "value";
}

// POST: api/Person
public void Post([FromBody]string value)
{
}

// PUT: api/Person/5
public void Put(int id, [FromBody]string value)
{
}

// DELETE: api/Person/5
public void Delete(int id)
{
}

When I'm publish my web application example in path C:/www
And trying to host this folder from iis7 I can't use above URL. I'm getting error 404 Not found
"http://192.168.0.214:8081/api/Person"
IIS7 Image:

And here is my error
Image error:

A: Your url is incorrect
Change
http://192.168.0.214:8081/api/Person

To
http://192.168.0.214:8081/FirstWebPage/api/Person


text:
Q: Diff between Subscription and Subscriber angular2 While I was working on some project I came across this type Subscriber<T>. I am not able to declare a property with appropriate type.
Problem is when I do,
let sub = this._api.getDefaultMedia().subscriptions.play.subscribe(
            () => {
                this.play();
            }
        );
console.log(sub);

It prints me the following which is of type Subscriber

But if I try to assign a variable which is of type Subscription
private subPlay : Subscription;

 this.subPlay = this._api.getDefaultMedia().subscriptions.play.subscribe(
            () => {
                this.play();
            }
        );

It gives me the following error Type Subscription is not assignable to type Subscription

Even though it says it is returning Subscription, when I do console it is of type Subscriber.
So what is the difference or similarity between these two?

A: There are two things to this:

*

*Type Subscription is not assignable to type Subscription.
I bet you imported or declared some other Subscription class and now TypeScript tries to assign the original Subscription form rxjs package to your custom Subscription class. That's why it complains that _subscriptions property is missing which can't happen otherwise.
See https://github.com/ReactiveX/rxjs/blob/master/src/Subscription.ts#L45.

*The subscribe() method really returns an instance of Subscriber class.
However Subscriber extends the Subscription class so the types are correct. If you're using TypeScript the compiler won't let you do any malicious stuff but if you were using just ES6 you could exploit this. I had a comment on one of RxJS's issues regarding exactly this situation: https://github.com/ReactiveX/rxjs/issues/2487#issuecomment-288976689.
As a rule of thumb, if you're unsure what instances are returned from function calls always have a look at the .d.ts file. This is recommended by the creators of RxJS themselves.
The subscribe() call is also not the only place you can encounter behavior. For example all window*() operators emit an instance of Subject instead of Observable. The same applies for retryWhen() and retryWhen() operators.
Some time ago I made a PR to RxJS regarding forcing Observables instead of Subjects and it was closed for the reasons I summarized here. You can have a look at them in the following links if you're interested in more indepth explanation:

*

*https://github.com/ReactiveX/rxjs/issues/2391

*https://github.com/ReactiveX/rxjs/pull/2408

*https://github.com/ReactiveX/rxjs/issues/2487#issuecomment-288871607


text:
Q: Password less telnet to remote server and execute commands and retrieve the details Currently am logging into the server using telnet on the command line without a password:
telnet -afl root servername

I need a script which should connect to server using telnet without a password, run a command like wc -l, and retrieve the result of this command.
I tried using expect, but it is prompting for a password, throwing an error. Can someone suggest a way this can be done?

A: Try this:
#!/usr/bin/env perl

use strict;
use warnings;

use Net::Telnet;

my $t = new Net::Telnet (Timeout  => 10);

$t->open('nethack.alt.org');

$t->waitfor( -match => '/Quit/' );

$t->print( 'w' );

print $t->waitfor( -match => '/Watch which game/' );


text:
Q: VBA MSWord 2007 - Insert text at line 7 I'm moving data from one document to another. I need to move the data and already have it as a string. I just don't know how to put it in the other word document.
The following is getting the text.
'finds a range of text between the words "Purpose" and "Scope" and makes it strThePurpose
Application.ScreenUpdating = False
Selection.HomeKey wdStory
Selection.Find.Text = "Purpose"
blnFound = Selection.Find.Execute
If blnFound Then
    Selection.MoveLeft wdWord
    Set rng1 = Selection.Range
    Selection.Find.Text = "Scope" 'changed here 2014-18-04 from "7.0 Revisions:" to "Revisions:"
    blnFound = Selection.Find.Execute
    If blnFound Then
        Set rng2 = Selection.Range
        Set rngFound = ActiveDocument.Range(rng1.Start, rng2.Start)
        strThePurposeText = rngFound
        'MsgBox (strTheText)

    End If
End If

I just don't know how to put it in the word document at a specific line in the template file.

Solved
Answer that seems to work:
Selection.GoTo What:=wdGoToLine, Which:=wdGoToFirst, Count:=7, Name:=""
Selection.TypeText Text:=strTheRefDocsText

Solved better
A better and more effective approach is to insert a bookmark in word and insert at the bookmark into the word template.
Selection.GoTo What:=wdGoToBookmark, Name:="bmBeginningOfDocument"
Selection.PasteAndFormat (wdPasteDefault)

A: Selection.GoTo What:=wdGoToBookmark, Name:="bmBeginningOfDocument"
Selection.PasteAndFormat (wdPasteDefault)

I used the above code as a better idea on how to get to the location.