问:
What is wrong with my Factorial Function logic?
I'm trying to get a factorial number in the JS console in Chrome.

Obviously, there is something wrong with my understanding of the for loop, and I'd like to know what part of it is not logical to me.

Thank you very much for answers <3

```<code>var newX

function factorial(x) {
    if(x > 0){
        for(i = 1;i <= x;i++){
            var newX = x * i ;
} return newX;
};
};
</code>```

答:
writing var newX in loop means making new variable every time till loop is executing and another thing is you are multiplying x*i but it should be newX *=  i to satisfy the condition of factorial (i.e every time you have to multiply the result with next number ).</p>

```<code>var newX=1;
function factorial(x) {    if(x > 0){
 for(i = 1;i <= x;i++){ newX *=  i ;
} return newX;  }; };
</code>```

Body:
I'm trying to get a factorial number in the JS console in Chrome.

Obviously, there is something wrong with my understanding of the for loop, and I'd like to know what part of it is not logical to me.

Thank you very much for answers <3

var newX

function factorial(x) {
    if(x > 0){
        for(i = 1;i <= x;i++){
            var newX = x * i ;
} return newX;
};
};

Body:
writing var newX in loop means making new variable every time till loop is executing and another thing is you are multiplying x*i but it should be newX *=  i to satisfy the condition of factorial (i.e every time you have to multiply the result with next number ).

var newX=1;
function factorial(x) {    if(x > 0){
 for(i = 1;i <= x;i++){ newX *=  i ;
} return newX;  }; };


来源: stackexchange

问:
PHPUNIT Mocking method to accept any parameter
I use simple-phpunit from phpunit/phpunit-bridge by and with Symfony here.

I have a class A, that I desire to test, which uses a class B method in it.

While mocking the B and it's method I realise it is called multiple time and with multiple parameters : a class name and a integer.
I use returnValueMap() for this but have a problem : PHPUNIT seem to require that I precisely set the parameters, to their exact value when the method shall be called.
I can set the class name ( there are a given possible number fo them , so I can set them manually) but the given integer is arbitrary ( and the method is called in a loop ) , therefore I cannot set it precisely.

Is it possible to tell PHPUNIT to accept any parameter to this function ?
Like a anyParameter() method ( that I did not find after scouring the TestCase file ).

If I set the Integer parameter to a fixed value in the test and the class method, the test pass ( but of course I can't set the Integer as a fixed value in the class method ).

```<code>class ToBeTested{
     public $objectB;
     public function functionToTest($dataList){
        ......
        $objectB=new ObjectB();
        foreach($dataList as $data){
            $className=$data['className'];
            $integerNeeded=$data['integer'];
            //Here if $inetegerNeeded is not the exact value set in the Mock
            //$result will be null
            $result=$this->objectB->doSomething($className,$integerNeeded);
            if($result == null) throw new \Excpetion(" Object is null");
        }
        .....
     }
}
</code>```

```<code>class UnitTest extends TestCase{
       /**
         $generatedDataList comes from a DataProvider
          with some varied and exotic data close to real use cases
       **/
       public function testFunction($generatedDataList)
       {
           $mockOfObjectB= $this->getMockBuilder(ObjectB::class)
                 ->getMock();
          /**
      Here I'd like to use $this->anyParameter() or something that'd work that      way
      If I set this to a fixed value here and in the functionToTest() method it   passes
          **/
           $anyInteger=-1;
           $dataReferenceMap= [
              ['ClassNameA',$anyInteger,new MockObject()],
              ['ClassNameB',$anyInteger,new MockObject()],
              ['ClassNameC',$anyInteger,new MockObject()],
           ];
           $mockOfObjectB
            ->expects($this->any())
            ->method('doSomething')
            ->will($this->returnValueMap($dataReferenceMap));
            $objectToTest = new ToBeTested();
            $objectToTest->objectB=$mockOfObjectB;

            //DO THE TESTING - will because of the parameter Fail
            $objectToTest->functionToTest($generatedDataList);
          }
    }
}
</code>```

Might I also be wrongly returnValueMap() ?

It's quite new to me and I think the docs on it are pretty scarce and don't explain really well how to use it.

答:
I would go with willReturnCallback. Here is the example (checked with phpunit 8.1)

```<code><?php

declare(strict_types = 1);

use PHPUnit\Framework\TestCase;

final class SomeTest extends TestCase
{
    public function testSome()
    {
        $mock = $this
            ->getMockBuilder(\stdClass::class)
            ->setMethods(['doSomething'])
            ->getMock();
        $mock->method('doSomething')
            ->willReturnCallback(
                function (string $classname, int $int) {
                    $map = [
                    'ClassNameA' => 123,
                    'ClassNameB' => 345,
                    // ...
                    ];
                    return $map[$classname];
                }
            );
        $this->assertSame(123, $mock->doSomething('ClassNameA', 1));
        $this->assertSame(123, $mock->doSomething('ClassNameA', 1111111));
        $this->assertSame(345, $mock->doSomething('ClassNameB', 13456));
        $this->assertSame(345, $mock->doSomething('ClassNameB', 999999));
    }
}
</code>```

It is a shortcut for ->will($this->returnCallback(...)). The doc

ContentLicense: CC BY-SA 4.0

Body:
I use simple-phpunit from phpunit/phpunit-bridge by and with Symfony here.

I have a class A, that I desire to test, which uses a class B method in it.

While mocking the B and it's method I realise it is called multiple time and with multiple parameters : a class name and a integer.
I use returnValueMap() for this but have a problem : PHPUNIT seem to require that I precisely set the parameters, to their exact value when the method shall be called.
I can set the class name ( there are a given possible number fo them , so I can set them manually) but the given integer is arbitrary ( and the method is called in a loop ) , therefore I cannot set it precisely.

Is it possible to tell PHPUNIT to accept any parameter to this function ?
Like a anyParameter() method ( that I did not find after scouring the TestCase file ).

If I set the Integer parameter to a fixed value in the test and the class method, the test pass ( but of course I can't set the Integer as a fixed value in the class method ).

class ToBeTested{
     public $objectB;
     public function functionToTest($dataList){
        ......
        $objectB=new ObjectB();
        foreach($dataList as $data){
            $className=$data['className'];
            $integerNeeded=$data['integer'];
            //Here if $inetegerNeeded is not the exact value set in the Mock
            //$result will be null
            $result=$this->objectB->doSomething($className,$integerNeeded);
            if($result == null) throw new \Excpetion(" Object is null");
        }
        .....
     }
}

class UnitTest extends TestCase{
       /**
         $generatedDataList comes from a DataProvider
          with some varied and exotic data close to real use cases
       **/
       public function testFunction($generatedDataList)
       {
           $mockOfObjectB= $this->getMockBuilder(ObjectB::class)
                 ->getMock();
          /**
      Here I'd like to use $this->anyParameter() or something that'd work that      way
      If I set this to a fixed value here and in the functionToTest() method it   passes
          **/
           $anyInteger=-1;
           $dataReferenceMap= [
              ['ClassNameA',$anyInteger,new MockObject()],
              ['ClassNameB',$anyInteger,new MockObject()],
              ['ClassNameC',$anyInteger,new MockObject()],
           ];
           $mockOfObjectB
            ->expects($this->any())
            ->method('doSomething')
            ->will($this->returnValueMap($dataReferenceMap));
            $objectToTest = new ToBeTested();
            $objectToTest->objectB=$mockOfObjectB;

            //DO THE TESTING - will because of the parameter Fail
            $objectToTest->functionToTest($generatedDataList);
          }
    }
}

Might I also be wrongly returnValueMap() ?

It's quite new to me and I think the docs on it are pretty scarce and don't explain really well how to use it.

Body:
I would go with willReturnCallback. Here is the example (checked with phpunit 8.1)

<?php

declare(strict_types = 1);

use PHPUnit\Framework\TestCase;

final class SomeTest extends TestCase
{
    public function testSome()
    {
        $mock = $this
            ->getMockBuilder(\stdClass::class)
            ->setMethods(['doSomething'])
            ->getMock();
        $mock->method('doSomething')
            ->willReturnCallback(
                function (string $classname, int $int) {
                    $map = [
                    'ClassNameA' => 123,
                    'ClassNameB' => 345,
                    // ...
                    ];
                    return $map[$classname];
                }
            );
        $this->assertSame(123, $mock->doSomething('ClassNameA', 1));
        $this->assertSame(123, $mock->doSomething('ClassNameA', 1111111));
        $this->assertSame(345, $mock->doSomething('ClassNameB', 13456));
        $this->assertSame(345, $mock->doSomething('ClassNameB', 999999));
    }
}

It is a shortcut for ->will($this->returnCallback(...)). The doc


问:
How to split a Korean word into it's components?
So, for example the character 김 is made up of ㄱ, ㅣ and ㅁ. I need to split the Korean word into it's components to get the resulting 3 characters.

I tried by doing the following but it doesn't seem to output it correctly:

```<code>let str = "김"
let utf8 = str.utf8
let first:UInt8 = utf8.first!
let char = Character(UnicodeScalar(first))
</code>```

The problem is, that that code returns ê, when it should be returning ㄱ.

答:
You need to use the decomposedStringWithCompatibilityMapping string to get the unicode scalar values and then use those scalar values to get the characters. Something below,

```<code>let string = "김"
for scalar in string.decomposedStringWithCompatibilityMapping.unicodeScalars {
  print("\(scalar) ")
}
</code>```

Output:

```<code>ᄀ
ᅵ
ᆷ
</code>```

You can create list of character strings as,

```<code>let chars = string.decomposedStringWithCompatibilityMapping.unicodeScalars.map { String($0) }
print(chars)
// ["ᄀ", "ᅵ", "ᆷ"]
</code>```

Korean related info in Apple docs

Extended grapheme clusters are a flexible way to represent many
  complex script characters as a single Character value. For example,
  Hangul syllables from the Korean alphabet can be represented as either
  a precomposed or decomposed sequence. Both of these representations
  qualify as a single Character value in Swift:

```<code>let precomposed: Character = "\u{D55C}"                  // 한
let decomposed: Character = "\u{1112}\u{1161}\u{11AB}"   // ᄒ, ᅡ, ᆫ
// precomposed is 한, decomposed is 한
</code>```

Body:
So, for example the character 김 is made up of ㄱ, ㅣ and ㅁ. I need to split the Korean word into it's components to get the resulting 3 characters.

I tried by doing the following but it doesn't seem to output it correctly:

let str = "김"
let utf8 = str.utf8
let first:UInt8 = utf8.first!
let char = Character(UnicodeScalar(first))

The problem is, that that code returns ê, when it should be returning ㄱ.

Body:
You need to use the decomposedStringWithCompatibilityMapping string to get the unicode scalar values and then use those scalar values to get the characters. Something below,

let string = "김"
for scalar in string.decomposedStringWithCompatibilityMapping.unicodeScalars {
  print("\(scalar) ")
}

Output:

ᄀ
ᅵ
ᆷ

You can create list of character strings as,

let chars = string.decomposedStringWithCompatibilityMapping.unicodeScalars.map { String($0) }
print(chars)
// ["ᄀ", "ᅵ", "ᆷ"]

Korean related info in Apple docs

Extended grapheme clusters are a flexible way to represent many
  complex script characters as a single Character value. For example,
  Hangul syllables from the Korean alphabet can be represented as either
  a precomposed or decomposed sequence. Both of these representations
  qualify as a single Character value in Swift:

let precomposed: Character = "\u{D55C}"                  // 한
let decomposed: Character = "\u{1112}\u{1161}\u{11AB}"   // ᄒ, ᅡ, ᆫ
// precomposed is 한, decomposed is 한


Title: Plotting multiple curve line plots in python with Matplotlib

Body:
I am trying to plot 3 loss curves in one figure. I have the following problems.

I can't get a smooth curve, instead it joins point-to-point in a sharp line

How do I change the scales of the axis, to display the MSE loss which disappears because it is too small?

from matplotlib import pyplot as plt

epochs=list(range(5000,50001,5000))
print(epochs)
mae_loss=[0.500225365,
0.000221096,
0.000060971,
0.000060323,
0.000059905,
0.000059579,
0.000059274,
0.000058972,
0.000058697,
0.000058476]

mse_loss=[0.135419831,
0.018331185,
0.002481434,
0.000335913,
0.000045486,
0.000006180,
0.000000867,
0.000000147,
0.000000042,
0.000000042]

rmse_loss=[0.500225306,
0.000293739,
0.000126985,
0.000121944,
0.000119484,
0.000117791,
0.000116400,
0.000115198,
0.000114148,
0.000113228]

plt.plot(epochs, mae_loss, 'b', label='MAE')
plt.plot(epochs, mse_loss, 'r', label='MSE')
plt.plot(epochs, mse_loss, 'g', label='RMSE')
plt.legend()
plt.show()

Body:
To smooth your plots:

import matplotlib.pyplot as plt
import numpy as np
from scipy.interpolate import make_interp_spline, BSpline

def create_spline_from(x, y, resolution):
  new_x = np.linspace(x[0], x[-1], resolution)
  y_spline = make_interp_spline(x, y, k=3)
  new_y= y_spline(new_x)

  return (new_x, new_y)

epochs=list(range(5000,50001,5000))
print(epochs)
mae_loss=[0.500225365,
0.000221096,
0.000060971,
0.000060323,
0.000059905,
0.000059579,
0.000059274,
0.000058972,
0.000058697,
0.000058476]

mse_loss=[0.135419831,
0.018331185,
0.002481434,
0.000335913,
0.000045486,
0.000006180,
0.000000867,
0.000000147,
0.000000042,
0.000000042]

rmse_loss=[0.500225306,
0.000293739,
0.000126985,
0.000121944,
0.000119484,
0.000117791,
0.000116400,
0.000115198,
0.000114148,
0.000113228]

x, y = create_spline_from(epochs, mae_loss, 50)
plt.plot(x, y, 'b', label='MAE')

x, y = create_spline_from(epochs, mse_loss, 50)
plt.plot(x, y, 'r', label='MSE')

x, y = create_spline_from(epochs, rmse_loss, 50)
plt.plot(x, y, 'g', label='RMSE')
plt.legend()
plt.show()


问:
How to split a column of data into two columns based on other matching column criteria in Microsoft Excel?
I have a database list of products and their components but often have multiple sizes. I'm looking for a formula based method to split a separate size of the same items into a second column for user-friendly viewing. I've tried pivot tables which I couldn't get to work, and I really would prefer not to do this manually (we have thousands of entries).

The first table is the original source I have, and the second is the table I would like it to become.

Thanks so much in advance.

答:
Short answer: Use a PivotTable.

Field settings:

Long answer: What you're looking for (exactly) cannot be achieved via a PivotTable, but you could achieve it through formulas (probably) or VBA (definitely). However, you'll need to demonstrate an attempt on your part before we can help you with that, or at least provide a clear, concise before & after. As your current example stands, there's no way we can predict what that would look like on a large scale.


问:
calculate the number of points and save the result in the user profile database
So I have a form containing questions of type free fields (text), multiple choice (checkbox), single choice (radio).

I get the values of the button checked and I save in database for each user but what I want to do is change this value like this:

```<code>data-point "2" = 10 points,
data-point "3" = 7 points,
data-point "4" = 4 points,
data-point "5" = 2 points,
</code>```

and then with these values I have to do a calculation and define a profile according to the result .. how should I do that? SQL request? in the loop? a little help would be welcome ..here my twig to loop on subquestion.

```<code><div class=" col-6 d-flex">
     <div class="label-div1">

           <label for="subscale{{subQuestion.id}}for{{i}}>
              <img src="{{asset('images/survey/humeur/'~ i ~'.jpg')}}">
            </label>

             <input type="radio" class="radio-pict" name="{{subQuestion.id}}" id="subscale{{i}}" data-point="{{i}}"value="{{i}}">

         </div>
</code>```

here my controller to save de answers

```<code> public function saveAnswer(Request $request)
{
    /* Repository */
    $questionRepo =  $this->getDoctrine()->getRepository(Question::class);
    $answerRepo =  $this->getDoctrine()->getRepository(Answer::class);
    $choiceRepo = $this->getDoctrine()->getRepository(Choice::class);
    $userSlpRepo = $this->getDoctrine()->getRepository(UserSlp::class);

    /* Entity Manager */
    $em = $this->getDoctrine()->getManager();

    $datas = $request->request->all();

    $userSlp = $userSlpRepo->findOneByGaeaUserId($this->getUser()->getId());

    foreach ($datas as $data => $value) {

        $questionId = explode("_", $data);
        $question = $questionRepo->findOneById($questionId[0]);
       switch ($question) {
            case 'Sub_question_free':

                $answer = new Answer_free;
                $answer->setFreeAswere($value);

                break;

            case 'Sub_question_scale':

                $answer = new Answer_scale;

                $answer->setScale($value);

                break;

        $answer->setQuestion($question);
        $answer->setUserSlp($userSlp);

        $em->persist($answer);
        $em->flush();
       }
      exit;
    }
  }
</code>```

and here my twig to display on admin the results..

```<code>{% if answer.question == "Sub_question_choice" or
      answer.question == "Sub_question_scale" or
      answer.question == "Sub_question_free" %}
{% if answer == "choice" %}
{% for choice in answer.choices %}
<p>{{choice.name}}</p>
{% endfor %}
{% elseif answer == "free" %}
<p>{{answer.freeAswere}}</p>
 {% elseif answer == "scale" %}
<p> {{answer.scale}}</p>
{% endif %}
</code>```

答:
So first, in Symfony a controller always need to send back a response. Even if it's just a redirect or a JsonResponse. So you shouldn't use exit in your controller.

You should use Symfony form, but if you are new to Symfony, I can understand that it's not easy.

Here to help you, you have many options:

You can change value with some conditions inside your swith statement in your controller

You can separate that in a service, look for service in Symfony on the docs. And use dependency injection inside your controller like this :

```<code>Service :
    public function conversion(){
    //Some conditions
    }
controller:
    public function saveAnswer(Request $request, YourService $service)
</code>```

And use it inside as a function.

(More Easy Option) You can overload your setter in your entity (Answer.php for example):

```<code>public function yourSetter(...){
//do some conditions and after set your variables depending on result
}
</code>```

Hope this will help you, feel free to ask if you want !

Body:
So I have a form containing questions of type free fields (text), multiple choice (checkbox), single choice (radio).

I get the values of the button checked and I save in database for each user but what I want to do is change this value like this:

data-point "2" = 10 points,
data-point "3" = 7 points,
data-point "4" = 4 points,
data-point "5" = 2 points,

and then with these values I have to do a calculation and define a profile according to the result .. how should I do that? SQL request? in the loop? a little help would be welcome ..here my twig to loop on subquestion.

             <input type="radio" class="radio-pict" name="{{subQuestion.id}}" id="subscale{{i}}" data-point="{{i}}"value="{{i}}">

here my controller to save de answers

 public function saveAnswer(Request $request)
{
    /* Repository */
    $questionRepo =  $this->getDoctrine()->getRepository(Question::class);
    $answerRepo =  $this->getDoctrine()->getRepository(Answer::class);
    $choiceRepo = $this->getDoctrine()->getRepository(Choice::class);
    $userSlpRepo = $this->getDoctrine()->getRepository(UserSlp::class);

    /* Entity Manager */
    $em = $this->getDoctrine()->getManager();

    $datas = $request->request->all();

    $userSlp = $userSlpRepo->findOneByGaeaUserId($this->getUser()->getId());

    foreach ($datas as $data => $value) {

        $questionId = explode("_", $data);
        $question = $questionRepo->findOneById($questionId[0]);
       switch ($question) {
            case 'Sub_question_free':

                $answer = new Answer_free;
                $answer->setFreeAswere($value);

                break;

            case 'Sub_question_scale':

                $answer = new Answer_scale;

                $answer->setScale($value);

                break;

        $answer->setQuestion($question);
        $answer->setUserSlp($userSlp);

        $em->persist($answer);
        $em->flush();
       }
      exit;
    }
  }

and here my twig to display on admin the results..

{% if answer.question == "Sub_question_choice" or
      answer.question == "Sub_question_scale" or
      answer.question == "Sub_question_free" %}
{% if answer == "choice" %}
{% for choice in answer.choices %}

{{choice.name}}

{% endfor %}
{% elseif answer == "free" %}

{{answer.freeAswere}}

 {% elseif answer == "scale" %}

 {{answer.scale}}

{% endif %}

Body:
So first, in Symfony a controller always need to send back a response. Even if it's just a redirect or a JsonResponse. So you shouldn't use exit in your controller.

You should use Symfony form, but if you are new to Symfony, I can understand that it's not easy.

Here to help you, you have many options:

You can change value with some conditions inside your swith statement in your controller

You can separate that in a service, look for service in Symfony on the docs. And use dependency injection inside your controller like this :

Service :
    public function conversion(){
    //Some conditions
    }
controller:
    public function saveAnswer(Request $request, YourService $service)

And use it inside as a function.

(More Easy Option) You can overload your setter in your entity (Answer.php for example):

public function yourSetter(...){
//do some conditions and after set your variables depending on result
}

Hope this will help you, feel free to ask if you want !


问:
Create my own classList object when the browser does not implement it itself
I have JavaScript code that adds and removes classes using the classList object.
The code is up and working correctly as expected until I received complaints about it because it does not work in Opera and in IE8.

I don't want to use any frameworks or code libraries. I'd like to reduce to a max the code I have to change in my program so I wanted to make my own classList object and add it to the node object. I already have this code:

```<code>if (typeof(document.createElement('input').classList) == 'undefined') {
    HTMLElement.prototype.classList = new function () {
        this.add = function (addClass) {
            this.className += addClass;
        }
    }
}
</code>```

which, obviously, does not work.
The problem is: I can't access the HTMLElement.className of this object like this. How can I accomplish that? How can I make this object to work similar to or exactly like the original?

答:
Instead of extending the prototype you can just create a helper function that returns the values you need:

```<code>classList = function ( elem ) {
    return elem.className.replace(/\s+/g,' ').split(' ');
};
</code>```

Then instead of calling elem.classList you'd just call classList(elem), meaning it doesn't work exactly like the original but it returns the same data.

ContentLicense: CC BY-SA 3.0

Body:
I have JavaScript code that adds and removes classes using the classList object.
The code is up and working correctly as expected until I received complaints about it because it does not work in Opera and in IE8.

I don't want to use any frameworks or code libraries. I'd like to reduce to a max the code I have to change in my program so I wanted to make my own classList object and add it to the node object. I already have this code:

if (typeof(document.createElement('input').classList) == 'undefined') {
    HTMLElement.prototype.classList = new function () {
        this.add = function (addClass) {
            this.className += addClass;
        }
    }
}

which, obviously, does not work.
The problem is: I can't access the HTMLElement.className of this object like this. How can I accomplish that? How can I make this object to work similar to or exactly like the original?

Body:
Instead of extending the prototype you can just create a helper function that returns the values you need:

classList = function ( elem ) {
    return elem.className.replace(/\s+/g,' ').split(' ');
};

Then instead of calling elem.classList you'd just call classList(elem), meaning it doesn't work exactly like the original but it returns the same data.


问:
Ignoring option -Xprof; support was removed in 10.0
What is a proper replacement for the -Xprof flag?

Running a java program with JDK 11 with the -Xprof flag produces the following output:

```<code>Ignoring option -Xprof; support was removed in 10.0
</code>```

答:
At the list of deprecated features as of Java 9 Take a look at the description of JDK-8176098:

This technology is no longer relevant and is a source of root scanning for the GC and contains bugs. We want to remove flatprofiler in JDK 10 and therefore deprecated it in JDK 9.

Clicking to the linked related report JDK-8173715 reveals:

We assume that this technology is no longer in use and is a source of root scanning for the GC.

Unfortunately, there was an agreement of conclusion of removing a buggy -Xprof feature with an assumption that there is a minimal risk of affecting someone by its removal.

Body:
What is a proper replacement for the -Xprof flag?

Running a java program with JDK 11 with the -Xprof flag produces the following output:

Ignoring option -Xprof; support was removed in 10.0


问:
Add type signature for a helper function inside
First I define the following data type

```<code>data Supply s a = S (Stream s -> (a, Stream s))
data Stream a = Cons a (Stream a)
</code>```

Then I want to implement a function which maps to a Supply with the following type signature:

```<code>mapSupply :: (a -> b) -> Supply s a -> Supply s b
</code>```

And here is my implementation: (which compiles with no problem)

```<code>mapSupply :: (a -> b) -> Supply s a -> Supply s b
mapSupply mapFunc (S supFuncA) = S supFuncB where
    supFuncB strm = let (la, strms) = supFuncA strm in
        ((mapFunc la), strms)
</code>```

Then I met a problem when I tried to write down the type signature for the helper function named supFuncB which I defined inside mapSupply.

The type signature for supFuncB is very simple and should be:

```<code>supFuncB :: Stream s -> (b, Stream s)
</code>```

However when I tried to add the type signature in the code, I got a compiler error. The code looks like this

```<code>mapSupply :: (a -> b) -> Supply s a -> Supply s b
mapSupply mapFunc (S supFuncA) = S supFuncB where
    supFuncB :: Stream s -> (b, Stream s)
    supFuncB strm = let (la, strms) = supFuncA strm in
        ((mapFunc la), strms)
</code>```

And then compiler complained:

```<code>• Couldn't match type ‘s1’ with ‘s’
  ‘s1’ is a rigid type variable bound by
    the type signature for:
      supFuncB :: forall s1 b1. Stream s1 -> (b1, Stream s1)
    at Main.hs:58:5-41
  ‘s’ is a rigid type variable bound by
    the type signature for:
      mapSupply :: forall a b s. (a -> b) -> Supply s a -> Supply s b
    at Main.hs:56:1-49
  Expected type: Stream s1
    Actual type: Stream s
• In the expression: strms
  In the expression: ((mapFunc la), strms)
  In the expression:
    let (la, strms) = supFuncA strm in ((mapFunc la), strms)
</code>```

I'm very new to Haskell and I don't understand why the compile would fail?  And what should be the correct type signature if I were to add it in the code.

答:
To begin from the end, the solution is turning on ScopedTypeVariables and using an explicit forall in the mapSupply signature, like this:

```<code>{-# LANGUAGE ScopedTypeVariables #-}  -- Put this at the top of your file.

mapSupply :: forall a b s. (a -> b) -> Supply s a -> Supply s b
mapSupply mapFunc (S supFuncA) = S supFuncB where
    supFuncB :: Stream s -> (b, Stream s)
    supFuncB strm = let (la, strms) = supFuncA strm in
        ((mapFunc la), strms)
</code>```

What follows is an explanation of why that is necessary.

When you write a signature like this:

```<code>mapSupply :: (a -> b) -> Supply s a -> Supply s b
</code>```

GHC actually sees this:

```<code>mapSupply :: forall a b s. (a -> b) -> Supply s a -> Supply s b
</code>```

The forall, which normally can be left implicit, says that a, b and s can be anything -- mapSupply is a polymorphic function, and so whoever uses it is free to choose any concrete types for the three type variables. Writing the foralls explicitly, your second definition would look like this:

```<code>mapSupply :: forall a b s. (a -> b) -> Supply s a -> Supply s b
mapSupply mapFunc (S supFuncA) = S supFuncB where
    supFuncB :: forall s b. Stream s -> (b, Stream s)
    supFuncB strm = let (la, strms) = supFuncA strm in
        ((mapFunc la), strms)
</code>```

According to it, a, b and s in mapSupply can be anything, and the same goes for s and b in supFuncB. That is a problem, though. For instance, the definition involves strms, whose type is s... except that s, which shows up because you are using supFuncA, is not the one from the supFuncB signature, but rather the one from the mapSupply signature. While the s from mapSupply can, in principle, be anything, as I noted before, once you actually choose an s by using mapSupply, the s from supFuncB must match it. That being so, the forall in the supFuncB signature is out of place, as its type variables can't really be anything. It becomes easier to see if we rename the type variables from supFuncB so that their names don't clash with those from mapSupply (given the forall, it should be a valid move to do that):

```<code>mapSupply :: forall a b s. (a -> b) -> Supply s a -> Supply s b
mapSupply mapFunc (S supFuncA) = S supFuncB where
    supFuncB :: forall s1 b1. Stream s1 -> (b1, Stream s1)
    supFuncB strm = let (la, strms) = supFuncA strm in
        ((mapFunc la), strms)
</code>```

(GHC does that internally, which explains why the error message you got mentioned an s1 type variable.)

This problem only happened because of the signature added to supFuncB, which introduced an implicit forall. Without the signature, GHC does what you want by not generalising the types from supFuncB -- in that case, it is not polymorphic, but rather monomorphic in the type variables a, b and s, which are borrowed from mapSupply. The ScopedTypeVariables extension makes it possible to recover that behaviour while writing a type signature for supFuncB. When it is enabled, using an explicit forall for the type variables in a signature will make any type variables with the same name in the corresponding definition refer to the same thing (as long as they aren't also under a forall in their own signatures). In other words, by doing that it becomes possible to refer to the variables from the outer signature anywhere within the scope of the corresponding definition, which justifies the name of the extension.

Body:
First I define the following data type

data Supply s a = S (Stream s -> (a, Stream s))
data Stream a = Cons a (Stream a)

Then I want to implement a function which maps to a Supply with the following type signature:

mapSupply :: (a -> b) -> Supply s a -> Supply s b

And here is my implementation: (which compiles with no problem)

mapSupply :: (a -> b) -> Supply s a -> Supply s b
mapSupply mapFunc (S supFuncA) = S supFuncB where
    supFuncB strm = let (la, strms) = supFuncA strm in
        ((mapFunc la), strms)

Then I met a problem when I tried to write down the type signature for the helper function named supFuncB which I defined inside mapSupply.

The type signature for supFuncB is very simple and should be:

supFuncB :: Stream s -> (b, Stream s)

However when I tried to add the type signature in the code, I got a compiler error. The code looks like this

mapSupply :: (a -> b) -> Supply s a -> Supply s b
mapSupply mapFunc (S supFuncA) = S supFuncB where
    supFuncB :: Stream s -> (b, Stream s)
    supFuncB strm = let (la, strms) = supFuncA strm in
        ((mapFunc la), strms)

And then compiler complained:

• Couldn't match type ‘s1’ with ‘s’
  ‘s1’ is a rigid type variable bound by
    the type signature for:
      supFuncB :: forall s1 b1. Stream s1 -> (b1, Stream s1)
    at Main.hs:58:5-41
  ‘s’ is a rigid type variable bound by
    the type signature for:
      mapSupply :: forall a b s. (a -> b) -> Supply s a -> Supply s b
    at Main.hs:56:1-49
  Expected type: Stream s1
    Actual type: Stream s
• In the expression: strms
  In the expression: ((mapFunc la), strms)
  In the expression:
    let (la, strms) = supFuncA strm in ((mapFunc la), strms)

I'm very new to Haskell and I don't understand why the compile would fail?  And what should be the correct type signature if I were to add it in the code.

Body:
To begin from the end, the solution is turning on ScopedTypeVariables and using an explicit forall in the mapSupply signature, like this:

{-# LANGUAGE ScopedTypeVariables #-}  -- Put this at the top of your file.

mapSupply :: forall a b s. (a -> b) -> Supply s a -> Supply s b
mapSupply mapFunc (S supFuncA) = S supFuncB where
    supFuncB :: Stream s -> (b, Stream s)
    supFuncB strm = let (la, strms) = supFuncA strm in
        ((mapFunc la), strms)

What follows is an explanation of why that is necessary.

When you write a signature like this:

mapSupply :: (a -> b) -> Supply s a -> Supply s b

GHC actually sees this:

mapSupply :: forall a b s. (a -> b) -> Supply s a -> Supply s b

The forall, which normally can be left implicit, says that a, b and s can be anything -- mapSupply is a polymorphic function, and so whoever uses it is free to choose any concrete types for the three type variables. Writing the foralls explicitly, your second definition would look like this:

mapSupply :: forall a b s. (a -> b) -> Supply s a -> Supply s b
mapSupply mapFunc (S supFuncA) = S supFuncB where
    supFuncB :: forall s b. Stream s -> (b, Stream s)
    supFuncB strm = let (la, strms) = supFuncA strm in
        ((mapFunc la), strms)

According to it, a, b and s in mapSupply can be anything, and the same goes for s and b in supFuncB. That is a problem, though. For instance, the definition involves strms, whose type is s... except that s, which shows up because you are using supFuncA, is not the one from the supFuncB signature, but rather the one from the mapSupply signature. While the s from mapSupply can, in principle, be anything, as I noted before, once you actually choose an s by using mapSupply, the s from supFuncB must match it. That being so, the forall in the supFuncB signature is out of place, as its type variables can't really be anything. It becomes easier to see if we rename the type variables from supFuncB so that their names don't clash with those from mapSupply (given the forall, it should be a valid move to do that):

mapSupply :: forall a b s. (a -> b) -> Supply s a -> Supply s b
mapSupply mapFunc (S supFuncA) = S supFuncB where
    supFuncB :: forall s1 b1. Stream s1 -> (b1, Stream s1)
    supFuncB strm = let (la, strms) = supFuncA strm in
        ((mapFunc la), strms)

(GHC does that internally, which explains why the error message you got mentioned an s1 type variable.)

This problem only happened because of the signature added to supFuncB, which introduced an implicit forall. Without the signature, GHC does what you want by not generalising the types from supFuncB -- in that case, it is not polymorphic, but rather monomorphic in the type variables a, b and s, which are borrowed from mapSupply. The ScopedTypeVariables extension makes it possible to recover that behaviour while writing a type signature for supFuncB. When it is enabled, using an explicit forall for the type variables in a signature will make any type variables with the same name in the corresponding definition refer to the same thing (as long as they aren't also under a forall in their own signatures). In other words, by doing that it becomes possible to refer to the variables from the outer signature anywhere within the scope of the corresponding definition, which justifies the name of the extension.


问:
Copy file from one folder to another
I'm trying to copy the file as the Android path comes, without success, although it already existed as permissions on AndroidManifest, it's as if the file did not exist or know it there.
Here's a piece of code:

```<code>public void onActivityResult(int requestCode, int resultCode, Intent data)
{
    switch (requestCode) {
        case FILE_SELECT_CODE:
            if (resultCode == RESULT_OK) {

                Uri uri = data.getData();
                String origem = uri.getPath();
                File src = new File(origem);
                if(src.isFile()){
                    Log.d(TAG,src.toString());
                }

                File root = Environment.getExternalStorageDirectory();
                root = new File(root.toString(), "Kcollector/importa/import.csv");

                try {
                    copy(src,root,true);
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
            break;
    }
    super.onActivityResult(requestCode, resultCode, data);
}

public static void copy(File origem, File destino, boolean overwrite) throws IOException{
    Date date = new Date();
    if (destino.exists() && !overwrite){
        System.err.println(destino.getName()+" já existe, ignorando...");
        return;
    }
    FileInputStream fisOrigem = new FileInputStream(origem);
    FileOutputStream fisDestino = new FileOutputStream(destino);
    FileChannel fcOrigem = fisOrigem.getChannel();
    FileChannel fcDestino = fisDestino.getChannel();
    fcOrigem.transferTo(0, fcOrigem.size(), fcDestino);
    fisOrigem.close();
    fisDestino.close();
    Long time = new Date().getTime() - date.getTime();
    System.out.println("Saiu copy"+time);
}
</code>```

The error that returns me when trying to copy:

W/System.err: java.io.FileNotFoundException: /external_storage/Kcollector/importa/kvendasajustado.csv (No such file or directory)
W/System.err:     at java.io.FileInputStream.open0(Native Method)

答:
check the runtime permissions or use the method indicated in the first response

```<code>public static void copy(File src, File dst) throws IOException {
    InputStream in = new FileInputStream(src);
    try {
        OutputStream out = new FileOutputStream(dst);
        try {
            // Transfer bytes from in to out
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        } finally {
            out.close();
        }
    } finally {
        in.close();
    }
}
</code>```

Finally check the url if is formed good.
Otherwise you can de bug with a breakpoint(search these words), and find exactly where the problem comes from

Title: Copy file from one folder to another

Body:
I'm trying to copy the file as the Android path comes, without success, although it already existed as permissions on AndroidManifest, it's as if the file did not exist or know it there.
Here's a piece of code:

public void onActivityResult(int requestCode, int resultCode, Intent data)
{
    switch (requestCode) {
        case FILE_SELECT_CODE:
            if (resultCode == RESULT_OK) {

                Uri uri = data.getData();
                String origem = uri.getPath();
                File src = new File(origem);
                if(src.isFile()){
                    Log.d(TAG,src.toString());
                }

                File root = Environment.getExternalStorageDirectory();
                root = new File(root.toString(), "Kcollector/importa/import.csv");

                try {
                    copy(src,root,true);
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
            break;
    }
    super.onActivityResult(requestCode, resultCode, data);
}

public static void copy(File origem, File destino, boolean overwrite) throws IOException{
    Date date = new Date();
    if (destino.exists() && !overwrite){
        System.err.println(destino.getName()+" já existe, ignorando...");
        return;
    }
    FileInputStream fisOrigem = new FileInputStream(origem);
    FileOutputStream fisDestino = new FileOutputStream(destino);
    FileChannel fcOrigem = fisOrigem.getChannel();
    FileChannel fcDestino = fisDestino.getChannel();
    fcOrigem.transferTo(0, fcOrigem.size(), fcDestino);
    fisOrigem.close();
    fisDestino.close();
    Long time = new Date().getTime() - date.getTime();
    System.out.println("Saiu copy"+time);
}

The error that returns me when trying to copy:

W/System.err: java.io.FileNotFoundException: /external_storage/Kcollector/importa/kvendasajustado.csv (No such file or directory)
W/System.err:     at java.io.FileInputStream.open0(Native Method)

Body:
check the runtime permissions or use the method indicated in the first response

public static void copy(File src, File dst) throws IOException {
    InputStream in = new FileInputStream(src);
    try {
        OutputStream out = new FileOutputStream(dst);
        try {
            // Transfer bytes from in to out
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        } finally {
            out.close();
        }
    } finally {
        in.close();
    }
}

Finally check the url if is formed good.
Otherwise you can de bug with a breakpoint(search these words), and find exactly where the problem comes from


问:
change dataTables page number in resize
I'm using dataTables (https://datatables.net) and trying to do a responsive page number, I need this:

Desktop:
first prev 1 2 3 4 5 next last

Mobile:
first prev 1 2 3 next last

Actually with my code I get this on mobile, nothing change:
first prev 1 2 3 4 5 next last

This is my code:

```<code>$(window).resize(function () {
   if ($(this).outerWidth() < 768){
      // change the dataTable pageLength in here
      $.fn.DataTable.ext.pager.numbers_length = 3;
   } else {
      // default pageLength
      $.fn.DataTable.ext.pager.numbers_length = 5;
   }
});
</code>```

答: There is a Responsive extension for datatables. You can also try the solutions Here.</p>

Title: change dataTables page number in resize

Body:
I'm using dataTables (https://datatables.net) and trying to do a responsive page number, I need this:

Desktop:
first prev 1 2 3 4 5 next last

Mobile:
first prev 1 2 3 next last

Actually with my code I get this on mobile, nothing change:
first prev 1 2 3 4 5 next last

This is my code:

$(window).resize(function () {
   if ($(this).outerWidth() < 768){
      // change the dataTable pageLength in here
      $.fn.DataTable.ext.pager.numbers_length = 3;
   } else {
      // default pageLength
      $.fn.DataTable.ext.pager.numbers_length = 5;
   }
});


问:
How to mock extension methods with Moq | Url.Page()
I am trying to mock a class which registers users to test. and In the test code I can see it clearly fails at callbackUrl below.
The PageModel class has a field IUrlHelper declared as Url. The IUrlHelper interface has 5 methods which does NOT include .Page(). Mocking those 5 would be easy but I have no idea how to mock extension methods.
Can someone please help? I have been stuck on this for ages.

RegisterModel

```<code>public class RegisterModel : PageModel
{
    private readonly IUrlHelper _urlHelper;

    public RegisterModel(
        IUrlHelper urlHelper)
        {}

    public async Task<IActionResult> OnPostAsync(
        string returnUrl = null)
    {
        returnUrl = returnUrl ?? Url.Content("~/");
        var callbackUrl = Url.Page(
                    "/Account/ConfirmEmail",
                    pageHandler: null,
                    values: new { userId = "full code has IdentityUserCreated", code = "string" },
                    protocol: Request.Scheme);
        LocalRedirect(returnUrl);
        return Page();
    }
}
</code>```

RegisterModelTests

```<code>[TestFixture]
public class RegisterModelTests
{
    private Mock<IUrlHelper> _mockUrlHelper;

    [SetUp]
    public void SetUp()
    {
        _mockUrlHelper = new Mock<IUrlHelper>();
        SetUpUrlHelper();
    }

    public RegisterModel CreateRegisterModel()
    {
        return new RegisterModel(
            _mockUrlHelper.Object
        );
    }

    [Test]
    public async Task GivenValidInput_OnPostAsync_CreatesANewUser()
    {
        // Arrange
        var unitUnderTest = CreateRegisterModel();

        // Act
        var result = await unitUnderTest.OnPostAsync("/asdsad/asda");

        // Assert
        if (result != null)
            Assert.Pass();
    }

    private void SetUpUrlHelper()
    {
        _mockUrlHelper.Setup(x => x.Page(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<IdentityUser>(),
               It.IsAny<string>())).Returns("callbackUrl").Verifiable();
    }
</code>```

答:
I tried ICodeGorilla's solution but found that Static Types cannot be used as type arguments.  So I modified the code a bit to this:

```<code>        public static void Replace(Type original, Type target)
        {
            var targetMethods = GetStaticPublicMethods(target);
            foreach (var targetMethod in targetMethods)
            {
                var parameters = targetMethod.GetParameters().Select(x => x.ParameterType).ToArray();
                var originalMethod = original.GetMethod(targetMethod.Name, parameters);
                if (originalMethod != null)
                {
                    SwapMethodBodies(originalMethod, targetMethod);
                }
                else
                {
                    Debug.WriteLine(
                        "*****************************************************************************************");
                    Debug.WriteLine($"Method not found - {targetMethod.Name}");
                    Debug.WriteLine(
                        "*****************************************************************************************");
                }
            }
        }

        private static List<MethodInfo> GetStaticPublicMethods(Type t)
        {
            return t.GetMethods(BindingFlags.Public | BindingFlags.Static)
                .Distinct().ToList();
        }
</code>```

The usage is now:

```<code>ShimHelper.Replace(
                typeof(ExtensionClass),
                typeof(MockedExtensionClass));
</code>```

I found this worked very nicely for AjaxRequestExtensions in MVC.

Body:
I am trying to mock a class which registers users to test. and In the test code I can see it clearly fails at callbackUrl below.
The PageModel class has a field IUrlHelper declared as Url. The IUrlHelper interface has 5 methods which does NOT include .Page(). Mocking those 5 would be easy but I have no idea how to mock extension methods.
Can someone please help? I have been stuck on this for ages.

RegisterModel

public class RegisterModel : PageModel
{
    private readonly IUrlHelper _urlHelper;

    public RegisterModel(
        IUrlHelper urlHelper)
        {}

    public async Task<IActionResult> OnPostAsync(
        string returnUrl = null)
    {
        returnUrl = returnUrl ?? Url.Content("~/");
        var callbackUrl = Url.Page(
                    "/Account/ConfirmEmail",
                    pageHandler: null,
                    values: new { userId = "full code has IdentityUserCreated", code = "string" },
                    protocol: Request.Scheme);
        LocalRedirect(returnUrl);
        return Page();
    }
}

RegisterModelTests

[TestFixture]
public class RegisterModelTests
{
    private Mock<IUrlHelper> _mockUrlHelper;

    [SetUp]
    public void SetUp()
    {
        _mockUrlHelper = new Mock<IUrlHelper>();
        SetUpUrlHelper();
    }

    public RegisterModel CreateRegisterModel()
    {
        return new RegisterModel(
            _mockUrlHelper.Object
        );
    }

    [Test]
    public async Task GivenValidInput_OnPostAsync_CreatesANewUser()
    {
        // Arrange
        var unitUnderTest = CreateRegisterModel();

        // Act
        var result = await unitUnderTest.OnPostAsync("/asdsad/asda");

        // Assert
        if (result != null)
            Assert.Pass();
    }

    private void SetUpUrlHelper()
    {
        _mockUrlHelper.Setup(x => x.Page(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<IdentityUser>(),
               It.IsAny<string>())).Returns("callbackUrl").Verifiable();
    }

Body:
I tried ICodeGorilla's solution but found that Static Types cannot be used as type arguments.  So I modified the code a bit to this:

        public static void Replace(Type original, Type target)
        {
            var targetMethods = GetStaticPublicMethods(target);
            foreach (var targetMethod in targetMethods)
            {
                var parameters = targetMethod.GetParameters().Select(x => x.ParameterType).ToArray();
                var originalMethod = original.GetMethod(targetMethod.Name, parameters);
                if (originalMethod != null)
                {
                    SwapMethodBodies(originalMethod, targetMethod);
                }
                else
                {
                    Debug.WriteLine(
                        "*****************************************************************************************");
                    Debug.WriteLine($"Method not found - {targetMethod.Name}");
                    Debug.WriteLine(
                        "*****************************************************************************************");
                }
            }
        }

        private static List<MethodInfo> GetStaticPublicMethods(Type t)
        {
            return t.GetMethods(BindingFlags.Public | BindingFlags.Static)
                .Distinct().ToList();
        }

The usage is now:

ShimHelper.Replace(
                typeof(ExtensionClass),
                typeof(MockedExtensionClass));

I found this worked very nicely for AjaxRequestExtensions in MVC.


问:
FragmentPagerAdapter's Fragment not showing RecyclerView's items
I think the easiest way to show the problem is the gif below. When i'm on the home fragment, and switch to Recent, Recent is a fragment with ViewPager and TabLayout, the item that's supposed to be in the recyclerView shows up normally, but when i go back to Home Fragment, and go back to Recent, the Item is not there anymore. I believe that it has something to do with the fact that when I go back to the Recent Fragment, even though the Recent Fragment's onCreate() is being called, the 'All' Fragment, which is the first in the ViewPager is not calling it's onCreate().

It's calling the onResume() however, and i check the RecyclerView's list size in there, and it still has the item in it, it just not showing up.

How can i fix that?

Is there a way to force the FragmentPagerAdapter to call onCreate() on it's fragment's, like the 'All' Fragment when going back?

答:
Found the solution, didn't know where to even look for the problem so i didn't post the code in question to not make it too long.

When using a ViewPager inside a Fragment, don't use getActivity().getSupportFragmentManager() when creating FragmentPagerAdapter, use getChildFragmentManager() instead.

So when it comes to code, use this:

```<code>MyFragmentPagerAdapter adapter = new MyFragmentPagerAdapter(getActivity(), getChildFragmentManager());
</code>```

Instead of :

```<code>MyFragmentPagerAdapter adapter = new MyFragmentPagerAdapter(getActivity(), getActivity().getSupportFragmentManager());
</code>```

Body:
Found the solution, didn't know where to even look for the problem so i didn't post the code in question to not make it too long.

When using a ViewPager inside a Fragment, don't use getActivity().getSupportFragmentManager() when creating FragmentPagerAdapter, use getChildFragmentManager() instead.

So when it comes to code, use this:

MyFragmentPagerAdapter adapter = new MyFragmentPagerAdapter(getActivity(), getChildFragmentManager());

Instead of :

MyFragmentPagerAdapter adapter = new MyFragmentPagerAdapter(getActivity(), getActivity().getSupportFragmentManager());


问:
Modal dialog and __doPostback Infinite loop
I've got a modal dialog created using ModalPopupExtender. There is an UI created in it using Webservices and a JQuery Templates. There is also a hidden ASP.NET button which is called from the javascript using the __doPostback() technique. The javascript hides the modal popup and __doPostback is called on the button (which is inside of the ModalPopupExtender)

I use this technique to pass some parameters are from the javascript. The server-side event handler does some processing and transfers to a page (in some cases, back to itself)

This works fine when the page it transfers to is a different one but if it transfers to the same page, the postback happens over and over again until the stack blows.

How do i stop the postback from re-occurring when I postback to the same page. I guess it doesn't happen the first time around because it posts to a different page and the postback is invalidated.

Code samples are difficult to provide as it's a fairly complicated system and it's difficult to break it apart.

It sounds horrible I know, all I want to do, however, it to call a server side function from javascript with some variables. Is there a better way to do this?

答:
With out a code sample I can only speculate and hopefully point you in the right direction.

When you transfer to a new page the old page (and therefore the javascript on that page) passes out of scope and therefore does not continue to execute. If, however, the page is reloaded and the condition that invoked the __doPostback continues then you have created the circular reference that causes your problem. Before you invoke __doPostback, but while you are still on the client, you need to clear whatever condition might be causing the chain of events.

If you can not uncover what is invoking your event chain then you might consider that instead of transferring back to the same page transfer to a new page (bounce.aspx) which in turn invokes a response.redirect BACK to the page so that it is not a Postback when it is being reloaded, but a fresh instance of the page. (Yes, this is a kludge, but it might be an effective stop gap...)

Cheers,

CEC


问:
How to remove trailing whitespace in code, using another script?
Something like:

```<code>import fileinput

for lines in fileinput.FileInput("test.txt", inplace=1):
    lines = lines.strip()
    if lines == '': continue
    print lines
</code>```

But nothing is being printed on stdout.

Assuming some string named foo:

```<code>foo.lstrip() # to remove leading white space
foo.rstrip() # to remove trailing whitespace
foo.strip()  # to remove both lead and trailing whitespace
</code>```

答:
It's a bit surprising seeing multiple answers suggesting to use python for this task, as there's no need to write a multi-line program for this.

Standard Unix tools like sed, awk or perl can achieve this easily straight from the command-line.

e.g anywhere you have perl (Windows, Mac, Linux) the following should achieve what the OP asked:

```<code>perl -i -pe 's/[ \t]+$//;' files...
</code>```

Explanation of the arguments to perl:

```<code>-i   # run the edit "in place" (modify the original file)
-p   # implies a loop with a final print over every input line
-e   # next arg is the perl expression to apply (to every line)
</code>```

s/[ \t]$//  is a substitution regex s/FROM/TO/: replace every trailing (end of line) non-empty space (spaces or tabs) with nothing.

Advantages:

One liner, no programming needed

Works on multiple (any number) of files

Works correctly on standard-input (no file arguments given)

Edit:

Newer versions of perl support \h (any horizontal-space character), so the solution becomes even shorter:

    perl -i -pe 's/\h+$//;' files...

More generally, if you want to modify any number of files directly from the command line, replacing every appearance of FOO with BAR, you may always use this generic template:

```<code>perl -i -pe 's/FOO/BAR/' files...
</code>```

Body:
Something like:

import fileinput

for lines in fileinput.FileInput("test.txt", inplace=1):
    lines = lines.strip()
    if lines == '': continue
    print lines

But nothing is being printed on stdout.

Assuming some string named foo:

foo.lstrip() # to remove leading white space
foo.rstrip() # to remove trailing whitespace
foo.strip()  # to remove both lead and trailing whitespace

Body:
It's a bit surprising seeing multiple answers suggesting to use python for this task, as there's no need to write a multi-line program for this.

Standard Unix tools like sed, awk or perl can achieve this easily straight from the command-line.

e.g anywhere you have perl (Windows, Mac, Linux) the following should achieve what the OP asked:

perl -i -pe 's/[ \t]+$//;' files...

Explanation of the arguments to perl:

-i   # run the edit "in place" (modify the original file)
-p   # implies a loop with a final print over every input line
-e   # next arg is the perl expression to apply (to every line)

s/[ \t]$//  is a substitution regex s/FROM/TO/: replace every trailing (end of line) non-empty space (spaces or tabs) with nothing.

Advantages:

One liner, no programming needed

Works on multiple (any number) of files

Works correctly on standard-input (no file arguments given)

Edit:

Newer versions of perl support \h (any horizontal-space character), so the solution becomes even shorter:

    perl -i -pe 's/\h+$//;' files...

More generally, if you want to modify any number of files directly from the command line, replacing every appearance of FOO with BAR, you may always use this generic template:

perl -i -pe 's/FOO/BAR/' files...


问:
Copying Attachments from parent object to child object when field changes
Trying copying Attachments from parent object to child object when attachment gets inserted on Opportunity(Parent Obj)

I have tried writing some code.

```<code>trigger CopyAttachmentsToRU on Attachment (after insert) {

    Set<Id> OppIds = new Set<Id>();
    for(Attachment file : Trigger.new) {

        // only collect those that are for the Opportunity object (others can be ignored)
        if(file.ParentId.getSObjectType() == Opportunity.getSObjectType()) {
            OppIds.add(file.ParentId);
            system.debug(OppIds);
        }
    }

    if(!OppIds.isEmpty()) {
        Map<Id,EIP_Lead_Rental_Object__c> ruMap = new Map<Id,EIP_Lead_Rental_Object__c>([select EIP_Opportunity__c from EIP_Lead_Rental_Object__c where EIP_Opportunity__c in : OppIds]);
        List<Attachment> attachments = new List<Attachment>();
        system.debug(ruMap);
        for(Attachment file : Trigger.new) {
            Attachment newFile = file.clone();
            newFile.ParentId = ruMap.get(file.ParentId).Id;
            attachments.add(newFile);
        }
        // finally, insert the cloned attachments
        insert attachments;

    }

}
</code>```

Every time an attachment gets attach to Opportunity..its not working for me !

答:
Your ruMap has keys made out of EIP_Lead_Rental_Object__c ids. But you try to call get() on it using Opportunity Ids. This will never work. I'm surprised it doesn't throw you a null-related error, do you have some try-catch in there that just swallows the exception?

You probably need something like

```<code>Map<Id,EIP_Lead_Rental_Object__c> ruMap = new Map<Id,EIP_Lead_Rental_Object__c>();
for(EIP_Lead_Rental_Object__c obj : [select Id, EIP_Opportunity__c from EIP_Lead_Rental_Object__c where EIP_Opportunity__c in : OppIds]){
    ruMap.put(obj.EIP_Opportunity__c, obj);
}
</code>```

and then you can

```<code>for(Attachment file : Trigger.new){
    if(ruMap.containsKey(file.ParentId)){
        Attachment newFile = file.clone();
        newFile.ParentId = ruMap.get(file.ParentId).Id;
        attachments.add(newFile);
    }
}
</code>```

Body:
Trying copying Attachments from parent object to child object when attachment gets inserted on Opportunity(Parent Obj)

I have tried writing some code.

trigger CopyAttachmentsToRU on Attachment (after insert) {

    Set<Id> OppIds = new Set<Id>();
    for(Attachment file : Trigger.new) {

        // only collect those that are for the Opportunity object (others can be ignored)
        if(file.ParentId.getSObjectType() == Opportunity.getSObjectType()) {
            OppIds.add(file.ParentId);
            system.debug(OppIds);
        }
    }

    if(!OppIds.isEmpty()) {
        Map<Id,EIP_Lead_Rental_Object__c> ruMap = new Map<Id,EIP_Lead_Rental_Object__c>([select EIP_Opportunity__c from EIP_Lead_Rental_Object__c where EIP_Opportunity__c in : OppIds]);
        List<Attachment> attachments = new List<Attachment>();
        system.debug(ruMap);
        for(Attachment file : Trigger.new) {
            Attachment newFile = file.clone();
            newFile.ParentId = ruMap.get(file.ParentId).Id;
            attachments.add(newFile);
        }
        // finally, insert the cloned attachments
        insert attachments;

    }

}

Every time an attachment gets attach to Opportunity..its not working for me !

Body:
Your ruMap has keys made out of EIP_Lead_Rental_Object__c ids. But you try to call get() on it using Opportunity Ids. This will never work. I'm surprised it doesn't throw you a null-related error, do you have some try-catch in there that just swallows the exception?

You probably need something like

Map<Id,EIP_Lead_Rental_Object__c> ruMap = new Map<Id,EIP_Lead_Rental_Object__c>();
for(EIP_Lead_Rental_Object__c obj : [select Id, EIP_Opportunity__c from EIP_Lead_Rental_Object__c where EIP_Opportunity__c in : OppIds]){
    ruMap.put(obj.EIP_Opportunity__c, obj);
}

and then you can

for(Attachment file : Trigger.new){
    if(ruMap.containsKey(file.ParentId)){
        Attachment newFile = file.clone();
        newFile.ParentId = ruMap.get(file.ParentId).Id;
        attachments.add(newFile);
    }
}


问:
How to automate the pipelining in azure devops using rest api
I would look to automate process of creating build, releases in azure devops. I do understand that rest api's exist. But will they help to automate the process and can this be done in node.js?</p>

答:
yes. Azure Devops do have API. I do not have experiences in node.js.

Docu for Azure DevOps REST API here:

https://learn.microsoft.com/en-us/rest/api/azure/devops/?view=azure-devops-rest-5.0

You may find node.js libraries here:

https://github.com/microsoft/azure-devops-node-api


问:
Detecting if IE7 or lower with conditional comments and javascript not working
I'm trying to check if a person is using anything IE with version less than 8 or anything else.

I use conditional comments to declare boolean..

```<code><!--[if lt IE 8]>
<script type="text/javascript">var badIE = true;</script>
<![endif]-->
</code>```

And now I check in my js file the boolean like this:

```<code>if (badIE == true){
    alert('You have bad IE!');
} else {
    alert('Bueno!');
}
</code>```

If I use IE7 or IE6, it alerts that "You have bad IE!". If I use anything else, it should alert "Bueno!", but it does not. What is the problem?

答:
Not a direct answer (Neal has you covered), but you may also be interested in: http://code.google.com/p/ie7-js/

From the page:
IE7.js is a JavaScript library to make Microsoft Internet Explorer behave like a standards-compliant browser. It fixes many HTML and CSS issues and makes transparent PNG work correctly under IE5 and IE6.

Though if you're using jQuery, keep in mind that it does many of the same things as this library.

Body:
I'm trying to check if a person is using anything IE with version less than 8 or anything else.

I use conditional comments to declare boolean..

And now I check in my js file the boolean like this:

if (badIE == true){
    alert('You have bad IE!');
} else {
    alert('Bueno!');
}

If I use IE7 or IE6, it alerts that "You have bad IE!". If I use anything else, it should alert "Bueno!", but it does not. What is the problem?


问:
Why I can't checked more than checkboxes?
Using Flask I populated a table and tried to create something which made it possible for clicking in any part of row and "checked" the checkbox input. But I can't checked more than one.

Created a var to check if the input is "checked", if no, checked! if yes, make possible unchecked the box at any part of tr.

```<code>  $("table tbody tr").on('click',function(){
    var checked = $("input:checkbox").is(':checked');
    if(checked){
     $("input:checkbox",this).prop('checked', false);
     console.log(checked);
    }else{
     console.log(checked);
     $("input:checkbox",this).prop('checked', true);
    }
</code>```

HTML:

```<code><table class="table table-responsive" id="osTable" width="100%" cellspacing="0" align="center">
        <thead align="center">
            <tr>
             <th>#</th>
             <th>Id</th>
             <th>Name</th>
            </tr>
        </thead>
        <tbody>
         {%for data in data%}
         <tr>
           <td><input type="checkbox" name="{{data[0]}}"></td>
           <td>{{data[0]}}</td>
           <td>{{data[1]}}</td>

         </tr>
         {%endfor%}
        </tbody>
    </table>
</code>```

答:
Change

```<code>$("input:checkbox").is(':checked');
</code>```

to

```<code>$("input:checkbox", this).is(':checked');
</code>```

You only want to check if the checkbox in your row (the this by the binding your doing) is checked or not.  You are currently checking if any checkbox any where is checked.  Giving the selector the this as the second argument limits the scope of the selector to just the row that was clicked.

Body:
Using Flask I populated a table and tried to create something which made it possible for clicking in any part of row and "checked" the checkbox input. But I can't checked more than one.

Created a var to check if the input is "checked", if no, checked! if yes, make possible unchecked the box at any part of tr.

  $("table tbody tr").on('click',function(){
    var checked = $("input:checkbox").is(':checked');
    if(checked){
     $("input:checkbox",this).prop('checked', false);
     console.log(checked);
    }else{
     console.log(checked);
     $("input:checkbox",this).prop('checked', true);
    }

HTML:

             #
             Id
             Name

         {%for data in data%}

           <input type="checkbox" name="{{data[0]}}">
           {{data[0]}}
           {{data[1]}}

         {%endfor%}

Body:
Change

$("input:checkbox").is(':checked');

to

$("input:checkbox", this).is(':checked');

You only want to check if the checkbox in your row (the this by the binding your doing) is checked or not.  You are currently checking if any checkbox any where is checked.  Giving the selector the this as the second argument limits the scope of the selector to just the row that was clicked.


问:
Is there an easy way to completely freeze object and its children in Javascript, (Deep Freeze)?
Often you have to pass an object as parameter. Functions accessing those objects are pass by reference and can change original object. Which depending on situation can be  unwanted outcome. So is there a way to freeze object. I know about Object.freeze()

But it doesn't affect objects/arrays inside it.

For example

```<code>a = { arr: [1,2,3]};
Object.freeze(a);
a.arr.push(4); // still works
</code>```

答:
Checkout deep-freeze it does recursively Object.freeze() on objects

Here's how they implement it

```<code>function deepFreeze (o) {
  Object.freeze(o);

  Object.getOwnPropertyNames(o).forEach(function (prop) {
    if (o.hasOwnProperty(prop)
    && o[prop] !== null
    && (typeof o[prop] === "object" || typeof o[prop] === "function")
    && !Object.isFrozen(o[prop])) {
      deepFreeze(o[prop]);
    }
  });

  return o;
};
</code>```

Body:
Often you have to pass an object as parameter. Functions accessing those objects are pass by reference and can change original object. Which depending on situation can be  unwanted outcome. So is there a way to freeze object. I know about Object.freeze()

But it doesn't affect objects/arrays inside it.

For example

a = { arr: [1,2,3]};
Object.freeze(a);
a.arr.push(4); // still works

Body:
Checkout deep-freeze it does recursively Object.freeze() on objects

Here's how they implement it

function deepFreeze (o) {
  Object.freeze(o);

  Object.getOwnPropertyNames(o).forEach(function (prop) {
    if (o.hasOwnProperty(prop)
    && o[prop] !== null
    && (typeof o[prop] === "object" || typeof o[prop] === "function")
    && !Object.isFrozen(o[prop])) {
      deepFreeze(o[prop]);
    }
  });

  return o;
};


问:
Wordpress - Site with different content for each user
I'm developing a wordpress website where users, after paying and becoming member, will have access to private contents. These contents have to be different for each user: when a user become member, I need to generate a individual schedule based on data entered by the user. When a user access to his personal page, he needs to see his personal schedule. For the part of membership I found my usefull plugins but for showing personal content I haven't found anything that can help me.
How can I achieve it? Is there any plugin that can fit my needs? If I need to entirely code it, how can I do for inserting this feature in classic multi-purpose wordpress theme?
Thank you</p>

答:
If you create new role "member" for users. You can check this when they visit your page with this code:

```<code>$user = wp_get_current_user();
if ( in_array( 'member', $user->roles ) ) {
    //Your code if user is "member"
}
</code>```

wp_get_current_user(); returned WP_User object. For more details see documentation

Body:
If you create new role "member" for users. You can check this when they visit your page with this code:

$user = wp_get_current_user();
if ( in_array( 'member', $user->roles ) ) {
    //Your code if user is "member"
}

wp_get_current_user(); returned WP_User object. For more details see documentation


问:
Powershell nested json to repeating csv
Kind of similar to Convert nested JSON array into separate columns in CSV file but instead of flattened csv (ie discipline_01, discicpline_01) exporting to multiple lines of the csv:

```<code>{
"data": [{
    "attributes": {
        "id": 10011,
        "title": "Test procedure",
        "slug": "slug",
        "url": "http://test.test",
        "disciplines": [
            "discipline_a",
            "discipline_b",
            "discipline_c"
        ]
    }
}]
}
</code>```

export to

```<code>"id","title","slug","url","discipline"
"10011","Test procedure","slug","http://test.test","discipline_a"
"10011","Test procedure","slug","http://test.test","discipline_b"
"10011","Test procedure","slug","http://test.test","discipline_c"
</code>```

Thanks to Export fields with nested values from JSON to CSV I've gotten this far:

```<code>$foo = invoke-restmethod $restquery -headers $headers
$foo |
select -ExpandProperty data |
select -ExpandProperty attributes |
select id, title, slug, url, disciplines |
   foreach {
        $_.disciplines = $_disciplines -join ' '
        $_ |
export-csv c:\outfile.csv -notypeinformation
</code>```

This gives me

```<code>"10011","Test procedure","slug","http://test.test","discipline_a discipline_b discipline_c"
</code>```

But no clue how to get it to:

```<code>"id","title","slug","url","discipline"
"10011","Test procedure","slug","http://test.test","discipline_a"
"10011","Test procedure","slug","http://test.test","discipline_b"
"10011","Test procedure","slug","http://test.test","discipline_c"
</code>```

Any help is appreciated.

答:
While your posted Json is invalid,

this might do:

```<code>## Q:\Test\2019\05\31\SO_56401395.ps1
$foo = invoke-restmethod $restquery -headers $headers

$Data = $foo.data.attributes | ForEach-Object {
    foreach ($discipline in $_.disciplines}(
        [PSCustomObject]@{
            id         = $_.id
            title      = $_.title
            slug       = $_.slug
            url        = $_.url
            discipline = $discipline
        }
    }
}
$Data | Export-Csv c:\outfile.csv -NoTypeInformation
</code>```

Title: Powershell nested json to repeating csv

Body:
Kind of similar to Convert nested JSON array into separate columns in CSV file but instead of flattened csv (ie discipline_01, discicpline_01) exporting to multiple lines of the csv:

{
"data": [{
    "attributes": {
        "id": 10011,
        "title": "Test procedure",
        "slug": "slug",
        "url": "http://test.test",
        "disciplines": [
            "discipline_a",
            "discipline_b",
            "discipline_c"
        ]
    }
}]
}

export to

"id","title","slug","url","discipline"
"10011","Test procedure","slug","http://test.test","discipline_a"
"10011","Test procedure","slug","http://test.test","discipline_b"
"10011","Test procedure","slug","http://test.test","discipline_c"

Thanks to Export fields with nested values from JSON to CSV I've gotten this far:

$foo = invoke-restmethod $restquery -headers $headers
$foo |
select -ExpandProperty data |
select -ExpandProperty attributes |
select id, title, slug, url, disciplines |
   foreach {
        $_.disciplines = $_disciplines -join ' '
        $_ |
export-csv c:\outfile.csv -notypeinformation

This gives me

"10011","Test procedure","slug","http://test.test","discipline_a discipline_b discipline_c"

But no clue how to get it to:

"id","title","slug","url","discipline"
"10011","Test procedure","slug","http://test.test","discipline_a"
"10011","Test procedure","slug","http://test.test","discipline_b"
"10011","Test procedure","slug","http://test.test","discipline_c"

Any help is appreciated.

Body:
While your posted Json is invalid,

this might do:

## Q:\Test\2019\05\31\SO_56401395.ps1
$foo = invoke-restmethod $restquery -headers $headers

$Data = $foo.data.attributes | ForEach-Object {
    foreach ($discipline in $_.disciplines}(
        [PSCustomObject]@{
            id         = $_.id
            title      = $_.title
            slug       = $_.slug
            url        = $_.url
            discipline = $discipline
        }
    }
}
$Data | Export-Csv c:\outfile.csv -NoTypeInformation


问:
How to make a div have a fixed size?
I made a site so when you click the button 30px it changes the font inside the div.

I have a ul inside it with the bottons. When I change the size of font the div expands and the nav buttons move with it as well.

How do i make it so it stays fixed but the fonts can still change.

答:
```<code><div class="ai">a b c d e f</div> // something like ~100px
<div class="ai">a b c d e</div> // ~80
<div class="ai">a b c d</div> // ~60

<script>

function _reWidthAll_div(classname) {

var _maxwidth = 0;

    $(classname).each(function(){

    var _width = $(this).width();

    _maxwidth = (_width >= _maxwidth) ? _width : _maxwidth; // define max width
    });

$(classname).width(_maxwidth); // return all div same width

}

_reWidthAll_div('.ai');

</script>
</code>```

Title: How to make a div have a fixed size?


问:
Xcode 10 Could not find any available simulators for iOS when install Carthage dependencies
I'm trying to install Carthage dependencies in my Xcode project with the

```<code>Carthage bootstrap --platform iOS
</code>```

command line but It's fail and I have this message in my terminal:

```<code>Could not find any available simulators for iOS
</code>```

I've just updated Xcode with the 10 version then the simulators are already installed.

I've also tried to delete each one and reinstall only one with iOS 12.

I have still the same error.

答:
In my case it was solved.

Close xcode

rm -rf ~/Library/Developer/CoreSimulator/Devices/

Open xcode

Create new project

Run empty project on any simulator

execute carthage update

Body:
I'm trying to install Carthage dependencies in my Xcode project with the

Carthage bootstrap --platform iOS

command line but It's fail and I have this message in my terminal:

Could not find any available simulators for iOS

I've just updated Xcode with the 10 version then the simulators are already installed.

I've also tried to delete each one and reinstall only one with iOS 12.

I have still the same error.


问:
Hide a list except the selected list option
I need some help with a nested list, what I want to do is to show one of the list options and hide the rest of the list,  a great example that I saw was in the filesonic.com languages selector or netlog status change in the header.

```<code><ul class="links">
  <li class="us">United States</li>
  <li class="canada">Canada</li>
  <li class="france">France</li>
  <li class="china">China</li>
  <li class="englande">England</li>
</code>```

United States is the default but when someone click on France, the rest of the list will hide and show will show.

thanks in advance.

答:
A quick n dirty sample with comments(you can improvize it based on your needs):

Working example @ http://jsfiddle.net/dCZpx/

```<code><div style="width: 100px">
    <div style="background-color: #FFDDEE" id="country">Click here to Select Country</div>
    <ul class="links">
        <li class="us">United States</li>
        <li class="canada">Canada</li>
        <li class="france">France</li>
        <li class="china">China</li>
        <li class="englande">England</li>
    </ul>
    <script type="text/javascript">
        $(function(){

            //Bind the Click handler for the box that displays the selected Country
            $("#country").click(function(){
                //When the Country Box is clicked, show all the country names except the selected one
                $(".links li").not("." + $(this).data("current")).show("slow");
            });

            //First Hide all the Country Names list
            $(".links li").hide();

            //Bind OnClick handler to all list elements which are children of .links
            $(".links li").click(function(){
                //Set the currently selected country in the data attribute of the #country element.
                $("#country").data("current", $(this).attr("class"));
                //Set the text of the #country div to the selected country name
                $("#country").text($(this).text());
                //Now hide all the list elements
                $(".links li").hide("slow");
            });
               $(".links li.us").click();
        });
    </script>
</div>
</code>```

Body:
I need some help with a nested list, what I want to do is to show one of the list options and hide the rest of the list,  a great example that I saw was in the filesonic.com languages selector or netlog status change in the header.

United States

Canada

France

China

England

United States is the default but when someone click on France, the rest of the list will hide and show will show.

thanks in advance.

Body:
A quick n dirty sample with comments(you can improvize it based on your needs):

Working example @ http://jsfiddle.net/dCZpx/

<div style="width: 100px">
    <div style="background-color: #FFDDEE" id="country">Click here to Select Country</div>
    <ul class="links">
        <li class="us">United States</li>
        <li class="canada">Canada</li>
        <li class="france">France</li>
        <li class="china">China</li>
        <li class="englande">England</li>
    </ul>
    <script type="text/javascript">
        $(function(){

            //Bind the Click handler for the box that displays the selected Country
            $("#country").click(function(){
                //When the Country Box is clicked, show all the country names except the selected one
                $(".links li").not("." + $(this).data("current")).show("slow");
            });

            //First Hide all the Country Names list
            $(".links li").hide();

            //Bind OnClick handler to all list elements which are children of .links
            $(".links li").click(function(){
                //Set the currently selected country in the data attribute of the #country element.
                $("#country").data("current", $(this).attr("class"));
                //Set the text of the #country div to the selected country name
                $("#country").text($(this).text());
                //Now hide all the list elements
                $(".links li").hide("slow");
            });
               $(".links li.us").click();
        });
    </script>
</div>


问:
Email validation C# asp.net
I used the following pattern to validate my email field.

```<code>    return Regex.IsMatch(email,
                 @"^(?("")("".+?(?<!\\)""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
                 @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-0-9a-z]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$",
                 RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250));
</code>```

It uses the following reference:
https://learn.microsoft.com/en-us/dotnet/standard/base-types/how-to-verify-that-strings-are-in-valid-email-format

My requirement is to have maximum number of 64 characters for user part, and max length for whole email string is 254 characters.  The pattern in the reference only allow max 134 characters. Can someone give clear explanation of the meaning for the pattern? What is the right pattern to achieve my goal?

答:
The code you cited is over-engineered, all you need to verify an email is to check for an at symbol and for a dot. If you need anything more precise, you are probably at a point where you actually need to email the recipient and ask for their confirmation that they hold the email, something that is simpler than a complex regex, and which provides much more precision.

Such a regex would simply be:

```<code>.+@.+\..+
</code>```

Commentated below

```<code>.+      At least one of any character
@       The at symbol
.+      At least one character
\.      The . symbol
.+      At least one character
</code>```

Of course this means that some emails might be accepted as false positives, like tomas@company.c when the user intended tomas@company.com , but even if you design the most robust of regexes, one that checks against a list of accepted TLDs, you will never catch tomas@company.co, and you might insert positive falses like tomas@company.blockchain when a new TLD is released and your code isn't updated.

So just keep it simple.

Title: Email validation C# asp.net

Body:
I used the following pattern to validate my email field.

    return Regex.IsMatch(email,
                 @"^(?("")("".+?(?<!\\)""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
                 @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-0-9a-z]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$",
                 RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250));

It uses the following reference:
https://learn.microsoft.com/en-us/dotnet/standard/base-types/how-to-verify-that-strings-are-in-valid-email-format

My requirement is to have maximum number of 64 characters for user part, and max length for whole email string is 254 characters.  The pattern in the reference only allow max 134 characters. Can someone give clear explanation of the meaning for the pattern? What is the right pattern to achieve my goal?

Body:
The code you cited is over-engineered, all you need to verify an email is to check for an at symbol and for a dot. If you need anything more precise, you are probably at a point where you actually need to email the recipient and ask for their confirmation that they hold the email, something that is simpler than a complex regex, and which provides much more precision.

Such a regex would simply be:

.+@.+\..+

Commentated below

.+      At least one of any character
@       The at symbol
.+      At least one character
\.      The . symbol
.+      At least one character

Of course this means that some emails might be accepted as false positives, like tomas@company.c when the user intended tomas@company.com , but even if you design the most robust of regexes, one that checks against a list of accepted TLDs, you will never catch tomas@company.co, and you might insert positive falses like tomas@company.blockchain when a new TLD is released and your code isn't updated.

So just keep it simple.


问:
How to remove the title bar in mintty cygwin
How do i remove the title bar in the cygwin mintty terminal window ?
there is no option in the options -> window configuration

答:
One way would be using mintty's -B (--Border) option when invoking it. Check [GitHub.Mintty]: mintty (or man mintty) for more details.

As a note, on my (Win 10) machine mintty's window quickly disappears, when specifying the option.


问:
git: fatal: I don't handle protocol 'http'
I copy and pasted an git clone command from a web page: https://fedorahosted.org/ibus-typing-booster/

I got this:

```<code>user@host> git clone http://git.fedorahosted.org/git/ibus-typing-booster.git

Cloning into 'ibus-typing-booster'...
fatal: I don't handle protocol 'http'
</code>```

答:
My solution:

Type: git clone .

Copy the repository url and paste it after of git clone .

Move the cursor to position between git clone and https://... .

Delete space if it had between git clone and https://... until
have git clonehttps://...

Re-add the space and press Enter.

Body:
I copy and pasted an git clone command from a web page: https://fedorahosted.org/ibus-typing-booster/

I got this:

user@host> git clone http://git.fedorahosted.org/git/ibus-typing-booster.git

Cloning into 'ibus-typing-booster'...
fatal: I don't handle protocol 'http'


问:
How to pass multiple parameters to SystemUtil.Run using vbscript and UFT?
I need to call an Executable file that needs some parameters in order to be run successfully.
I am using SystemUtil.Run
I know the syntax to use it but I don't really get how to make it work when muliutple parameters are needed.

i tried sending all of them in a string

```<code> systemutil.Run "c:\file.exe","param1,param2"
</code>```

and with the hint given

```<code>systemutil.Run "c:\file.exe",[param1,param2]
</code>```

also with a string

```<code>systemutil.run "C:\file.exe", ""&param1&""&","&""&param2&""
</code>```

still I am not sure how to make it work.

Any ideas on how to do this?

答:
Try the below.

```<code>systemutil.run "C:\file.exe","param1 param2 param3"
</code>```

If you have spaces in your param then use the below approach.

```<code>systemutil.run "C:\file.exe","param1""param 2""param 3"
</code>```

Body:
I need to call an Executable file that needs some parameters in order to be run successfully.
I am using SystemUtil.Run
I know the syntax to use it but I don't really get how to make it work when muliutple parameters are needed.

i tried sending all of them in a string

 systemutil.Run "c:\file.exe","param1,param2"

and with the hint given

systemutil.Run "c:\file.exe",[param1,param2]

also with a string

systemutil.run "C:\file.exe", ""&param1&""&","&""&param2&""

still I am not sure how to make it work.

Any ideas on how to do this?

Body:
Try the below.

systemutil.run "C:\file.exe","param1 param2 param3"

If you have spaces in your param then use the below approach.

systemutil.run "C:\file.exe","param1""param 2""param 3"


问:
Sending Bearer Token with HttpPost in Android
I couldn't find a way to authenticate my app with my server using the Bearer token I had created. it works perfectly with Postman though.

I've tried using UTF-8 encoding, using ?access_token in url, tried a lot of answers I found on Stackoverflow.

```<code>HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("https://dmyzda2o.ui.nabu.casa/api/services/script/turn_on");
//httpPost.addHeader("Accept-Language", "he");
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
nameValuePair.add(new BasicNameValuePair("Authorization", "Bearer eyJ0NiJ9.eyJpc3MiOiJmOWVkZDI5YjY2MTE0Mjc3YNDdmMzIwMWI2ZCIsImlhdCI6MTU1OTIwMjYwOCwiZXhwIjoxODc0NTYyNjA4fQ.HEb3b6kpW6OzAxcLumS8DlJWmZVAWfn0Lg84seBZGpQ"));
nameValuePair.add(new BasicNameValuePair("Content-Type", "application/json"));
nameValuePair.add(new BasicNameValuePair("entity_id", "script.gt11"));
Log.v("nameValue","entered");

try {
    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair, HTTP.UTF_8));
</code>```

The error I get is 401 Unauthorized on every attempt.

答:
I'm using Volley, but when I set up the headers, I do it with this:</p>

```<code>HashMap<String, String> headers = new HashMap<String, String>();
    String authValue = "Bearer " + apiToken;
    headers.put("Authorization", authValue);
    headers.put("Accept", "application/json; charset=UTF-8");
    headers.put("Content-Type", "application/json; charset=UTF-8");
</code>```

Body:
I couldn't find a way to authenticate my app with my server using the Bearer token I had created. it works perfectly with Postman though.

I've tried using UTF-8 encoding, using ?access_token in url, tried a lot of answers I found on Stackoverflow.

HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("https://dmyzda2o.ui.nabu.casa/api/services/script/turn_on");
//httpPost.addHeader("Accept-Language", "he");
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
nameValuePair.add(new BasicNameValuePair("Authorization", "Bearer eyJ0NiJ9.eyJpc3MiOiJmOWVkZDI5YjY2MTE0Mjc3YNDdmMzIwMWI2ZCIsImlhdCI6MTU1OTIwMjYwOCwiZXhwIjoxODc0NTYyNjA4fQ.HEb3b6kpW6OzAxcLumS8DlJWmZVAWfn0Lg84seBZGpQ"));
nameValuePair.add(new BasicNameValuePair("Content-Type", "application/json"));
nameValuePair.add(new BasicNameValuePair("entity_id", "script.gt11"));
Log.v("nameValue","entered");

try {
    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair, HTTP.UTF_8));

The error I get is 401 Unauthorized on every attempt.

Body:
I'm using Volley, but when I set up the headers, I do it with this:

HashMap<String, String> headers = new HashMap<String, String>();
    String authValue = "Bearer " + apiToken;
    headers.put("Authorization", authValue);
    headers.put("Accept", "application/json; charset=UTF-8");
    headers.put("Content-Type", "application/json; charset=UTF-8");


问:
Ensure a tag is present and start with cva_ for all resources in Azure
is it possible to ensure a tag is present and start with cva_ for all resources in Azure with Azure policy ?

I'm finding difficulty what field type to use to match for tagname. This is to look for any tag on any resource and validate that it contains a tag starting with "cva_"

答: You may use Azure Policy to archive this requirement. You may use "ensure tag is present" Az Policy or "Append tag and its default value" Az Policy. Both are built in and you may select tag name and/or value durring Az Policy Assigment.</p>