问:
Apply payments to charges recursively SQL Server
I have in a single table both charges and payments. Payments are "applied" to charges in order to balance the account to zero. There is no specific order to apply, as long as all charges are balanced to zero (or most of them).

After the SP I'm trying to build there would be two possible states of the table. As I said, I don't care how they are "applied" as long as most of charges' balances is zero.

```<code>CREATE TABLE dbo.Transactions (
TrxID       INT IDENTITY,
TrxType     BIT, -- 1 for Charges, 0 for Payments
TrxDescription  VARCHAR(MAX),
Amount  DECIMAL(13,2),
ApplyTo     INT -- TrxID of the charge to which the payment is "applied"
);

INSERT INTO dbo.Transactions VALUES(1,'Charge1',100,NULL);
INSERT INTO dbo.Transactions VALUES(0,'Payment1',-80,NULL);
INSERT INTO dbo.Transactions VALUES(0,'Payment2',-15,NULL);
INSERT INTO dbo.Transactions VALUES(1,'Charge3',200,NULL);
INSERT INTO dbo.Transactions VALUES(0,'Payment4',-20,NULL);
INSERT INTO dbo.Transactions VALUES(0,'Payment5',-80,NULL);
INSERT INTO dbo.Transactions VALUES(0,'Payment6',-105,NULL);

SELECT * FROM dbo.transactions

SELECT SUM(Amount) FROM dbo.Transactions;
SELECT SUM(Amount) FROM dbo.Transactions WHERE TrxType=1;
SELECT SUM(Amount) FROM dbo.Transactions WHERE TrxType=0;

-- CORRECT APPLICATION
UPDATE dbo.Transactions SET ApplyTo=1 WHERE TrxID IN(2,5)
UPDATE dbo.Transactions SET ApplyTo=4 WHERE TrxID IN(3,6,7)

-- The global balance is zero
SELECT SUM(Amount) FROM dbo.Transactions

-- Both charges have zero balance
SELECT t.*,t.Amount+b.Balance 'Balance'
FROM dbo.Transactions t
OUTER APPLY (SELECT SUM(t2.Amount)Balance
         FROM dbo.Transactions t2
         WHERE t.TrxID=t2.ApplyTo
)b

-- WRONG APPLICATION
UPDATE dbo.Transactions SET ApplyTo=1 WHERE TrxID IN(2,3,5)
UPDATE dbo.Transactions SET ApplyTo=4 WHERE TrxID IN(6,7)

-- The global balance is zero
SELECT SUM(Amount) FROM dbo.Transactions

-- Charges dont have correct balance, as they could be both zero if applied correctly
SELECT t.*,t.Amount+b.Balance 'Balance'
FROM dbo.Transactions t
OUTER APPLY (SELECT SUM(t2.Amount)Balance
         FROM dbo.Transactions t2
         WHERE t.TrxID=t2.ApplyTo
)b
</code>```

Thanks.

答:
What you're trying to solve is the subset sum problem. This is an NP complete problem, and even the best algorithms run in exponential time O(2N/2).

Given that your problem looks like a balance sheet that could involve thousands of payments and charges (subsets and sums), there is not an exact solution that can run in a reasonable amount of time.

Here is a solution that will make a best effort to apply the payments using a MySQL stored procedure:

```<code>BEGIN

    DECLARE charge int;
    declare charge_id int;
    DECLARE payment int;
    declare payment_id int;
    declare foundrows int;

    balance_loop: LOOP

       SELECT trxid, amount into charge_id, charge
        from transactions
        where trxtype = 1
        and applyto is null
        limit 1;

        SET foundrows = (SELECT FOUND_ROWS());

        if foundrows = 0 then
            call debug(concat('Finished '));
            leave balance_loop;
        end if;

        call debug(concat('Balancing charge ', charge_id));
        call debug(concat('starting with charge amount: ', charge));

        payment_loop: while charge > 0 do
            call debug(concat('start charge: ', charge));

            SELECT trxid, ABS(amount) into payment_id, payment
            FROM transactions
            WHERE trxtype =  0
            AND applyto is null
            AND ABS(amount) <= charge
            order by RAND()
            limit 1;

            call debug(concat('applying payment: ', payment));
            set charge = charge - payment;

            call debug(concat('remaining charge: ', charge));

            if charge >= 0 then
                update transactions
                set applyto = charge_id
                where trxid = payment_id;
                call debug(concat('applied payment_id', payment_id, ' to charge ID ', charge_id));
            end if;

        end while;

        update transactions set applyto = 0 where trxid = charge_id;

    end loop;

END
</code>```

Body:
I have in a single table both charges and payments. Payments are "applied" to charges in order to balance the account to zero. There is no specific order to apply, as long as all charges are balanced to zero (or most of them).

After the SP I'm trying to build there would be two possible states of the table. As I said, I don't care how they are "applied" as long as most of charges' balances is zero.

CREATE TABLE dbo.Transactions (
TrxID       INT IDENTITY,
TrxType     BIT, -- 1 for Charges, 0 for Payments
TrxDescription  VARCHAR(MAX),
Amount  DECIMAL(13,2),
ApplyTo     INT -- TrxID of the charge to which the payment is "applied"
);

INSERT INTO dbo.Transactions VALUES(1,'Charge1',100,NULL);
INSERT INTO dbo.Transactions VALUES(0,'Payment1',-80,NULL);
INSERT INTO dbo.Transactions VALUES(0,'Payment2',-15,NULL);
INSERT INTO dbo.Transactions VALUES(1,'Charge3',200,NULL);
INSERT INTO dbo.Transactions VALUES(0,'Payment4',-20,NULL);
INSERT INTO dbo.Transactions VALUES(0,'Payment5',-80,NULL);
INSERT INTO dbo.Transactions VALUES(0,'Payment6',-105,NULL);

SELECT * FROM dbo.transactions

SELECT SUM(Amount) FROM dbo.Transactions;
SELECT SUM(Amount) FROM dbo.Transactions WHERE TrxType=1;
SELECT SUM(Amount) FROM dbo.Transactions WHERE TrxType=0;

-- CORRECT APPLICATION
UPDATE dbo.Transactions SET ApplyTo=1 WHERE TrxID IN(2,5)
UPDATE dbo.Transactions SET ApplyTo=4 WHERE TrxID IN(3,6,7)

-- The global balance is zero
SELECT SUM(Amount) FROM dbo.Transactions

-- Both charges have zero balance
SELECT t.*,t.Amount+b.Balance 'Balance'
FROM dbo.Transactions t
OUTER APPLY (SELECT SUM(t2.Amount)Balance
         FROM dbo.Transactions t2
         WHERE t.TrxID=t2.ApplyTo
)b

-- WRONG APPLICATION
UPDATE dbo.Transactions SET ApplyTo=1 WHERE TrxID IN(2,3,5)
UPDATE dbo.Transactions SET ApplyTo=4 WHERE TrxID IN(6,7)

-- The global balance is zero
SELECT SUM(Amount) FROM dbo.Transactions

-- Charges dont have correct balance, as they could be both zero if applied correctly
SELECT t.*,t.Amount+b.Balance 'Balance'
FROM dbo.Transactions t
OUTER APPLY (SELECT SUM(t2.Amount)Balance
         FROM dbo.Transactions t2
         WHERE t.TrxID=t2.ApplyTo
)b

Thanks.

Body:
What you're trying to solve is the subset sum problem. This is an NP complete problem, and even the best algorithms run in exponential time O(2N/2).

Given that your problem looks like a balance sheet that could involve thousands of payments and charges (subsets and sums), there is not an exact solution that can run in a reasonable amount of time.

Here is a solution that will make a best effort to apply the payments using a MySQL stored procedure:

BEGIN

    DECLARE charge int;
    declare charge_id int;
    DECLARE payment int;
    declare payment_id int;
    declare foundrows int;

    balance_loop: LOOP

       SELECT trxid, amount into charge_id, charge
        from transactions
        where trxtype = 1
        and applyto is null
        limit 1;

        SET foundrows = (SELECT FOUND_ROWS());

        if foundrows = 0 then
            call debug(concat('Finished '));
            leave balance_loop;
        end if;

        call debug(concat('Balancing charge ', charge_id));
        call debug(concat('starting with charge amount: ', charge));

        payment_loop: while charge > 0 do
            call debug(concat('start charge: ', charge));

            SELECT trxid, ABS(amount) into payment_id, payment
            FROM transactions
            WHERE trxtype =  0
            AND applyto is null
            AND ABS(amount) <= charge
            order by RAND()
            limit 1;

            call debug(concat('applying payment: ', payment));
            set charge = charge - payment;

            call debug(concat('remaining charge: ', charge));

            if charge >= 0 then
                update transactions
                set applyto = charge_id
                where trxid = payment_id;
                call debug(concat('applied payment_id', payment_id, ' to charge ID ', charge_id));
            end if;

        end while;

        update transactions set applyto = 0 where trxid = charge_id;

    end loop;

END


来源: stackexchange

问:
Need help in extracting unique lines from a file using python
I have a file with the below details:

```<code>**169.254.230.157 : 169.254.42.146**
169.254.230.157 : 169.254.138.97
169.254.230.157 : 169.254.162.67
169.254.223.76 : 169.254.42.146
**169.254.223.76 : 169.254.138.97**
169.254.223.76 : 169.254.162.67
</code>```

I need to get the unique lines like the below

```<code>169.254.230.157 : 169.254.42.146
169.254.223.76 : 169.254.138.97
</code>```

Below is what i was trying:

```<code>    ping_ip = open("ping.txt","r")
    ping_lines = ping_ip.readlines()

    list1 = []
    list2 = []
    for line in ping_lines:
        ip_s, ip_d = line.split(":")
        #print ip_s, " : ", ip_d
        m = re.search(ip_s.rstrip(),line)
        n = re.search(ip_d.rstrip(),line)
        if m and n not in list1 and list2 :
            list1.append(m.group(0))
            list2.append(n.group(0))
            print line
    print set(list1)
</code>```

答:
Not sure I understand your question completely, but if you are trying to get the unique values from a list of values such as the IP addresses you listed, you can put your data into a Set, which by definition is a collection of unique items.

https://docs.python.org/2/library/sets.html

With your code, you could do something like this(not sure this works but just for demonstration purposes):

```<code>from sets import Set
### - print IPs - ###
ping_ip = open("ping.txt","r")
ping_lines = ping_ip.readlines()

count = 0
print "################################################"
print "START"
print "################################################"
try:
#####
set1=Set()
set2=Set()
for line in ping_lines:
    ip_s, ip_d = line.split(":")
    set1.add(ip_s)
    set2.add(ip_d)
    print set(list1)
    print set(list2)
    #####
except:
    print "exiting..."
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a file with the below details:

**169.254.230.157 : 169.254.42.146**
169.254.230.157 : 169.254.138.97
169.254.230.157 : 169.254.162.67
169.254.223.76 : 169.254.42.146
**169.254.223.76 : 169.254.138.97**
169.254.223.76 : 169.254.162.67

I need to get the unique lines like the below

169.254.230.157 : 169.254.42.146
169.254.223.76 : 169.254.138.97

Below is what i was trying:

    ping_ip = open("ping.txt","r")
    ping_lines = ping_ip.readlines()

    list1 = []
    list2 = []
    for line in ping_lines:
        ip_s, ip_d = line.split(":")
        #print ip_s, " : ", ip_d
        m = re.search(ip_s.rstrip(),line)
        n = re.search(ip_d.rstrip(),line)
        if m and n not in list1 and list2 :
            list1.append(m.group(0))
            list2.append(n.group(0))
            print line
    print set(list1)

Body:
Not sure I understand your question completely, but if you are trying to get the unique values from a list of values such as the IP addresses you listed, you can put your data into a Set, which by definition is a collection of unique items.

https://docs.python.org/2/library/sets.html

With your code, you could do something like this(not sure this works but just for demonstration purposes):

from sets import Set
### - print IPs - ###
ping_ip = open("ping.txt","r")
ping_lines = ping_ip.readlines()

count = 0
print "################################################"
print "START"
print "################################################"
try:
#####
set1=Set()
set2=Set()
for line in ping_lines:
    ip_s, ip_d = line.split(":")
    set1.add(ip_s)
    set2.add(ip_d)
    print set(list1)
    print set(list2)
    #####
except:
    print "exiting..."


问:
GitLab git user password
I have just installed GitLab.

I created a project called project-x.

I have created few users and assigned it to the project.

Now I tried to clone:

```<code> git clone git@192.168.0.108:project-x.git
</code>```

It prompted me for a password.

What password should I use?

答:
I had this same problem when using a key of 4096 bits:

$ ssh-keygen -t rsa -C "GitLab" -b 4096

  $ ssh -vT git@gitlabhost

  ...

  debug1: Offering public key: /home/user/.ssh/id_rsa

  debug1: Authentications that can continue: publickey,password

  debug1: Trying private key: /home/user/.ssh/id_dsa

  debug1: Trying private key: /home/user/.ssh/id_ecdsa

  debug1: Next authentication method: password

  git@gitlabhost's password:

  Connection closed by host

But with the 2048 bit key (the default size), ssh connects to gitlab without prompting for a password (after adding the new pub key to the user's gitlab ssh keys)

$ ssh-keygen -t rsa -C "GitLab"

  $ ssh -vT git@gitlabhost

  Welcome to GitLab, Joe User!

Title: GitLab git user password

Body:
I have just installed GitLab.

I created a project called project-x.

I have created few users and assigned it to the project.

Now I tried to clone:

 git clone git@192.168.0.108:project-x.git

It prompted me for a password.

What password should I use?


问:
python regular expressions index long string and eliminate all things between regular patterns A and B
I have the following sentence where I want to get rid of everything with the format '(number)/(... ;  number)' :

In all living organisms, from bacteria to man, DNA and chromatin are
  invariably associated with binding proteins, which organize their
  structure (1; 2 ;  3). Many of these architectural proteins are
  molecular bridges that can bind at two or more distinct DNA sites to
  form loops. For example, bacterial DNA is looped and compacted by the
  histonelike protein H-NS, which has two distinct DNA-binding domains
  (4). In eukaryotes, complexes of transcription factors and RNA
  polymerases stabilize enhancer-promoter loops (5; 6; 7 ;  8), while
  HP1 (9), histone H1 (10), and the polycomb-repressor complex PRC1/2
  (11 ;  12) organize inactive chromatin. Proteins also bind to specific
  DNA sequences to form larger structures, like nucleoli and the
  histone-locus, or Cajal and promyeloleukemia bodies (13; 14; 15; 16;
  17 ;  18). The selective binding of molecular bridges to active and
  inactive regions of chromatin has also been highlighted as one
  possible mechanism underlying the formation of topologically
  associated domains (TADs)—regions rich in local DNA interactions (6; 8
  ;  19).

I want it to be in the form:

In all living organisms, from bacteria to man, DNA and chromatin are
  invariably associated with binding proteins, which organize their
  structure . Many of these architectural proteins are molecular bridges
  that can bind at two or more distinct DNA sites to form loops. For
  example, bacterial DNA is looped and compacted by the histonelike
  protein H-NS, which has two distinct DNA-binding domains . In
  eukaryotes, complexes of transcription factors and RNA polymerases
  stabilize enhancer-promoter loops , while HP1 , histone H1 , and the
  polycomb-repressor complex PRC1/2  organize inactive chromatin.
  Proteins also bind to specific DNA sequences to form larger
  structures, like nucleoli and the histone-locus, or Cajal and
  promyeloleukemia bodies . The selective binding of molecular bridges
  to active and inactive regions of chromatin has also been highlighted
  as one possible mechanism underlying the formation of topologically
  associated domains (TADs)—regions rich in local DNA interactions .

My attempt was as follows:

```<code>import re
x=re.sub(r'\(.+;  \d+\)', '', x) # eliminate brackets with multiple numbers
#### NOTE: there are 2 spaces between the last ';' and the last digit
x=re.sub(r'\d+\)', '', x) # eliminate brackets with single number
</code>```

My output was this:

In all living organisms, from bacteria to man, DNA and chromatin are
  invariably associated with binding proteins, which organize their
  structure .

So clearly my code is missing something. I thought that '(.+)' would identify all brackets containing non-arbitrary characters and then I could further specify that I want all the ones ending in a ';  number'.

I just want a flexible way of indexing a sentence at all places with '(number' and 'number)' and eliminate everything in between....

答:
You can use a pattern like \(\d+(?:;\s?\d+\s?)*\), which matches an initial parentheses and digits ( <number>, and then any possible repeating ; <number>s that ends in ). Test it.

Or if you're feeling brave you can use \([;\d\s]+\) which just matches everything with digits/spaces/semicolons between two parentheses. Test it.

Body:
I have the following sentence where I want to get rid of everything with the format '(number)/(... ;  number)' :

In all living organisms, from bacteria to man, DNA and chromatin are
  invariably associated with binding proteins, which organize their
  structure (1; 2 ;  3). Many of these architectural proteins are
  molecular bridges that can bind at two or more distinct DNA sites to
  form loops. For example, bacterial DNA is looped and compacted by the
  histonelike protein H-NS, which has two distinct DNA-binding domains
  (4). In eukaryotes, complexes of transcription factors and RNA
  polymerases stabilize enhancer-promoter loops (5; 6; 7 ;  8), while
  HP1 (9), histone H1 (10), and the polycomb-repressor complex PRC1/2
  (11 ;  12) organize inactive chromatin. Proteins also bind to specific
  DNA sequences to form larger structures, like nucleoli and the
  histone-locus, or Cajal and promyeloleukemia bodies (13; 14; 15; 16;
  17 ;  18). The selective binding of molecular bridges to active and
  inactive regions of chromatin has also been highlighted as one
  possible mechanism underlying the formation of topologically
  associated domains (TADs)—regions rich in local DNA interactions (6; 8
  ;  19).

I want it to be in the form:

In all living organisms, from bacteria to man, DNA and chromatin are
  invariably associated with binding proteins, which organize their
  structure . Many of these architectural proteins are molecular bridges
  that can bind at two or more distinct DNA sites to form loops. For
  example, bacterial DNA is looped and compacted by the histonelike
  protein H-NS, which has two distinct DNA-binding domains . In
  eukaryotes, complexes of transcription factors and RNA polymerases
  stabilize enhancer-promoter loops , while HP1 , histone H1 , and the
  polycomb-repressor complex PRC1/2  organize inactive chromatin.
  Proteins also bind to specific DNA sequences to form larger
  structures, like nucleoli and the histone-locus, or Cajal and
  promyeloleukemia bodies . The selective binding of molecular bridges
  to active and inactive regions of chromatin has also been highlighted
  as one possible mechanism underlying the formation of topologically
  associated domains (TADs)—regions rich in local DNA interactions .

My attempt was as follows:

import re
x=re.sub(r'\(.+;  \d+\)', '', x) # eliminate brackets with multiple numbers
#### NOTE: there are 2 spaces between the last ';' and the last digit
x=re.sub(r'\d+\)', '', x) # eliminate brackets with single number

My output was this:

In all living organisms, from bacteria to man, DNA and chromatin are
  invariably associated with binding proteins, which organize their
  structure .

So clearly my code is missing something. I thought that '(.+)' would identify all brackets containing non-arbitrary characters and then I could further specify that I want all the ones ending in a ';  number'.

I just want a flexible way of indexing a sentence at all places with '(number' and 'number)' and eliminate everything in between....


问:
String cannot be converted to JSONObject for a registration page
i am trying to make a registration page, and i have completed the xml page and i have written the activity java file
here is the code

```<code>public class RegisterActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_register);

    final EditText etUserName = (EditText) findViewById(R.id.etUserName);
    final EditText etUserEmail = (EditText) findViewById(R.id.etUserEmail);
    final EditText etUserContactNo = (EditText) findViewById(R.id.etUserContactNo);
    final EditText etUserPassword = (EditText) findViewById(R.id.etUserPassword);
    final Button btnRegister = (Button) findViewById(R.id.btnRegister);

    btnRegister.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final String UserName = etUserName.getText().toString();
            final String UserContactNo = etUserContactNo.getText().toString();
            final String UserEmail = etUserEmail.getText().toString();
            final String UserPassword = etUserPassword.getText().toString();

            Response.Listener<String> responseListener = new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        JSONObject jsonResponse = new JSONObject(response);
                        boolean success =  jsonResponse.getBoolean("success");

                        if (success){
                            Intent intent  = new Intent(RegisterActivity.this, LoginActivity.class);
                            RegisterActivity.this.startActivity(intent);
                        }else{
                            AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
                            builder.setMessage("Registration Failed")
                                    .setNegativeButton("Retry", null)
                                    .create()
                                    .show();
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            };

            RegisterRequest registerRequest = new RegisterRequest(UserName, UserPassword, UserContactNo, UserEmail, responseListener);
            RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
            queue.add(registerRequest);

        }
    });

}
</code>```

}

and the php file that is connected to the activity

```<code><?php
$con = mysqli_connect("******", "*****", "*******", "*******");

$UserName = $_POST["UserName"];
$UserPassword = $_POST["UserPassword"];
$UserContactNo = $_POST["UserContactNo"];
$UserEmail = $_POST["UserEmail"];

$statement = mysqli_prepare($con, "INSERT INTO UserDetails (UserName,UserContactNo, UserEmail, UserPassword) VALUES (?, ?, ?, ?)");
mysqli_stmt_bind_param($statement, "ssss", $UserName, $UserContactNo, $UserEmail, $UserPassword);
mysqli_stmt_execute($statement);

$response = array();
$response["success"] = true;

echo json_encode($response);
?>
</code>```

and the problem that i am facing, which is written in the android monitor

```<code>03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err: org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at org.json.JSON.typeMismatch(JSON.java:111)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:160)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:173)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at com.example.hp.myapplication.RegisterActivity$1$1.onResponse(RegisterActivity.java:43)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at com.example.hp.myapplication.RegisterActivity$1$1.onResponse(RegisterActivity.java:39)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at android.os.Handler.handleCallback(Handler.java:739)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at android.os.Looper.loop(Looper.java:148)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5417)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
03-30 20:39:24.125 1582-1595/system_process I/UsageStatsService: User[0] Flushing usage stats to disk
</code>```

答: You should change your backend part: your php script should return json content with next header: Content-Type:application/json;. Now it returns text/html.

Body:
i am trying to make a registration page, and i have completed the xml page and i have written the activity java file
here is the code

public class RegisterActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_register);

    final EditText etUserName = (EditText) findViewById(R.id.etUserName);
    final EditText etUserEmail = (EditText) findViewById(R.id.etUserEmail);
    final EditText etUserContactNo = (EditText) findViewById(R.id.etUserContactNo);
    final EditText etUserPassword = (EditText) findViewById(R.id.etUserPassword);
    final Button btnRegister = (Button) findViewById(R.id.btnRegister);

    btnRegister.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final String UserName = etUserName.getText().toString();
            final String UserContactNo = etUserContactNo.getText().toString();
            final String UserEmail = etUserEmail.getText().toString();
            final String UserPassword = etUserPassword.getText().toString();

            Response.Listener<String> responseListener = new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        JSONObject jsonResponse = new JSONObject(response);
                        boolean success =  jsonResponse.getBoolean("success");

                        if (success){
                            Intent intent  = new Intent(RegisterActivity.this, LoginActivity.class);
                            RegisterActivity.this.startActivity(intent);
                        }else{
                            AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
                            builder.setMessage("Registration Failed")
                                    .setNegativeButton("Retry", null)
                                    .create()
                                    .show();
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            };

            RegisterRequest registerRequest = new RegisterRequest(UserName, UserPassword, UserContactNo, UserEmail, responseListener);
            RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
            queue.add(registerRequest);

        }
    });

}

}

and the php file that is connected to the activity

<?php
$con = mysqli_connect("******", "*****", "*******", "*******");

$UserName = $_POST["UserName"];
$UserPassword = $_POST["UserPassword"];
$UserContactNo = $_POST["UserContactNo"];
$UserEmail = $_POST["UserEmail"];

$statement = mysqli_prepare($con, "INSERT INTO UserDetails (UserName,UserContactNo, UserEmail, UserPassword) VALUES (?, ?, ?, ?)");
mysqli_stmt_bind_param($statement, "ssss", $UserName, $UserContactNo, $UserEmail, $UserPassword);
mysqli_stmt_execute($statement);

$response = array();
$response["success"] = true;

echo json_encode($response);
?>

and the problem that i am facing, which is written in the android monitor

03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err: org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at org.json.JSON.typeMismatch(JSON.java:111)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:160)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:173)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at com.example.hp.myapplication.RegisterActivity$1$1.onResponse(RegisterActivity.java:43)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at com.example.hp.myapplication.RegisterActivity$1$1.onResponse(RegisterActivity.java:39)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at android.os.Handler.handleCallback(Handler.java:739)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at android.os.Looper.loop(Looper.java:148)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5417)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
03-30 20:39:24.125 1582-1595/system_process I/UsageStatsService: User[0] Flushing usage stats to disk


答:
Try the following regex:

```<code>r'\s\((\d+\s?;?\s?)+\)'
</code>```

This regex will match one or more groups of numbers (followed by spaces/semicolons) inside of parenthesis.

There seems to always be a space before the collection of numbers, so matching that should help with the "trailing space".

Title: python regular expressions index long string and eliminate all things between regular patterns A and B

Body:
Try the following regex:

r'\s\((\d+\s?;?\s?)+\)'

This regex will match one or more groups of numbers (followed by spaces/semicolons) inside of parenthesis.

There seems to always be a space before the collection of numbers, so matching that should help with the "trailing space".


问:
Ajax base64 String does not work in success
I generate every few second a base64 string from a canvas:

```<code>function generateImg(start) {

    startInterval = setInterval(function() {
       saveBase64StringAjax(canvas.toDataURL());
    }, 1000);

}

function saveBase64StringAjax(imgData) {
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    $.ajax({
        url: 'postStream',
        type: 'post',
        data: imgData,
        success:function(data) {
            console.log(data);
        }
    });
}
</code>```

If I copy the data from console.log(canvas.toDataURL()) and paste it into here http://codebeautify.org/base64-to-image-converter I get the correct image.

I am sending the data via ajax to my controller function:

```<code>public function postAjax(Request $request)
{
    $data = $request->all();
}
</code>```

The success method in my ajax calls that $data but that base64string is wrong, if I paste that here: http://codebeautify.org/base64-to-image-converter it shows nothing.

The working base64 String : http://kopy.io/fjlzp
The base64 String which does not work: http://kopy.io/w1F20

In addition to that I get this script generated around the not working base 64 string: http://kopy.io/X7TtO

答:
A typical Base64 string may look like :

TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlz
  IHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2Yg
  dGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGlu
  dWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRo
  ZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4=

Note that because of the = at the end the server will get a query string with an array key TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlz
IHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2Yg
dGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGlu
dWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRo
ZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4 and an empty value which will mess things up.

Do this:

```<code>function saveBase64StringAjax(imgData) {
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    $.ajax({
        url: 'postStream',
        type: 'post',
        data: { imgData: imgData },
        success:function(data) {
            console.log(data);
        }
    });
}
</code>```

Then you can get this data via:

```<code>public function postAjax(Request $request) {
    $data = $request->imgData;
}
</code>```

Body:
I generate every few second a base64 string from a canvas:

function generateImg(start) {

    startInterval = setInterval(function() {
       saveBase64StringAjax(canvas.toDataURL());
    }, 1000);

}

function saveBase64StringAjax(imgData) {
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    $.ajax({
        url: 'postStream',
        type: 'post',
        data: imgData,
        success:function(data) {
            console.log(data);
        }
    });
}

If I copy the data from console.log(canvas.toDataURL()) and paste it into here http://codebeautify.org/base64-to-image-converter I get the correct image.

I am sending the data via ajax to my controller function:

public function postAjax(Request $request)
{
    $data = $request->all();
}

The success method in my ajax calls that $data but that base64string is wrong, if I paste that here: http://codebeautify.org/base64-to-image-converter it shows nothing.

The working base64 String : http://kopy.io/fjlzp
The base64 String which does not work: http://kopy.io/w1F20

In addition to that I get this script generated around the not working base 64 string: http://kopy.io/X7TtO

Body:
A typical Base64 string may look like :

TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlz
  IHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2Yg
  dGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGlu
  dWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRo
  ZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4=

Note that because of the = at the end the server will get a query string with an array key TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlz
IHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2Yg
dGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGlu
dWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRo
ZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4 and an empty value which will mess things up.

Do this:

function saveBase64StringAjax(imgData) {
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    $.ajax({
        url: 'postStream',
        type: 'post',
        data: { imgData: imgData },
        success:function(data) {
            console.log(data);
        }
    });
}

Then you can get this data via:

public function postAjax(Request $request) {
    $data = $request->imgData;
}


问:
blank rows while exporting the data as csv file in php
I need to export the db content as csv file in my Application.It is working. But the content is not start from the first row. Its starts from 40th row.What I have to do more in that? </p>

```<code>header('Content-Encoding: UTF-8');
header("Cache-Control: cache, must-revalidate");
header("Pragma: public");
header('Content-Type: text/csv, charset=UTF-8; encoding=UTF-8');
$filename = date('Y_m_d_s');
header("Content-Disposition: attachment; filename=\"".$filename.".csv\"");

if($dbResult) {
    $cnthead=0; $cntr =count($dbResult[0])-1;
    foreach($dbResult[0] as $key => $Val){
        echo $key;
        if($cnthead < $cntr) {
            echo ",";
            $cnthead++;
        }
    }
    echo "\n";
    foreach($dbResult as $dbRes){
        $cntcontnt=0;
        foreach($dbRes as $dbVal){
            echo $dbVal;
            if($cntcontnt < $cntr) {
                echo ",";
                $cntcontnt++;
            }
        }
        echo "\n";
    }
}
</code>```

<p>$dbResult array is like below,</p>

```<code>Array
(
    [0] => Array
        (
            [Appraisee Name] => aaa R
            [Team] => Software
            [Appraisee Emp No] => -
            [Appraiser Name] => vvv A
            [Appraiser Emp No] => -
            [Reviewer Name] => sss S
            [Reviewer Emp No] => -
            [Current Appraisal Status] => start
        )

    [1] => Array
        (
            [Appraisee Name] => gan R
            [Team] => Software
            [Appraisee Emp No] => -
            [Appraiser Name] => fcv R
            [Appraiser Emp No] => -
            [Reviewer Name] => sss S
            [Reviewer Emp No] => -
            [Current Appraisal Status] => start
        )
)
</code>```

答:
Thanks to user2063756, you pointed me on the right direction.
My CSV file was starting at the 4th row.
Simply because I was using a PHP include file of my constants....and this file had an empty line before the "

WAS
"

instead of
"

Body:
I need to export the db content as csv file in my Application.It is working. But the content is not start from the first row. Its starts from 40th row.What I have to do more in that?

header('Content-Encoding: UTF-8');
header("Cache-Control: cache, must-revalidate");
header("Pragma: public");
header('Content-Type: text/csv, charset=UTF-8; encoding=UTF-8');
$filename = date('Y_m_d_s');
header("Content-Disposition: attachment; filename=\"".$filename.".csv\"");

if($dbResult) {
    $cnthead=0; $cntr =count($dbResult[0])-1;
    foreach($dbResult[0] as $key => $Val){
        echo $key;
        if($cnthead < $cntr) {
            echo ",";
            $cnthead++;
        }
    }
    echo "\n";
    foreach($dbResult as $dbRes){
        $cntcontnt=0;
        foreach($dbRes as $dbVal){
            echo $dbVal;
            if($cntcontnt < $cntr) {
                echo ",";
                $cntcontnt++;
            }
        }
        echo "\n";
    }
}

$dbResult array is like below,

Array
(
    [0] => Array
        (
            [Appraisee Name] => aaa R
            [Team] => Software
            [Appraisee Emp No] => -
            [Appraiser Name] => vvv A
            [Appraiser Emp No] => -
            [Reviewer Name] => sss S
            [Reviewer Emp No] => -
            [Current Appraisal Status] => start
        )

    [1] => Array
        (
            [Appraisee Name] => gan R
            [Team] => Software
            [Appraisee Emp No] => -
            [Appraiser Name] => fcv R
            [Appraiser Emp No] => -
            [Reviewer Name] => sss S
            [Reviewer Emp No] => -
            [Current Appraisal Status] => start
        )
)


问:
Binding Variables in Ruby
I currently have a table that is listed as follows:

```<code>projects = Project.find(:all, :conditions => [conditions + "AND (name LIKE ? OR description LIKE ?)", "%#{params[:query]}%", "%#{params[:query]}%"])
</code>```

where

```<code> conditions = Project.in_used_projects(:alias => "projects")
</code>```

However I need to include a 3rd variable which is not from the Project table but from a Tags table. The column I need is Tag - > Names. Is there anyway I can bind variables from another table in Ruby? The Project.find(all) automatically passes the SELECT * FROM Project into MYSQL. Someone has suggested using a join function, but I'm not sure how this would work. Any ideas?

EDIT 1

I have tried the suggested answer of using

```<code>projects = Project.find(:all, :joins => "tags", :conditions => [conditions + "AND (projects.name LIKE ? OR description LIKE ? OR tags.name LIKE ?", ["%#{params[:query]}%" * 3]].flatten)
</code>```

but now I am getting another error

Mysql::Error: Unknown table 'projects': SELECTprojects.* FROMprojectstags WHERE ((projects.status = 2)AND (projects.name LIKE '%%' OR projects.description LIKE '%%' OR tags.name LIKE '%%')

Very strange considering the projects table exists. Why isn't Ruby recognizing it now that i've included another table?

答: Do you have any relationship between projects and tags? If the reason for your query is that there is, it should be reflected in the model (for ex with a HABTM), which would also enable you to easily filter based on that relationship without the need to have complex SQL queries crafted.</p>

ContentLicense: CC BY-SA 2.5

Title: Binding Variables in Ruby

Body:
I currently have a table that is listed as follows:

projects = Project.find(:all, :conditions => [conditions + "AND (name LIKE ? OR description LIKE ?)", "%#{params[:query]}%", "%#{params[:query]}%"])

where

 conditions = Project.in_used_projects(:alias => "projects")

However I need to include a 3rd variable which is not from the Project table but from a Tags table. The column I need is Tag - > Names. Is there anyway I can bind variables from another table in Ruby? The Project.find(all) automatically passes the SELECT * FROM Project into MYSQL. Someone has suggested using a join function, but I'm not sure how this would work. Any ideas?

EDIT 1

I have tried the suggested answer of using

projects = Project.find(:all, :joins => "tags", :conditions => [conditions + "AND (projects.name LIKE ? OR description LIKE ? OR tags.name LIKE ?", ["%#{params[:query]}%" * 3]].flatten)

but now I am getting another error

Mysql::Error: Unknown table 'projects': SELECTprojects.* FROMprojectstags WHERE ((projects.status = 2)AND (projects.name LIKE '%%' OR projects.description LIKE '%%' OR tags.name LIKE '%%')

Very strange considering the projects table exists. Why isn't Ruby recognizing it now that i've included another table?


问:
Show/hide iframes with an event listener
I am fairly new to javascript/web development but I am tasked in a group project to create image comparison sliders to an existing webpage.  There is a map (ArcGIS web map) on the page, and I have found a service that hosts image comparison sliders in iframes.

I was thinking that I could use an EventListener to listen for when the user clicks on a point on the map, and then it would display the corresponding iframe, and hide the last one.

Is this possible?

答: Yes. This is definitely possible in Javascript. All you have to do is setup a function to be called on an onclick event, and in this function you must obtain the required click coordinates (using event.clientX and event.clientY). Based on these coordinates you can figure out the required iFrame number.


答:
Maybe you can try to use the pattern

```<code>re.sub('\([0-9; ]+\)', '', x)
</code>```

which removes all parenthesis that contein at least a number, a ";" or a space.

I think it's not the case to use the r prefix.

Body:
Maybe you can try to use the pattern

re.sub('\([0-9; ]+\)', '', x)

which removes all parenthesis that contein at least a number, a ";" or a space.

I think it's not the case to use the r prefix.


问:
How to authenticate user against Active Directory from java?
I need to authenticate users against Active Directory from java. In order to understand what is going on under the hood I've started with openldap docker instance and spring tutorial from here:
https://spring.io/guides/gs/authenticating-ldap/

What I understand from many debug sessions is that Spring retrieves password attribute from ldap and compares it with hashed user password or it just filters users by uid and hashed password and if there is an entry then the password is correct.

Ok, sounds good. Now I'm trying to do the same thing against Active Directory. The problem is is that when I retrieve user from it, it gives me many attributes, but it doesn't give me any attribute which look like hashed password. So maybe Active Directory doesn't allow to get password attribute and I should filter users by this attribute. But I don't know it's name and don't know where to get it.

So my questions are:
1. Do I understand everything right?
2. Do I need to just filter users by uid and hashed password?
3. If the second one is correct, then what is the query for users filtration?
4. If the second one is not correct, then what did I understand wrong and how should I authenticate users against Active Directory from java?

答:
I would proceed with using the bind authentication approach with Active Directory.  I have used this approach in the past without any problems against Active Directory (or ADAM).  With a bind scenario you simply use the username and password supplied by the user and allow the LDAP instance to perform the comparison (authentication).  Here is reference section from Spring Documentation:

18.3.2 Using Bind Authentication

This is the most common LDAP authentication scenario.

   This simple example would obtain the DN for the user by substituting the user login name in the supplied pattern and attempting to bind as that user with the login password. This is OK if all your users are stored under a single node in the directory. If instead you wished to configure an LDAP search filter to locate the user, you could use the following:

If used with the server definition above, this would perform a search under the DN ou=people,dc=springframework,dc=org using the value of the user-search-filter attribute as a filter. Again the user login name is substituted for the parameter in the filter name. If user-search-base isn't supplied, the search will be performed from the root.

You may want to read through the content regarding LDAP Authentication (Chapter 18 in Spring 3.x Documentation).  There may be other information you find useful.


问:
react: uncaught TypeError: Cannot read property 'state' of undefined
I am trying to get 'state' object in function Application which is out from General class and I am getting this error "Uncaught TypeError: Cannot read property 'state' of undefined".
  The code is</p>

```<code>class General extends Comment {
  constructor() {
    super();
    this.state = { comments: first_comment};
  }
}

const Application = () => {
  return (
    <div> Hello world beginner: {this.state.comments}</div>
  );
};

render(<Application/>, document.getElementById('container'));
</code>```

答:
Few Things:

*Stateless Functional Components don't have state, lifecycle methods, and this keyword.

*You need to connect General and Application component so that Application component can you the state value of General component.

*Make Application component as child of General component and pass the comments value in props, and in Application access the value by props.comments.

Write it like this:

```<code>class General extends Component {
  constructor() {
    super();
    this.state = { comments: first_comment};
  }
  render(){
     return (
        <div>
            <Application comments={this.state.comments}/>
        </div>
     )
  }
}

const Application = (props) => {
  return (
    <div> Hello world beginner: {props.comments}</div>
  );
};

render(<General/>, document.getElementById('container'));
</code>```

Check the working example:

class General extends React.Component {
      constructor() {
        super();
        this.state = { comments: 'first_comment'};
      }
      render(){
         return (

                <Application comments={this.state.comments}/>

         )
      }
    }

    const Application = (props) => {
      return (

 Hello world beginner: {props.comments}

      );
    };

    ReactDOM.render(<General/>, document.getElementById('container'));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='container'/></code>```

Body:
I am trying to get 'state' object in function Application which is out from General class and I am getting this error "Uncaught TypeError: Cannot read property 'state' of undefined".
  The code is

class General extends Comment {
  constructor() {
    super();
    this.state = { comments: first_comment};
  }
}

const Application = () => {
  return (

 Hello world beginner: {this.state.comments}

  );
};

render(<Application/>, document.getElementById('container'));

Body:
Few Things:

*Stateless Functional Components don't have state, lifecycle methods, and this keyword.

*You need to connect General and Application component so that Application component can you the state value of General component.

*Make Application component as child of General component and pass the comments value in props, and in Application access the value by props.comments.

Write it like this:

class General extends Component {
  constructor() {
    super();
    this.state = { comments: first_comment};
  }
  render(){
     return (
        <div>
            <Application comments={this.state.comments}/>
        </div>
     )
  }
}

const Application = (props) => {
  return (
    <div> Hello world beginner: {props.comments}</div>
  );
};

render(<General/>, document.getElementById('container'));

Check the working example:

class General extends React.Component {
      constructor() {
        super();
        this.state = { comments: 'first_comment'};
      }
      render(){
         return (
            <div>
                <Application comments={this.state.comments}/>
            </div>
         )
      }
    }

    const Application = (props) => {
      return (
        <div> Hello world beginner: {props.comments}</div>
      );
    };

    ReactDOM.render(<General/>, document.getElementById('container'));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='container'/>


问:
How can I insert a character after every 2 characters?
I want to insert a slash after every two characters, but just for the first two instances. The following regex inserts after every occurrence. Does anyone know how to limit it to two occurrences? The amount will be entered by the user through an input element. So if a user entered 30032017 it would be something like the following.

```<code>function insertSlash(val) {
    return val.match(new RegExp('.{1,2}', 'g')).join("/");
}

insertSlash(input);
</code>```

so for the first character the user would enter 3. On the next input it will be 0. this should then insert a slash.

this should then return 30/03/2017.

答:
There are a couple of ways you can do this, you can use a regex formatted just for this type of string

function insertSlash(val) {
  return val.replace(/^(\d{2})(\d{2})/, '$1/$2/');
}

console.log(insertSlash('30032017'));```
</div>
</div>
</p>

<p>Or you can use a simple replace function to keep track of replace counts</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function insertSlash(val) {
  var count = 2;
  var i = 0;
  return val.replace(/(\d{2})/g, function(match, capture) {
    return (i++ < count) ? capture + '/' : capture;
  });
}

console.log(insertSlash('30032017'));</code>```

EDIT

It looks like you've edited your question to include the need for this to happen as the user types. There are mask plugins for this that take into account caret placement, placeholder information, and it would probably be worth your time to check some of them out. Here is one that I found that has a react JS component for it. I can't vouch for it, I've never used it, but it is an idea for something to look at.

Body:
I want to insert a slash after every two characters, but just for the first two instances. The following regex inserts after every occurrence. Does anyone know how to limit it to two occurrences? The amount will be entered by the user through an input element. So if a user entered 30032017 it would be something like the following.

function insertSlash(val) {
    return val.match(new RegExp('.{1,2}', 'g')).join("/");
}

insertSlash(input);

so for the first character the user would enter 3. On the next input it will be 0. this should then insert a slash.

this should then return 30/03/2017.

Body:
There are a couple of ways you can do this, you can use a regex formatted just for this type of string

function insertSlash(val) {
  return val.replace(/^(\d{2})(\d{2})/, '$1/$2/');
}

console.log(insertSlash('30032017'));

Or you can use a simple replace function to keep track of replace counts

function insertSlash(val) {
  var count = 2;
  var i = 0;
  return val.replace(/(\d{2})/g, function(match, capture) {
    return (i++ < count) ? capture + '/' : capture;
  });
}

console.log(insertSlash('30032017'));

EDIT

It looks like you've edited your question to include the need for this to happen as the user types. There are mask plugins for this that take into account caret placement, placeholder information, and it would probably be worth your time to check some of them out. Here is one that I found that has a react JS component for it. I can't vouch for it, I've never used it, but it is an idea for something to look at.


问:
Xcode - Cannot disable indexing
I have been fighting this for a about a week now. I CANNOT get indexing to disable in Xcode. Has anyone else ever experienced this? The following command has zero effect:

defaults write com.apple.dt.XCode IDEIndexDisable 1

I relaunch Xcode after issuing this via terminal (as root) and when I re-open xcode, projects attempt to index. I have repaired permissions on the machine and upgraded to the latest xcode to no avail. Its driving me crazy as I am taking a huge hit in performance due to indexing on a very large project. Any help would be greatly appreciated.

答:
These are the steps I used to edit the com.apple.dt.XCode.plist file:

1 Open the file in XCode (but don't save it)

2 Edit the file by adding a new property called IDEIndexDisable, with type Boolean and value set to YES (to add a new property tap on the + button on the first property underneath Root node)

3 Export the file under a new filename in same directory, ex. myfile.plist under ~/Library/Preferences/

4 Quit XCode

5 Create a backup of the original com.apple.dt.XCode.plist file (in case something goes wrong you can revert to this file -- always a good practice)

6 Rename/copy the exported file to the original filename, ex. in Terminal do

% mv myfile.plist com.apple.dt.XCode.plist

7 Reopen XCode, you should now not have indexing

Title: Xcode - Cannot disable indexing


问:
To access tinymce iframe elements through jquery
I an using Tinymce Editor. In need to access tinymce iframe with jquery
I had tried...

```<code>var iframe = $('#comment_ifr')[0];//document.getElementById('comment_ifr');// or $('#comment_ifr')[0]; the other is just faster.
alert(iframe);
var doc = iframe.document || iframe.contentDocument || iframe.contentWindow && iframe.contentWindow.document || null;
   //if( !doc ) return;
   //and now jquery

$( "img", doc ).click(function() {
    alert('image clicked');
   });

----------
</code>```

In my above code once an image inserted in tinymce iframe. Once i click that image i need to trigger an event. Help me.

答:
Try:</p>

```<code>$("#comment_ifr").contents().filter("img").click(function() {
    alert('clicked');
});
</code>```

Body:
I an using Tinymce Editor. In need to access tinymce iframe with jquery
I had tried...

var iframe = $('#comment_ifr')[0];//document.getElementById('comment_ifr');// or $('#comment_ifr')[0]; the other is just faster.
alert(iframe);
var doc = iframe.document || iframe.contentDocument || iframe.contentWindow && iframe.contentWindow.document || null;
   //if( !doc ) return;
   //and now jquery

$( "img", doc ).click(function() {
    alert('image clicked');
   });

----------

In my above code once an image inserted in tinymce iframe. Once i click that image i need to trigger an event. Help me.

Body:
Try:

$("#comment_ifr").contents().filter("img").click(function() {
    alert('clicked');
});


问:
Retrieving two values from each line of a text document
I am trying to get the contents from a file, the ping result and the description. The everything through pinging works, but I how do I get the description in my output?

```<code>GC D:\Temp\System.txt | %{
    If (Test-Connection $_ -Quiet -Count 2){
        Write-Host "$_ is UP" -b Green
    }
    Else{
        Write-Host "$_ is Down" -b Red
    }
}
PAUSE
</code>```

Content with IP addresses to ping and their descriptions

```<code>10.200.11.2     Firewall
10.200.11.14    Test1
192.168.254.81  Test2
192.168.254.133 Test3
</code>```

答:
Use regular expressions, ($_ -replace "\s.+","") - All that up to the space (tabulation)
($_ -replace ".+\s","") - All that after a space (tabulation)

```<code>  GC D:\Temp\System.txt | %{
If (Test-Connection ($_ -replace "\s.+","") -Quiet -Count 2){
    Write-Host "$_ is UP" -b Green
    Write-Host ($_ -replace ".+\s","")
}
Else{
    Write-Host "$_ is Down" -b Red
    Write-Host ($_ -replace ".+\s","")
}
</code>```

String Write-Host ($_ -replace ".+\s","") are descriptions

Body:
I am trying to get the contents from a file, the ping result and the description. The everything through pinging works, but I how do I get the description in my output?

GC D:\Temp\System.txt | %{
    If (Test-Connection $_ -Quiet -Count 2){
        Write-Host "$_ is UP" -b Green
    }
    Else{
        Write-Host "$_ is Down" -b Red
    }
}
PAUSE

Content with IP addresses to ping and their descriptions

10.200.11.2     Firewall
10.200.11.14    Test1
192.168.254.81  Test2
192.168.254.133 Test3

Body:
Use regular expressions, ($_ -replace "\s.+","") - All that up to the space (tabulation)
($_ -replace ".+\s","") - All that after a space (tabulation)

  GC D:\Temp\System.txt | %{
If (Test-Connection ($_ -replace "\s.+","") -Quiet -Count 2){
    Write-Host "$_ is UP" -b Green
    Write-Host ($_ -replace ".+\s","")
}
Else{
    Write-Host "$_ is Down" -b Red
    Write-Host ($_ -replace ".+\s","")
}

String Write-Host ($_ -replace ".+\s","") are descriptions


问:
Configure Solr to reject index/update requests with later timestamp (in the document)
While replaying documents (to cover for indexing holes), it is possible for my solr server to receive indexing reqests from two sources at the same time; and one of those sources will have an older copy of the document. I have lastModified timestamp in my solr documents. How can I use it to skip indexing the document if its recent copy has already been indexed (by the other stream)?

I am considering to modify UpdateHandler and read the document before indexing (when more than one indexing 'streams' are in progress). I am not sure if this is a viable approach.

答: You can use your timestamps with DocBasedVersionConstraintsProcessorFactory and ignoreOldUpdates set. That seems to match your use-case exactly, as described in the Solr Reference Guide.</p>


问:
AutoFlushWrapper with Mail target
I'm trying to send myself an email with the latest log entries when an error occurs. But I don't want to receive any mail unless an actual ERROR-level entry have been logged, so I've set the bufferSize to a big number. My problem is, the mail target isn't being triggered when the ERROR-level entry is logged, only when the actual bufferSize is hit, meaning I'm not receiving any mails at all since the bufferSize is so big. My NLog.config up like this:

<targets>
  <target name="mailautoflush" xsi:type="AutoFlushWrapper" condition="level >= LogLevel.Error">
    <target name="mailbuffer" xsi:type="BufferingWrapper" bufferSize="1000000">
      <target name="mail" xsi:type="Mail" ... />
    </target>
  </target>
</targets>
<rules>
    <logger name="*" minlevel="Info" writeTo="mailautoflush"></logger>
</rules>
```

What am I doing wrong? Also, is there a better way to do this? Using the AutoFlushWrapper/BufferingWrapper trick seems like a hack. Thanks!

答:
You code looks valid.

Also, is there a better way to do this? Using the AutoFlushWrapper/BufferingWrapper trick seems like a hack. Thanks!

It's more like a modular design - you can combine blocks with each other.

Title: AutoFlushWrapper with Mail target

Body:
I'm trying to send myself an email with the latest log entries when an error occurs. But I don't want to receive any mail unless an actual ERROR-level entry have been logged, so I've set the bufferSize to a big number. My problem is, the mail target isn't being triggered when the ERROR-level entry is logged, only when the actual bufferSize is hit, meaning I'm not receiving any mails at all since the bufferSize is so big. My NLog.config up like this:

<targets>
  <target name="mailautoflush" xsi:type="AutoFlushWrapper" condition="level >= LogLevel.Error">
    <target name="mailbuffer" xsi:type="BufferingWrapper" bufferSize="1000000">
      <target name="mail" xsi:type="Mail" ... />
    </target>
  </target>
</targets>
<rules>
    <logger name="*" minlevel="Info" writeTo="mailautoflush"></logger>
</rules>

What am I doing wrong? Also, is there a better way to do this? Using the AutoFlushWrapper/BufferingWrapper trick seems like a hack. Thanks!


问:
Firebase Storage Web: How to upload a file
I added the following function to my website. I am using Firebase Storage but for some reason it seems as if it is not working and I have no idea why.

When you upload a file the progress bar should  show the progress of saving/uploading the file to Firebase Storage but that is not the case. Firebase has been initialized and I know it works.

I would greatly appreciate if someone could help me and tell me why the function is not working as described above and how to fix it.

```<code>function AddMed() {
        var uploader = document.getElementById("uploader");
    var fileButton = document.getElementById("fileButton");
    var email = sessionStorage.getItem("email");
  //Listen for file selection

    fileButton.addEventListener('change', function (e) {
    // Get File
        var file = e.target.files[0];
    //Create a storage ref

        var storageRef = firebase.storage().ref('file/' + file.name);
    /** folder name will be email,
    Will have to transfer variable from page to page and files will be .jpeg**/
    //Upload file

        var task = storageRef.put(file);
    //Update progress bar

        task.on('state_changed',
                function progress(snapshot) {
                var percentage = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
                uploader.value = percentage;
            },
            function complete() {

                    });
    });

}
</code>```

答:
First change the security Rules

service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write: if request.auth == null;
    }
  }
}```
</div>
</div>
</p>

<ol start="2">
<li>Create a file</li>
</ol>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
 <title>Firebase Web Basics</title>

 <link href="https://fonts.googleapis.com/css?family=Raleway:300,400,500,700" rel="stylesheet">

 <script src="https://use.fontawesome.com/939e9dd52c.js"></script>

 <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>

 <div class="mainDiv" align="right">
  <h1 align="left">Firebase File Upload</h1>
  <progress id="uploader" value="0" max="100">0%</progress>
  <input type="file" id="fileButton" value="upload"/>
 </div>

<script src="https://www.gstatic.com/firebasejs/3.7.4/firebase.js"></script>
<script>
  // Initialize Firebase
  var config = {
    apiKey: "******************************",
    authDomain: "******************************",
    databaseURL: "******************************",
    storageBucket: "******************************",
    messagingSenderId: "******************************"
  };
  firebase.initializeApp(config);
  //-------------------------------------

  var uploader = document.getElementById('uploader');
  var fileButton =         document.getElementById('fileButton');
  fileButton.addEventListener('change', function(e){
  var file = e.target.files[0];
  var storageRef = firebase.storage().ref('img/'+file.name);
  var task = storageRef.put(file);
  task.on('state_changed', function progress(snapshot) {
    var percentage = (snapshot.bytesTransferred/snapshot.totalBytes)*100;
    uploader.value = percentage;

  }, function error(err) {

  },function complete() {

  });
});

</script>

<script src="fileup.js">
</script>
</body>
</html></code>```

Body:
I added the following function to my website. I am using Firebase Storage but for some reason it seems as if it is not working and I have no idea why.

When you upload a file the progress bar should  show the progress of saving/uploading the file to Firebase Storage but that is not the case. Firebase has been initialized and I know it works.

I would greatly appreciate if someone could help me and tell me why the function is not working as described above and how to fix it.

function AddMed() {
        var uploader = document.getElementById("uploader");
    var fileButton = document.getElementById("fileButton");
    var email = sessionStorage.getItem("email");
  //Listen for file selection

    fileButton.addEventListener('change', function (e) {
    // Get File
        var file = e.target.files[0];
    //Create a storage ref

        var storageRef = firebase.storage().ref('file/' + file.name);
    /** folder name will be email,
    Will have to transfer variable from page to page and files will be .jpeg**/
    //Upload file

        var task = storageRef.put(file);
    //Update progress bar

        task.on('state_changed',
                function progress(snapshot) {
                var percentage = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
                uploader.value = percentage;
            },
            function complete() {

                    });
    });

}

Body:
First change the security Rules

service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write: if request.auth == null;
    }
  }
}

Create a file

<!DOCTYPE html>
<html>
<head>
 <title>Firebase Web Basics</title>

 <link href="https://fonts.googleapis.com/css?family=Raleway:300,400,500,700" rel="stylesheet">

 <script src="https://use.fontawesome.com/939e9dd52c.js"></script>

 <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>

 <div class="mainDiv" align="right">
  <h1 align="left">Firebase File Upload</h1>
  <progress id="uploader" value="0" max="100">0%</progress>
  <input type="file" id="fileButton" value="upload"/>
 </div>

<script src="https://www.gstatic.com/firebasejs/3.7.4/firebase.js"></script>
<script>
  // Initialize Firebase
  var config = {
    apiKey: "******************************",
    authDomain: "******************************",
    databaseURL: "******************************",
    storageBucket: "******************************",
    messagingSenderId: "******************************"
  };
  firebase.initializeApp(config);
  //-------------------------------------

  var uploader = document.getElementById('uploader');
  var fileButton =         document.getElementById('fileButton');
  fileButton.addEventListener('change', function(e){
  var file = e.target.files[0];
  var storageRef = firebase.storage().ref('img/'+file.name);
  var task = storageRef.put(file);
  task.on('state_changed', function progress(snapshot) {
    var percentage = (snapshot.bytesTransferred/snapshot.totalBytes)*100;
    uploader.value = percentage;

  }, function error(err) {

  },function complete() {

  });
});

</script>

<script src="fileup.js">
</script>
</body>
</html>


问:
Efficiently count the number of bits in an integer in JavaScript
Let's say I have an integer I and want to get the count of 1s in its binary form.

I am currently using the following code.

```<code>Number(i.toString(2).split("").sort().join("")).toString().length;
</code>```

Is there a faster way to do this? I am thinking about using bitwise operators.  Any thoughts?

NOTE: i is within the 32-bit limitation.

答:
Given that you're creating, sorting, and joining an array, if it's literally faster you want, you're probably better off doing it the boring way:

console.log(countOnes(8823475632));

function countOnes(i) {
  var str = i.toString(2);
  var n;
  var count = 0;
  for (n = 0; n < str.length; ++n) {
    if (str[n] === "1") {
      ++count;
    }
  }
  return count;
}```

(Use str.charAt(n) instead of str[n] if you need to support obsolete browsers.)

It's not as l33t or concise, but <s>I bet it's faster</s> it's much faster:

...and similarly on Firefox, IE11 (IE11 to a lesser degree).

Body:
Let's say I have an integer I and want to get the count of 1s in its binary form.

I am currently using the following code.

Number(i.toString(2).split("").sort().join("")).toString().length;

Is there a faster way to do this? I am thinking about using bitwise operators.  Any thoughts?

NOTE: i is within the 32-bit limitation.

Body:
Given that you're creating, sorting, and joining an array, if it's literally faster you want, you're probably better off doing it the boring way:

console.log(countOnes(8823475632));

function countOnes(i) {
  var str = i.toString(2);
  var n;
  var count = 0;
  for (n = 0; n < str.length; ++n) {
    if (str[n] === "1") {
      ++count;
    }
  }
  return count;
}

(Use str.charAt(n) instead of str[n] if you need to support obsolete browsers.)

It's not as l33t or concise, but <s>I bet it's faster</s> it's much faster:

...and similarly on Firefox, IE11 (IE11 to a lesser degree).


问:
c# trying to do cmd command for firewall port opening - sql ports
i'm new and need some help. I'm trying to do button who will open sql ports. i have this code but cant open the ports in inbound rules.</p>

```<code>private void addPorts_Click(object sender, EventArgs e)
        {
            System.Diagnostics.ProcessStartInfo myProcessInfo = new System.Diagnostics.ProcessStartInfo(); //Initializes a new ProcessStartInfo of name myProcessInfo
            myProcessInfo.FileName = Environment.ExpandEnvironmentVariables("%SystemRoot%") + @"\System32\cmd.exe"; //Sets the FileName property of myProcessInfo to %SystemRoot%\System32\cmd.exe where %SystemRoot% is a system variable which is expanded using Environment.ExpandEnvironmentVariables
            myProcessInfo.Arguments = @"netsh advfirewall firewall add rule name= ""Open Port 80"" dir=in action=allow protocol=TCP localport=80

@echo ========= SQL Server Ports  ===================
@echo Enabling SQLServer default instance port 1433
netsh advfirewall firewall add rule name = "" SQL Server"" dir =in action = allow protocol = TCP localport = 1433
@echo Enabling Dedicated Admin Connection port 1434
netsh advfirewall firewall add rule name = ""SQL Admin Connection"" dir =in action = allow protocol = TCP localport = 1434
@echo Enabling Conventional SQL Server Service Broker port 4022
netsh advfirewall firewall add rule name = ""SQL Service Broker"" dir =in action = allow protocol = TCP localport = 4022
@echo Enabling Transact SQL/ RPC port 135
netsh advfirewall firewall add rule name = ""SQL Debugger/RPC"" dir =in action = allow protocol = TCP localport = 135
@echo ========= Analysis Services Ports  ==============
@echo Enabling SSAS Default Instance port 2383
netsh advfirewall firewall add rule name = ""Analysis Services"" dir =in action = allow protocol = TCP localport = 2383
@echo Enabling SQL Server Browser Service port 2382
netsh advfirewall firewall add rule name = ""SQL Browser"" dir =in action = allow protocol = TCP localport = 2382

@echo ========= Misc Applications ==============
@echo Enabling HTTP port 80
netsh advfirewall firewall add rule name = ""HTTP"" dir =in action = allow protocol = TCP localport = 80
@echo Enabling SSL port 443
netsh advfirewall firewall add rule name = ""SSL"" dir =in action = allow protocol = TCP localport = 443
@echo Enabling port for SQL Server Browser Service's 'Browse' Button
netsh advfirewall firewall add rule name = ""SQL Browser"" dir =in action = allow protocol = UDP localport = 1434
@echo Allowing multicast broadcast response on UDP(Browser Service Enumerations OK)
netsh firewall set multicastbroadcastresponse ENABLE";
            myProcessInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; //Sets the WindowStyle of myProcessInfo which indicates the window state to use when the process is started to Hidden
            myProcessInfo.Verb = "runas"; //The process should start with elevated permissions
            System.Diagnostics.Process.Start(myProcessInfo); //Starts the process based on myProcessInfo
        }
</code>```

答:
```<code>private void addPorts_Click(object sender, EventArgs e)
        {
            Process process = new Process();
            process.StartInfo.FileName = "cmd.exe";
            process.StartInfo.CreateNoWindow = true;
            process.StartInfo.RedirectStandardInput = true;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.UseShellExecute = false;
            process.Start();
            process.StandardInput.WriteLine(@"
@echo Enabling SQLServer default instance port 1433
netsh advfirewall firewall add rule name =""SQLServer"" dir =in action = allow protocol = TCP localport = 1433
@echo Enabling Dedicated Admin Connection port 1434");
            process.StandardInput.Flush();
            process.StandardInput.Close();
            process.WaitForExit();
            Console.WriteLine(process.StandardOutput.ReadToEnd());
            //Console.ReadKey();
            MessageBox.Show("Succesful!", "Succesful!", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
</code>```

Body:
i'm new and need some help. I'm trying to do button who will open sql ports. i have this code but cant open the ports in inbound rules.

private void addPorts_Click(object sender, EventArgs e)
        {
            System.Diagnostics.ProcessStartInfo myProcessInfo = new System.Diagnostics.ProcessStartInfo(); //Initializes a new ProcessStartInfo of name myProcessInfo
            myProcessInfo.FileName = Environment.ExpandEnvironmentVariables("%SystemRoot%") + @"\System32\cmd.exe"; //Sets the FileName property of myProcessInfo to %SystemRoot%\System32\cmd.exe where %SystemRoot% is a system variable which is expanded using Environment.ExpandEnvironmentVariables
            myProcessInfo.Arguments = @"netsh advfirewall firewall add rule name= ""Open Port 80"" dir=in action=allow protocol=TCP localport=80

@echo ========= SQL Server Ports  ===================
@echo Enabling SQLServer default instance port 1433
netsh advfirewall firewall add rule name = "" SQL Server"" dir =in action = allow protocol = TCP localport = 1433
@echo Enabling Dedicated Admin Connection port 1434
netsh advfirewall firewall add rule name = ""SQL Admin Connection"" dir =in action = allow protocol = TCP localport = 1434
@echo Enabling Conventional SQL Server Service Broker port 4022
netsh advfirewall firewall add rule name = ""SQL Service Broker"" dir =in action = allow protocol = TCP localport = 4022
@echo Enabling Transact SQL/ RPC port 135
netsh advfirewall firewall add rule name = ""SQL Debugger/RPC"" dir =in action = allow protocol = TCP localport = 135
@echo ========= Analysis Services Ports  ==============
@echo Enabling SSAS Default Instance port 2383
netsh advfirewall firewall add rule name = ""Analysis Services"" dir =in action = allow protocol = TCP localport = 2383
@echo Enabling SQL Server Browser Service port 2382
netsh advfirewall firewall add rule name = ""SQL Browser"" dir =in action = allow protocol = TCP localport = 2382

@echo ========= Misc Applications ==============
@echo Enabling HTTP port 80
netsh advfirewall firewall add rule name = ""HTTP"" dir =in action = allow protocol = TCP localport = 80
@echo Enabling SSL port 443
netsh advfirewall firewall add rule name = ""SSL"" dir =in action = allow protocol = TCP localport = 443
@echo Enabling port for SQL Server Browser Service's 'Browse' Button
netsh advfirewall firewall add rule name = ""SQL Browser"" dir =in action = allow protocol = UDP localport = 1434
@echo Allowing multicast broadcast response on UDP(Browser Service Enumerations OK)
netsh firewall set multicastbroadcastresponse ENABLE";
            myProcessInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; //Sets the WindowStyle of myProcessInfo which indicates the window state to use when the process is started to Hidden
            myProcessInfo.Verb = "runas"; //The process should start with elevated permissions
            System.Diagnostics.Process.Start(myProcessInfo); //Starts the process based on myProcessInfo
        }


问:
Module Not found during import in Jupyter Notebook
I have the following package (and working directory):

```<code>WorkingDirectory--
                 |--MyPackage--
                 |            |--__init__.py
                 |            |--module1.py
                 |            |--module2.py
                 |
                 |--notebook.ipynb
</code>```

In __init__.py I have:

```<code>import module1
import module2
</code>```

If I try to import MyPackage into my notebook:

```<code>import MyPackage as mp
</code>```

I will get ModuleNotFoundError: No module named 'module1'. But import works fine if I execute the script outside a notebook: if I create test.py in the same directory and do the same as in the notebook the import would work properly. It will work inside the notebook if I use fully qualified name in __init__.py (import MyPackage.module1).

What's the reason for different import behavior?

I have confirmed the working directory of the notebook is WorkingDirectory.

---Update---------

Exact error is:

```<code>C:\Users\Me\Documents\Working Directory\MyPackage\__init__.py in <module>()
---> 17 import module1

ModuleNotFoundError: No module named 'module1'
</code>```

My problem differs from the possible duplicate:

The notebook was able to find the package, but only unable to load the module. This was inferred from substituting module1 with MyPackage.module1 worked well and suggests it may not be a problem related with PATH.

I cded into WorkingDirectory and started the server there. The working directory should be the folder containing my package.

答:
I'm pretty sure this issue is related and the answer there will help you: https://stackoverflow.com/a/15622021/7458681

tl;dr the cwd of the notebook server is always the base path where you started the server, no matter was running import os os.getcwd() says. Use import sys sys.path.append("/path/to/your/module/folder").

I ran it with some dummy modules in the same structure as you had specified, and before modifying sys.path it wouldn't run and after it would

Body:
I have the following package (and working directory):

WorkingDirectory--
                 |--MyPackage--
                 |            |--__init__.py
                 |            |--module1.py
                 |            |--module2.py
                 |
                 |--notebook.ipynb

In __init__.py I have:

import module1
import module2

If I try to import MyPackage into my notebook:

import MyPackage as mp

I will get ModuleNotFoundError: No module named 'module1'. But import works fine if I execute the script outside a notebook: if I create test.py in the same directory and do the same as in the notebook the import would work properly. It will work inside the notebook if I use fully qualified name in __init__.py (import MyPackage.module1).

What's the reason for different import behavior?

I have confirmed the working directory of the notebook is WorkingDirectory.

---Update---------

Exact error is:

C:\Users\Me\Documents\Working Directory\MyPackage\__init__.py in <module>()
---> 17 import module1

ModuleNotFoundError: No module named 'module1'

My problem differs from the possible duplicate:

The notebook was able to find the package, but only unable to load the module. This was inferred from substituting module1 with MyPackage.module1 worked well and suggests it may not be a problem related with PATH.

I cded into WorkingDirectory and started the server there. The working directory should be the folder containing my package.


问:
How do I use url-retrieve to update a hash map value in elisp?
I have a list of names that need to be validated through a web query. In order to do this manually I would enter a name into a search string, submit the string to the service, read the response and determine whether or not the name is valid. I am planning on performing this operation in batches of around 1000. My current struggle is retrieving the proper return value from the url-retrieve function.

```<code>(defvar *name-hash* (make-hash-table :test 'equal)) ;;Create Global Hash Table
(defun name-query (str)
  (let ((name-url "http://nameservice.com/x/namesearch?name=")
    (url-request-method "GET")
    (arg (url-hexify-string str))
    (retr-value (url-retrieve (concat name-url arg)
                       (lambda (status)(switch-to-buffer (current-buffer))
                     (if (search-forward "</name>" nil t);; if search result for name tag
                         (retr-value "FOUND")            ;; then return value
                       (retr-value "AVAILABLE"))))))     ;; else return value
    (puthash str retr-value *hostname-hash*)))           ;; populate hash table
</code>```

Example call

```<code>(name-query "myname")
</code>```

I expect the hash-table to be updated with a key-value pair similar to ("myname" "AVAILABLE"). Instead the hash-value is updated with something similar to

("myname" "#buffer    *http://nameservice.com/x/namesearch?name*-71829>")

How do I carry the results of the anonymous function's if statement into the puthash function?

答:
Construct a better function. Let's look at the steps required to solve the problem. They are:

declare a URL to call

build the full URL and set the request method

read the retrieved URL contents in a buffer

move the pointer to the beginning of the URL content buffer

search forward for a pattern (in my case an HTML tag works)

return the appropriate value (in my case FOUND or AVAILABLE)

update the hash map by setting the value equal to the if statement result

Below is elisp code that follows the above steps. In the original question I struggled with passing the name-query argument to the if statement. By moving the if statement up one level, the function's argument is available.

```<code>(defvar *name-hash* (make-hash-table :test 'equal)) ;;Create Global Hash Table
(defun name-query (str)
      (let ((name-url "http://nameservice.com/x/namesearch?name=")
        (url-request-method "GET")
        (url (concat name-url (url-hexify-string str))))
        (let ((download-buffer (url-retrieve-synchronously url)))
          (save-excursion
        (set-buffer download-buffer)
        (goto-char (point-min))
        (if (search-forward "</hostname>" nil t)
            (setf (gethash str *hostname-hash*) "FOUND")
          (setf (gethash str *hostname-hash*) "AVAILABLE"))))))
</code>```

Body:
I have a list of names that need to be validated through a web query. In order to do this manually I would enter a name into a search string, submit the string to the service, read the response and determine whether or not the name is valid. I am planning on performing this operation in batches of around 1000. My current struggle is retrieving the proper return value from the url-retrieve function.

(defvar *name-hash* (make-hash-table :test 'equal)) ;;Create Global Hash Table
(defun name-query (str)
  (let ((name-url "http://nameservice.com/x/namesearch?name=")
    (url-request-method "GET")
    (arg (url-hexify-string str))
    (retr-value (url-retrieve (concat name-url arg)
                       (lambda (status)(switch-to-buffer (current-buffer))
                     (if (search-forward "</name>" nil t);; if search result for name tag
                         (retr-value "FOUND")            ;; then return value
                       (retr-value "AVAILABLE"))))))     ;; else return value
    (puthash str retr-value *hostname-hash*)))           ;; populate hash table

Example call

(name-query "myname")

I expect the hash-table to be updated with a key-value pair similar to ("myname" "AVAILABLE"). Instead the hash-value is updated with something similar to

("myname" "#buffer    *http://nameservice.com/x/namesearch?name*-71829>")

How do I carry the results of the anonymous function's if statement into the puthash function?

Body:
Construct a better function. Let's look at the steps required to solve the problem. They are:

declare a URL to call

build the full URL and set the request method

read the retrieved URL contents in a buffer

move the pointer to the beginning of the URL content buffer

search forward for a pattern (in my case an HTML tag works)

return the appropriate value (in my case FOUND or AVAILABLE)

update the hash map by setting the value equal to the if statement result

Below is elisp code that follows the above steps. In the original question I struggled with passing the name-query argument to the if statement. By moving the if statement up one level, the function's argument is available.

(defvar *name-hash* (make-hash-table :test 'equal)) ;;Create Global Hash Table
(defun name-query (str)
      (let ((name-url "http://nameservice.com/x/namesearch?name=")
        (url-request-method "GET")
        (url (concat name-url (url-hexify-string str))))
        (let ((download-buffer (url-retrieve-synchronously url)))
          (save-excursion
        (set-buffer download-buffer)
        (goto-char (point-min))
        (if (search-forward "</hostname>" nil t)
            (setf (gethash str *hostname-hash*) "FOUND")
          (setf (gethash str *hostname-hash*) "AVAILABLE"))))))


问:
How to get "clientCustomerId" from Adwrods API in PHP with OAuth?
I am developing a Google Adwords app. I tried using the API libraries available in PHP. I found, I need "clientCustomerId" in "adsapi_php.ini". I don't see anyway to get this "clientCustomerId" using API with OAuth. Am I trying something wrong?</p>

答:
Try CustomerService

CustomerService provides information about your accounts. It has a
  getCustomers() method that takes no arguments and returns a list of
  Customer objects containing fields such as customerId, currencyCode,
  and dateTimeZone. CustomerService

Reference: Managing Accounts


问:
$formatters and $parsers not called in AngularJS 1.6.2

@version angularjs 1.6.2

I'm trying to do some formatters and parsers to have generic input/output for my really huge project.

The use case :

I have a custom component with ngModelController required on it, but when I use this component in my view with an attribute directive; which also requires ngModel to add $parser or $formatters; but when the value is changing into the component the $formatters or $parsers assign on it aren't called.

Te logic I would like

Component : ArtistSelect

Directive (parser) : ngObject ng-object-formatter="attribute_object" ng-object-parser="attribute_object"
View :

```<code><artist-select ng-model="model.artist" ng-object ng-object-formatter="id_artist"></artist-select>
</code>```

I would like the model.artist being formatted like : {id_artist: integer} instead of only an integer.

Angular doc : Note that the $parsers are not called when the bound
  ngModel expression changes programmatically.

also

Angular Doc : Since ng-model does not do a deep watch, $render() is only invoked if
  the values of $modelValue and $viewValue are actually different from
  their previous values. If $modelValue or $viewValue are objects
  (rather than a string or number) then $render() will not be invoked if
  you only change a property on the objects.

How to make it work ?

WORKING PLUNKER :  Behavior

Maybe I'm missing something, maybe I'm overthinking the the things or maybe It's just not possible to do.

Your help will be really appreciated !

答: I found out it was in my $doCheck(), I made a check which was never true.</p>

Body:
@version angularjs 1.6.2

I'm trying to do some formatters and parsers to have generic input/output for my really huge project.

The use case :

I have a custom component with ngModelController required on it, but when I use this component in my view with an attribute directive; which also requires ngModel to add $parser or $formatters; but when the value is changing into the component the $formatters or $parsers assign on it aren't called.

Te logic I would like

Component : ArtistSelect

Directive (parser) : ngObject ng-object-formatter="attribute_object" ng-object-parser="attribute_object"
View :

<artist-select ng-model="model.artist" ng-object ng-object-formatter="id_artist"></artist-select>

I would like the model.artist being formatted like : {id_artist: integer} instead of only an integer.

Angular doc : Note that the $parsers are not called when the bound
  ngModel expression changes programmatically.

also

Angular Doc : Since ng-model does not do a deep watch, $render() is only invoked if
  the values of $modelValue and $viewValue are actually different from
  their previous values. If $modelValue or $viewValue are objects
  (rather than a string or number) then $render() will not be invoked if
  you only change a property on the objects.

How to make it work ?

WORKING PLUNKER :  Behavior

Maybe I'm missing something, maybe I'm overthinking the the things or maybe It's just not possible to do.

Your help will be really appreciated !


问:
Does the order of fields in C# matter?
This question is inspired by Jon Skeet's answer:
Is there a c# equivalent to c++'s access-modifier regions

He makes a comment that it is possible for the order of fields in a file to matter. I am guessing that this has to do with the order that the fields are initialized, but I think it's a dangerous enough thing to code based on this side effect that it warranted its own question and discussion.

Are there other thoughts around how the order of fields within your code file could be manipulated and what impact that might have?

答: If fields are initialized as part of the declaration, they are added to the constructor (instance or static) in the order they appear in the file. </p>

OwnerDisplayName: Josh

Title: Does the order of fields in C# matter?

LastEditorDisplayName: Mehrdad Afshari

OwnerDisplayName: Brian Rasmussen


问:
.NET object size limit
It seems there is a 2 GB size limit for objects in .NET: How to run Fsi.exe in 64 Bits?

Is there a work around this? I would like to load a very large float array (10 GB) in memory and then do some work.

答:
I don't think there is an easy workaround for this, it seems to me there could be difficulties implementing a heap without a 2Gb limit on object size.

Maybe you would be better breaking the data up some how.  It should be possible to write a class that behave like an array but splits the data up into fixed sized chunks under the hood.

ContentLicense: CC BY-SA 4.0

Title: .NET object size limit


问:
How to pass the repeat count to x command in GDB
The x command can examine memory in GDB. Like

```<code>x/4xg 0x60400
</code>```

Now I am going to define my own x comand which examines memory with specified repeat count, like:

```<code>define myXCommand
    set var &repeatCount=$arg0
    x/(???)xg 0x60400
end
</code>```

I have tried many ways to pass the variant repeatCount to x command, but I failed finally. My problem is how to pass the repeat count to x command? Appreciated very much if anyone can help.

答:
A convenience variable can be used in most expressions, but the x command only allows the repeat count to be a string of digits, not an arbitrary expression.

What you can do is use the eval command, which does a printf on its arguments and then runs the result as a command.

```<code>define myXCommand
    set var $repeatCount=$arg0
    eval "x/%dxg 0x60400", $repeatCount
end
</code>```

Body:
The x command can examine memory in GDB. Like

x/4xg 0x60400

Now I am going to define my own x comand which examines memory with specified repeat count, like:

define myXCommand
    set var &repeatCount=$arg0
    x/(???)xg 0x60400
end

I have tried many ways to pass the variant repeatCount to x command, but I failed finally. My problem is how to pass the repeat count to x command? Appreciated very much if anyone can help.

Body:
A convenience variable can be used in most expressions, but the x command only allows the repeat count to be a string of digits, not an arbitrary expression.

What you can do is use the eval command, which does a printf on its arguments and then runs the result as a command.

define myXCommand
    set var $repeatCount=$arg0
    eval "x/%dxg 0x60400", $repeatCount
end