问:
PHP string replace the first and last occurance
I am trying to replace the occurrence of li tag with a tag but I also replace the other lis used in the string.

for example I have this:

```<code><li id="item" class="list-item" href="#">Item</li>
</code>```

but I want to replace the li tags without the list-item class name replaced.

if I do :

```<code>$f = array( '><a', 'li' );
$r = array( '', 'a' );
// output the menu
echo str_replace( $f, $r, $menu );
</code>```

then the class name list-item becomes ast-item where li is replaced with a.

How can I just replace the li tag and not all the instance of li?

答:
Try something like this:</p>

```<code>$string = '<li id="item" class="list-item" href="#">Item</li>';
$string = preg_replace("/<li\s(.+?)>(.+?)<\/li>/is", "<a $1>$2</a>", $string);
echo($string);
</code>```

Body:
I am trying to replace the occurrence of li tag with a tag but I also replace the other lis used in the string.

for example I have this:

Item

but I want to replace the li tags without the list-item class name replaced.

if I do :

$f = array( '><a', 'li' );
$r = array( '', 'a' );
// output the menu
echo str_replace( $f, $r, $menu );

then the class name list-item becomes ast-item where li is replaced with a.

How can I just replace the li tag and not all the instance of li?

Body:
Try something like this:

$string = '<li id="item" class="list-item" href="#">Item</li>';
$string = preg_replace("/<li\s(.+?)>(.+?)<\/li>/is", "<a $1>$2</a>", $string);
echo($string);


来源: stackexchange

问:
regex validate height without apostrophe
I am needing to validate person's height to feet and inches without the use of single or double quotes.  Here is an example I am looking for:

508 ==> 5' 8"

Zero's are used as place holders in this requirement.  Additionally, I need to check for valid inches but must have placeholder:

08 ==> 8 inches valid

8  ==> 8 inches invalid (missing placeholder)

13 ==> invalid (11 is max)

Feet and inches together:

511 ==> 5'11" (valid)

512 ==> 5'12" (invalid, should be written as 600)

513 ==> 5'13" (invalid, should be written as 601)

I have tried the following:

^(\d{1,5})((\s?)(-?)(\s?)([0-9]|(1[0-1])))?$

but this does not check for placeholder neither does it handle numbers greater than 12.

Appreciate any help in resolving this!

ContentLicense: CC BY-SA 3.0

Body:
Try this:

^[0-9]*((0[0-9])|(1[01]))$

It means:

[0-9]* 0 or more 0-9 characters

0[0-9] followed by 00 to 09

1[01] OR 10 to 11

Try it here.


问:
how to get previous value of textbox in jquery on change event

 $(".whitebox").on('change', function () {
       var previousAmt = $(this).data("old"); //  i want previous value
        var id = this.id;
        var slpitid = id.split("_");

        var checkboxid = "#chck_" + slpitid[0];
        if ($(checkboxid).is(':checked')) {
            var tipFlag = true;
        }
        else {
            var tipFlag = false;
        }

        if (tipFlag === true)
        {
            $("#amounttipchange").modal('show');
        }
        //alert(previousAmount);
    });```

i want to store previous value on change event how can i perform in jquery  i am not able to store value using $(this).data("old"); any help will be appreciated

答:
You almost got this right, but you forgot to update the data-old in your code, below is an example and jsbin

```<code> $(".whitebox").on('change', function (event) {
   // on first change will be empty string
   // as no previous value was set
   var oldValue = event.target.dataset.old;
   console.log('old value', oldValue);

   // your code here

   // at the end assign new value to data-old attribute
   $(this).data('old', event.target.value);
   console.log(event.target.value);
 });
</code>```

http://jsbin.com/jasaqiwuwo/

Body:
 $(".whitebox").on('change', function () {
       var previousAmt = $(this).data("old"); //  i want previous value
        var id = this.id;
        var slpitid = id.split("_");

        var checkboxid = "#chck_" + slpitid[0];
        if ($(checkboxid).is(':checked')) {
            var tipFlag = true;
        }
        else {
            var tipFlag = false;
        }

        if (tipFlag === true)
        {
            $("#amounttipchange").modal('show');
        }
        //alert(previousAmount);
    });

i want to store previous value on change event how can i perform in jquery  i am not able to store value using $(this).data("old"); any help will be appreciated

Body:
You almost got this right, but you forgot to update the data-old in your code, below is an example and jsbin

 $(".whitebox").on('change', function (event) {
   // on first change will be empty string
   // as no previous value was set
   var oldValue = event.target.dataset.old;
   console.log('old value', oldValue);

   // your code here

   // at the end assign new value to data-old attribute
   $(this).data('old', event.target.value);
   console.log(event.target.value);
 });

http://jsbin.com/jasaqiwuwo/


问:
Make Sylius catalog only
Who has experience Sylius before? Is possible to close front end purchase module to make Sylius become like catalog only? That mean user only can preview product's detail but unable to make purchase. Sorry for my English.</p>

答:
Yes, definitely.
You would have to overwrite twig templates, routes, the checkout state machine. This may be helpful:
http://docs.sylius.org/en/latest/cookbook/checkout.html
From the top of my head, I would go with leaving just one state (or none), but you have to play with it. I've never tried it yet. Not sure if that's all you need...</p>

```<code>winzou_state_machine:
  sylius_order_checkout:
    class: "%sylius.model.order.class%"
    property_path: checkoutState
    graph: sylius_order_checkout
    state_machine_class: "%sylius.state_machine.class%"
    states:
      cart: ~
</code>```

Title: Make Sylius catalog only

Body:
Yes, definitely.
You would have to overwrite twig templates, routes, the checkout state machine. This may be helpful:
http://docs.sylius.org/en/latest/cookbook/checkout.html
From the top of my head, I would go with leaving just one state (or none), but you have to play with it. I've never tried it yet. Not sure if that's all you need...

winzou_state_machine:
  sylius_order_checkout:
    class: "%sylius.model.order.class%"
    property_path: checkoutState
    graph: sylius_order_checkout
    state_machine_class: "%sylius.state_machine.class%"
    states:
      cart: ~


问:
Integrate a function of three variables C++
I spent quiet some time looking on the internet to find a solution to this, maybe it's out there but nothing of what I saw helped me.

I have a function !

```<code>double integrand(double r, double phi, double theta)
</code>```

That I want to integrate with some given definite bounds over the three dimensions. I found multiple lines of code on the internet that implement single variable definite integrals numerical schemes. I was thinking to myself "well, I'll just integrate along one dimension after the other".

Algorithmically speaking what I wanted to do was :

```<code>double firstIntegral(double r, double phi) {
    double result = integrationFunction(integrand,lower_bound,upper_bound);
    return result;
}
</code>```

And simply do it again two more times. This works easily in languages like Matlab where I can create functions handler anywhere but I don't know how to do it in C++. I would have to first define a function that some r and phi will calculate integrand(r, phi, theta) for any theta and make it in C++ a function of one variable only but I don't know how to do that.

How can I compute the triple integral of my three-variables function in C++ using a one -dimensional integration routine (or anything else really...) ?

答:
This is a very slow and inexact version for integrals over cartesian coordinates, which should work with C++11.

It is using std::function and lambdas to implement the numerical integration. No steps have been taken to optimize this.

A template based solution could be much faster (by several orders of magnitude) than this, because it may allow the compiler to inline and simplify some of the code.

```<code>#include<functional>
#include<iostream>

static double integrand(double /*x*/, double y, double /*z*/)
{
  return y;
}

double integrate_1d(std::function<double(double)> const &func, double lower, double upper)
{
  static const double increment = 0.001;

  double integral = 0.0;
  for(double x = lower; x < upper; x+=increment) {
    integral += func(x) * increment;
  }
  return integral;
}

double integrate_2d(std::function<double(double, double)> const &func, double lower1, double upper1, double lower2, double upper2)
{
  static const double increment = 0.001;

  double integral = 0.0;
  for(double x = lower2; x < upper2; x+=increment) {
    auto func_x = [=](double y){ return func(x, y);};
    integral += integrate_1d(func_x, lower1, upper1) * increment;
  }
  return integral;
}

double integrate_3d(std::function<double(double, double, double)> const &func,
                    double lower1, double upper1,
                    double lower2, double upper2,
                    double lower3, double upper3)
{
  static const double increment = 0.001;

  double integral = 0.0;
  for(double x = lower3; x < upper3; x+=increment) {
    auto func_x = [=](double y, double z){ return func(x, y, z);};
    integral += integrate_2d(func_x, lower1, upper1, lower2, upper2) * increment;
  }
  return integral;
}

int main()
{
  double integral = integrate_3d(integrand, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0);
  std::cout << "Triple integral: " << integral << std::endl;
  return 0;
}
</code>```

Body:
I spent quiet some time looking on the internet to find a solution to this, maybe it's out there but nothing of what I saw helped me.

I have a function !

double integrand(double r, double phi, double theta)

That I want to integrate with some given definite bounds over the three dimensions. I found multiple lines of code on the internet that implement single variable definite integrals numerical schemes. I was thinking to myself "well, I'll just integrate along one dimension after the other".

Algorithmically speaking what I wanted to do was :

double firstIntegral(double r, double phi) {
    double result = integrationFunction(integrand,lower_bound,upper_bound);
    return result;
}

And simply do it again two more times. This works easily in languages like Matlab where I can create functions handler anywhere but I don't know how to do it in C++. I would have to first define a function that some r and phi will calculate integrand(r, phi, theta) for any theta and make it in C++ a function of one variable only but I don't know how to do that.

How can I compute the triple integral of my three-variables function in C++ using a one -dimensional integration routine (or anything else really...) ?

Body:
This is a very slow and inexact version for integrals over cartesian coordinates, which should work with C++11.

It is using std::function and lambdas to implement the numerical integration. No steps have been taken to optimize this.

A template based solution could be much faster (by several orders of magnitude) than this, because it may allow the compiler to inline and simplify some of the code.

#include<functional>
#include<iostream>

static double integrand(double /*x*/, double y, double /*z*/)
{
  return y;
}

double integrate_1d(std::function<double(double)> const &func, double lower, double upper)
{
  static const double increment = 0.001;

  double integral = 0.0;
  for(double x = lower; x < upper; x+=increment) {
    integral += func(x) * increment;
  }
  return integral;
}

double integrate_2d(std::function<double(double, double)> const &func, double lower1, double upper1, double lower2, double upper2)
{
  static const double increment = 0.001;

  double integral = 0.0;
  for(double x = lower2; x < upper2; x+=increment) {
    auto func_x = [=](double y){ return func(x, y);};
    integral += integrate_1d(func_x, lower1, upper1) * increment;
  }
  return integral;
}

double integrate_3d(std::function<double(double, double, double)> const &func,
                    double lower1, double upper1,
                    double lower2, double upper2,
                    double lower3, double upper3)
{
  static const double increment = 0.001;

  double integral = 0.0;
  for(double x = lower3; x < upper3; x+=increment) {
    auto func_x = [=](double y, double z){ return func(x, y, z);};
    integral += integrate_2d(func_x, lower1, upper1, lower2, upper2) * increment;
  }
  return integral;
}

int main()
{
  double integral = integrate_3d(integrand, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0);
  std::cout << "Triple integral: " << integral << std::endl;
  return 0;
}


问:
Improper use of joins - how to rectify it
I would like to understand why revenue.RevC and revenue.RevD appears as Null even though when I run the separate nested selected on another tab it brings information up. </p>

<p>Can you spot a mistake that I am doing with my joins that prevents me from getting any data in my [rev col] and [rev del] columns. I believe it is due to using the left joins. Am I correct? </p>

```<code> with CTE as
 (
select count(tpt1.MovConID) as [Collections],
count(tpt2.MovConID) as [Count of Del],
sum (c1.[Chargeable Weight]) as [Total Col Chg Wt],
sum(c2.[Chargeable Weight]) as [Total Del Chg Wt],
revenueC.RevC as [Rev Col],
revenueD.RevD as [Rev Del]
from tptvehicle tptv
left JOIN tptHeader tpth ON tpth.VehicleID = tptV.VehicleID
left JOIN tptVehicleRevenueDaily tptrevenue on tptrevenue.VehicleReg = tptv.RegNo
left Join (select tpth.RunReference, tptV.VehicleID, sum(tptvehicle.Amount) as RevC from tptVehicleRevenueDaily tptvehicle
       inner join tptVehicle tptv on tptv.RegNo = tptvehicle.VehicleReg
       inner join tptHeader tptH on tptH.VehicleID = tptv.VehicleID
       inner join tptDetails tpt on tpt.RunID = tptH.RunID where tpt.RunType = 'C'
       group by tpth.RunReference, tptv.VehicleID) revenueC on revenueC.RunReference = Tpth.RunReference
Left Join (select tpth.RunReference, tptV.VehicleID, sum(tptvehicle.Amount) as RevD from tptVehicleRevenueDaily tptvehicle
       inner join tptVehicle tptv on tptv.RegNo = tptvehicle.VehicleReg
       Inner join tptHeader tptH on tptH.VehicleID = tptv.VehicleID
       Inner join tptDetails tpt on tpt.RunID = tptH.RunID where tpt.RunType = 'D'
       group by tpth.RunReference, tptv.VehicleID) revenueD on revenueD.VehicleID = TptV.VehicleID
 LEFT JOIN tptDetails tpt1 ON tpt1.RunID = tptH.RunID and tpt1.RunType = 'C'
 LEFT JOIN cgtConsignment c1 on c1.[Consignment Reference] = tpt1.MovConID
 LEFT JOIN tptDetails tpt2 on tpt2.RunID = tptH.RunID and tpt2.RunType = 'D'
 LEFT Join cgtConsignment c2 on c2.[Consignment Reference] = tpt2.MovConID
 where tpth.RunReference like 'bham-%' and
 tptH.JourneyDate >= @StartDate and
          tpth.JourneyDate <= @EndDate
          Group by revenueC.RevC, revenueD.RevD
 )
Select cte.collections, cte.[count of del], cte.[Total Col Chg Wt], cte.[Total Del Chg Wt], cte.[Rev Col], cte.[Rev Del]
from CTE
</code>```

答: Yes a left join will show you rows from the left hand side of the join (tptvehicle, tptHeader and tptVehicleRevenueDaily) even if no rows exist in your nested query... If you change it to an inner join, it will show only rows where these exist, however this will EXCLUDE vehicles which have no rows in this nested query (which are currently showing with nulls in those columns), do you want this?...</p>

Body:
I would like to understand why revenue.RevC and revenue.RevD appears as Null even though when I run the separate nested selected on another tab it brings information up.

Can you spot a mistake that I am doing with my joins that prevents me from getting any data in my [rev col] and [rev del] columns. I believe it is due to using the left joins. Am I correct?

 with CTE as
 (
select count(tpt1.MovConID) as [Collections],
count(tpt2.MovConID) as [Count of Del],
sum (c1.[Chargeable Weight]) as [Total Col Chg Wt],
sum(c2.[Chargeable Weight]) as [Total Del Chg Wt],
revenueC.RevC as [Rev Col],
revenueD.RevD as [Rev Del]
from tptvehicle tptv
left JOIN tptHeader tpth ON tpth.VehicleID = tptV.VehicleID
left JOIN tptVehicleRevenueDaily tptrevenue on tptrevenue.VehicleReg = tptv.RegNo
left Join (select tpth.RunReference, tptV.VehicleID, sum(tptvehicle.Amount) as RevC from tptVehicleRevenueDaily tptvehicle
       inner join tptVehicle tptv on tptv.RegNo = tptvehicle.VehicleReg
       inner join tptHeader tptH on tptH.VehicleID = tptv.VehicleID
       inner join tptDetails tpt on tpt.RunID = tptH.RunID where tpt.RunType = 'C'
       group by tpth.RunReference, tptv.VehicleID) revenueC on revenueC.RunReference = Tpth.RunReference
Left Join (select tpth.RunReference, tptV.VehicleID, sum(tptvehicle.Amount) as RevD from tptVehicleRevenueDaily tptvehicle
       inner join tptVehicle tptv on tptv.RegNo = tptvehicle.VehicleReg
       Inner join tptHeader tptH on tptH.VehicleID = tptv.VehicleID
       Inner join tptDetails tpt on tpt.RunID = tptH.RunID where tpt.RunType = 'D'
       group by tpth.RunReference, tptv.VehicleID) revenueD on revenueD.VehicleID = TptV.VehicleID
 LEFT JOIN tptDetails tpt1 ON tpt1.RunID = tptH.RunID and tpt1.RunType = 'C'
 LEFT JOIN cgtConsignment c1 on c1.[Consignment Reference] = tpt1.MovConID
 LEFT JOIN tptDetails tpt2 on tpt2.RunID = tptH.RunID and tpt2.RunType = 'D'
 LEFT Join cgtConsignment c2 on c2.[Consignment Reference] = tpt2.MovConID
 where tpth.RunReference like 'bham-%' and
 tptH.JourneyDate >= @StartDate and
          tpth.JourneyDate <= @EndDate
          Group by revenueC.RevC, revenueD.RevD
 )
Select cte.collections, cte.[count of del], cte.[Total Col Chg Wt], cte.[Total Del Chg Wt], cte.[Rev Col], cte.[Rev Del]
from CTE


问:
C++ String Interview Question
I was recently in a C++ technical interview, where I was given a bit of simple string manipulation code, which is intended to take a string and return a string that is comprised of the first and last n-characters, and then proceed to correct any bugs and to also make the function as efficient as possible, I came up with the solution below, however the interviewer claimed there was an even faster more optimal way:

Original code:

```<code>std::string first_last_n(int n, std::string s)
{
   std::string first_n = s.substr(0,n);
   std::string last_n = s.substr(s.size()-n-1,n);
   return first_n + last_n;
}
</code>```

My code:

```<code>bool first_last_n(const std::size_t& n, const std::string& s, std::string& r)
{
   if (s.size() < n)
      return false;
   r.reserve(2 * n);
   r.resize(0);
   r.append(s.data(),s.data() + n);
   r.append(s.data() + (s.size() - n), s.data() + s.size());
   return true;
}
</code>```

Summary of my changes:

Changed the interface to take a return string as reference (assuming RVO and rvalues are not available yet)

Removed temporary strings being constructed via substr

Passed input string as a const reference inorder to get around temporary instantiation of input

Fixed off-by-1 error in last_n string

Reduced the number of times each character is touched down to once, or twice (in the event of an overlapping scenario)

Placed a check in the event the string s's size is less than n, returning false for failure.

Assuming only native C++ is allowed, is there some other way of doing the above more efficiently or optimally?

Note 1: The original input string instance is not to be modified.

Note 2: All solutions must pass the following test case, otherwise they are not valid.

```<code>void test()
{
   {
      std::string s = "0123456789";
      std::string r = first_last_n(10,s);
      assert(r == "01234567890123456789");
   }

   {
      std::string s = "0123456789ABC0123456789";
      std::string r = first_last_n(10,s);
      assert(r == "01234567890123456789");
   }

   {
      std::string s = "1234321";
      std::string r = first_last_n(5,s);
      assert(r == "1234334321");
   }

}
</code>```

答:
This implementation should be fast:

```<code>inline std::string first_last_n(std::string::size_type n, const std::string& s)
{
    n = std::min(n, s.size());
    std::string ret;
    ret.reserve(2*n);
    ret.append(s.begin(), s.begin() + n);
    ret.append(s.end() - n, s.end());
    return ret;
}
</code>```

It passes all three unit tests.

When using GNU libstdc++, the line that declares & initializes ret is extremely fast because libstdc++ uses a global "empty string" variable. Thus, it's simply a pointer copy. Calls to begin and end on s are also fast because they will resolve to the const versions of begin and end, begin() const and end() const, so the internal representation of s is not "leaked". With libstdc++, std::string::const_iterator is const char*, which is a pointer type and random access iterator. Thus, when std::string::append<const char*>(const char*, const char*) calls std::distance to obtain the length of the input range, it is a pointer difference operation. Also, std::string::append<const char*>(const char*, const char*) results in something like a memmove. Finally, the reserve operation ensures that enough memory is available for the return value.

EDIT:
For the curious, here is the initialization of ret in the assembly output of MinGW g++ 4.5.0:

```<code>    movl    $__ZNSs4_Rep20_S_empty_rep_storageE+12, (%ebx)
</code>```

It's simply copying the pointer to the global "empty representation".

EDIT2:
Okay. I have now tested four variants with g++ 4.5.0 and Visual C++ 16.00.30319.01:

Variant 1 (the "c_str variant"):

```<code>inline std::string first_last_n(std::string::size_type n, const std::string& s)
{
   std::string::size_type s_size = s.size();
   n = std::min(n, s_size);
   std::string ret;
   ret.reserve(2*n);
   const char *s_cStr = s.c_str(), *s_cStr_end = s_cStr + s_size;
   ret.append(s_cStr, s_cStr + n);
   ret.append(s_cStr_end - n, s_cStr_end);
   return ret;
}
</code>```

Variant 2 (the "data string" variant):

```<code>inline std::string first_last_n(std::string::size_type n, const std::string& s)
{
   std::string::size_type s_size = s.size();
   n = std::min(n, s_size);
   std::string ret;
   ret.reserve(2*n);
   const char *s_data = s.data(), *s_data_end = s_data + s_size;
   ret.append(s_data, s_data + n);
   ret.append(s_data_end - n, s_data_end);
   return ret;
}
</code>```

Variant 3:

```<code>inline std::string first_last_n(std::string::size_type n, const std::string& s)
{
   std::string::size_type s_size = s.size();
   n = std::min(n, s_size);
   std::string ret(s);
   std::string::size_type d = s_size - n;
   return ret.replace(n, d, s, d, n);
}
</code>```

Variant 4 (my original code):

```<code>inline std::string first_last_n(std::string::size_type n, const std::string& s)
{
   n = std::min(n, s.size());
   std::string ret;
   ret.reserve(2*n);
   ret.append(s.begin(), s.begin() + n);
   ret.append(s.end() - n, s.end());
   return ret;
}
</code>```

The results for g++ 4.5.0 are:

Variant 4 is the fastest

Variant 3 is second (5% slower than variant 4)

Variant 1 is third (2% slower than variant 3)

Variant 2 is fourth (0.2% slower than variant 1)

The results for VC++ 16.00.30319.01 are:

Variant 1 is the fastest

Variant 2 is second (3% slower than variant 1)

Variant 4 is third (4% slower than variant 2)

Variant 3 is fourth (17% slower than variant 4)

Unsurprisingly, the variant that is fastest depends on the compiler. However, not knowing which compiler will be used I think that my variant is best because it is a familiar style of C++, it is the fastest when using g++, and it is not that much slower than variants 1 or 2 when using VC++.

One thing interesting from the VC++ results is that using c_str rather than data is faster. Perhaps that is why your interviewer said that there is a faster way than your implementation.

EDIT3:

Actually, I just thought about another variant:

Variant 5:

```<code>inline std::string first_last_n(std::string::size_type n, const std::string& s)
{
   n = std::min(n, s.size());
   std::string ret;
   ret.reserve(2*n);
   std::string::const_iterator s_begin = s.begin(), s_end = s.end();
   ret.append(s_begin, s_begin + n);
   ret.append(s_end - n, s_end);
   return ret;
}
</code>```

It's just like variant 4 except that the begin and end iterators for s are saved.

When variant 5 is tested, it actually beats out variant 2 (the data string variant) when using VC++:

Variant 1 is the fastest

Variant 5 is second (1.6% slower than variant 1)

Variant 2 is third (1.4% slower than variant 5)

Variant 4 is third (4% slower than variant 2)

Variant 3 is fourth (17% slower than variant 4)

OwnerDisplayName: Matthieu N.

LastEditorDisplayName: Matthieu N.

ContentLicense: CC BY-SA 2.5

Title: C++ String Interview Question

Body:
I was recently in a C++ technical interview, where I was given a bit of simple string manipulation code, which is intended to take a string and return a string that is comprised of the first and last n-characters, and then proceed to correct any bugs and to also make the function as efficient as possible, I came up with the solution below, however the interviewer claimed there was an even faster more optimal way:

Original code:

std::string first_last_n(int n, std::string s)
{
   std::string first_n = s.substr(0,n);
   std::string last_n = s.substr(s.size()-n-1,n);
   return first_n + last_n;
}

My code:

bool first_last_n(const std::size_t& n, const std::string& s, std::string& r)
{
   if (s.size() < n)
      return false;
   r.reserve(2 * n);
   r.resize(0);
   r.append(s.data(),s.data() + n);
   r.append(s.data() + (s.size() - n), s.data() + s.size());
   return true;
}

Summary of my changes:

Changed the interface to take a return string as reference (assuming RVO and rvalues are not available yet)

Removed temporary strings being constructed via substr

Passed input string as a const reference inorder to get around temporary instantiation of input

Fixed off-by-1 error in last_n string

Reduced the number of times each character is touched down to once, or twice (in the event of an overlapping scenario)

Placed a check in the event the string s's size is less than n, returning false for failure.

Assuming only native C++ is allowed, is there some other way of doing the above more efficiently or optimally?

Note 1: The original input string instance is not to be modified.

Note 2: All solutions must pass the following test case, otherwise they are not valid.

void test()
{
   {
      std::string s = "0123456789";
      std::string r = first_last_n(10,s);
      assert(r == "01234567890123456789");
   }

   {
      std::string s = "0123456789ABC0123456789";
      std::string r = first_last_n(10,s);
      assert(r == "01234567890123456789");
   }

   {
      std::string s = "1234321";
      std::string r = first_last_n(5,s);
      assert(r == "1234334321");
   }

}

Body:
This implementation should be fast:

inline std::string first_last_n(std::string::size_type n, const std::string& s)
{
    n = std::min(n, s.size());
    std::string ret;
    ret.reserve(2*n);
    ret.append(s.begin(), s.begin() + n);
    ret.append(s.end() - n, s.end());
    return ret;
}

It passes all three unit tests.

When using GNU libstdc++, the line that declares & initializes ret is extremely fast because libstdc++ uses a global "empty string" variable. Thus, it's simply a pointer copy. Calls to begin and end on s are also fast because they will resolve to the const versions of begin and end, begin() const and end() const, so the internal representation of s is not "leaked". With libstdc++, std::string::const_iterator is const char*, which is a pointer type and random access iterator. Thus, when std::string::append<const char*>(const char*, const char*) calls std::distance to obtain the length of the input range, it is a pointer difference operation. Also, std::string::append<const char*>(const char*, const char*) results in something like a memmove. Finally, the reserve operation ensures that enough memory is available for the return value.

EDIT:
For the curious, here is the initialization of ret in the assembly output of MinGW g++ 4.5.0:

    movl    $__ZNSs4_Rep20_S_empty_rep_storageE+12, (%ebx)

It's simply copying the pointer to the global "empty representation".

EDIT2:
Okay. I have now tested four variants with g++ 4.5.0 and Visual C++ 16.00.30319.01:

Variant 1 (the "c_str variant"):

inline std::string first_last_n(std::string::size_type n, const std::string& s)
{
   std::string::size_type s_size = s.size();
   n = std::min(n, s_size);
   std::string ret;
   ret.reserve(2*n);
   const char *s_cStr = s.c_str(), *s_cStr_end = s_cStr + s_size;
   ret.append(s_cStr, s_cStr + n);
   ret.append(s_cStr_end - n, s_cStr_end);
   return ret;
}

Variant 2 (the "data string" variant):

inline std::string first_last_n(std::string::size_type n, const std::string& s)
{
   std::string::size_type s_size = s.size();
   n = std::min(n, s_size);
   std::string ret;
   ret.reserve(2*n);
   const char *s_data = s.data(), *s_data_end = s_data + s_size;
   ret.append(s_data, s_data + n);
   ret.append(s_data_end - n, s_data_end);
   return ret;
}

Variant 3:

inline std::string first_last_n(std::string::size_type n, const std::string& s)
{
   std::string::size_type s_size = s.size();
   n = std::min(n, s_size);
   std::string ret(s);
   std::string::size_type d = s_size - n;
   return ret.replace(n, d, s, d, n);
}

Variant 4 (my original code):

inline std::string first_last_n(std::string::size_type n, const std::string& s)
{
   n = std::min(n, s.size());
   std::string ret;
   ret.reserve(2*n);
   ret.append(s.begin(), s.begin() + n);
   ret.append(s.end() - n, s.end());
   return ret;
}

The results for g++ 4.5.0 are:

Variant 4 is the fastest

Variant 3 is second (5% slower than variant 4)

Variant 1 is third (2% slower than variant 3)

Variant 2 is fourth (0.2% slower than variant 1)

The results for VC++ 16.00.30319.01 are:

Variant 1 is the fastest

Variant 2 is second (3% slower than variant 1)

Variant 4 is third (4% slower than variant 2)

Variant 3 is fourth (17% slower than variant 4)

Unsurprisingly, the variant that is fastest depends on the compiler. However, not knowing which compiler will be used I think that my variant is best because it is a familiar style of C++, it is the fastest when using g++, and it is not that much slower than variants 1 or 2 when using VC++.

One thing interesting from the VC++ results is that using c_str rather than data is faster. Perhaps that is why your interviewer said that there is a faster way than your implementation.

EDIT3:

Actually, I just thought about another variant:

Variant 5:

inline std::string first_last_n(std::string::size_type n, const std::string& s)
{
   n = std::min(n, s.size());
   std::string ret;
   ret.reserve(2*n);
   std::string::const_iterator s_begin = s.begin(), s_end = s.end();
   ret.append(s_begin, s_begin + n);
   ret.append(s_end - n, s_end);
   return ret;
}

It's just like variant 4 except that the begin and end iterators for s are saved.

When variant 5 is tested, it actually beats out variant 2 (the data string variant) when using VC++:

Variant 1 is the fastest

Variant 5 is second (1.6% slower than variant 1)

Variant 2 is third (1.4% slower than variant 5)

Variant 4 is third (4% slower than variant 2)

Variant 3 is fourth (17% slower than variant 4)


问:
Java: number of lines in a file without processing it
I need to know the number of lines of a file before processing it, because I need to know the number of lines before read it, or in the worst case escenario read it twice..... so I made this code but It not works.. so maybe is just not possible ?

```<code>InputStream inputStream2 = getInputStream();

BufferedReader reader = new BufferedReader(new InputStreamReader(getInputStream()));

String line;
int numLines = 0;
while ((line = reader.readLine()) != null) {
        numLines++;
}

TextFileDataCollection dataCollection = new TextFileDataCollection (numLines, 50);

BufferedReader reader2 = new BufferedReader(new InputStreamReader(inputStream2));

while ((line = reader2.readLine()) != null) {
        StringTokenizer st = new StringTokenizer(reader2.readLine(), ",");
        while (st.hasMoreElements()) {
            System.out.println(st.nextElement());
        }
}
</code>```

答:
You write

I need to know the number of lines of a file before processing it

but you don't present any file in your code; rather, you present only an InputStream.  This makes a difference, because indeed no, you cannot know the number of lines in the input without examining the input to count them.

If you had a file name, File object, or similar mechanism by which you could access the data more than once, then that would be straightforward, but a stream is not guaranteed to be associated with any persistent file -- it might convey data piped from another process or communicated over a network connection, for example.  Therefore, each byte provided by a generic InputStream can be read only once.

InputStream does provide an API for marking (mark()) a position and later returning to it (reset()), but stream implementations are not required to support it, and many do not.  Those that do support it typically impose a limit on how far past the mark you can read before invalidating it.  Readers support such a facility as well, with similar limitations.

Overall, if your only access to the data is via an InputStream, then your best bet is to process it without relying on advance knowledge of the contents.  But if you want to be able to read the data twice, to count lines first, for example, then you need to make your own arrangements to stash the data somewhere in order to ensure your ability to do so.  For example, you might copy it to a temporary file, or if you're prepared to rely on the input not being too large for it then you might store the contents in memory as a List of byte, byte[], char, or String.

Body:
I need to know the number of lines of a file before processing it, because I need to know the number of lines before read it, or in the worst case escenario read it twice..... so I made this code but It not works.. so maybe is just not possible ?

InputStream inputStream2 = getInputStream();

BufferedReader reader = new BufferedReader(new InputStreamReader(getInputStream()));

String line;
int numLines = 0;
while ((line = reader.readLine()) != null) {
        numLines++;
}

TextFileDataCollection dataCollection = new TextFileDataCollection (numLines, 50);

BufferedReader reader2 = new BufferedReader(new InputStreamReader(inputStream2));

while ((line = reader2.readLine()) != null) {
        StringTokenizer st = new StringTokenizer(reader2.readLine(), ",");
        while (st.hasMoreElements()) {
            System.out.println(st.nextElement());
        }
}


问:
Autosizing of TextView doesn't work (Android O)
I use new autosize feature added in support library 26. I read a documentation which can be found here :
https://developer.android.com/preview/features/autosizing-textview.html

I suppose that it should work this way: You can enable auto-sizing with this attribute: app:autoSizeTextType="uniform". I think that TextView should use all available space to display a whole text (not just a part - it shouldn't be cropped) and the textSize should be as big as possible. If you need to limit a maximum or minimum size of the text then you can use these two attributes:

```<code>app:autoSizeMinTextSize="XXsp" // (you can also use px or dp values.)
</code>```

or

```<code>app:autoSizeMaxTextSize="XXsp"
</code>```

So far so good. Let's say that I need a TextView with 56dp width. I have texts with a different length and I want to set these texts to this TextView. It should be automatically resized so it displays the whole text (all characters + not cropped) in the biggest possible textSize.

This is my TextView:

```<code><android.support.v7.widget.AppCompatTextView
        android:id="@+id/vName"
        style="@style/TextView.AutoSize"
        android:layout_width="56dp"
        android:gravity="bottom|center_horizontal"
        android:maxLines="1"
        app:autoSizeMinTextSize="1px"
        app:autoSizeTextType="uniform"
        app:layout_constraintBottom_toTopOf="@id/vGuideline"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent" />
</code>```

Unfortunately, the text view is cropped. I wanted to set this String as a text to the TextView above: "Groupa" but this is the result:

(TextView is inside ConstraintLayout with yellow circle background.)

As you can see the textview is not resized at all. Do you have any idea what to do?

Thanks.

答:
Have you tried setting all of the four attributes described in the link you posted?

E.g.

```<code>app:autoSizeTextType="uniform"
app:autoSizeMaxTextSize="13sp"
app:autoSizeMinTextSize="5sp"
app:autoSizeStepGranularity="1sp"
</code>```

You can also try setting both width and height to wrap_content, and setting minWidth and maxWidth to 56dp.

As poss also mentioned in the comments, maxlines seems to cause problems (for me as well), so try removing that (The autosizing should probably take care of this, by reducing the textsize).

Body:
I use new autosize feature added in support library 26. I read a documentation which can be found here :
https://developer.android.com/preview/features/autosizing-textview.html

I suppose that it should work this way: You can enable auto-sizing with this attribute: app:autoSizeTextType="uniform". I think that TextView should use all available space to display a whole text (not just a part - it shouldn't be cropped) and the textSize should be as big as possible. If you need to limit a maximum or minimum size of the text then you can use these two attributes:

app:autoSizeMinTextSize="XXsp" // (you can also use px or dp values.)

or

app:autoSizeMaxTextSize="XXsp"

So far so good. Let's say that I need a TextView with 56dp width. I have texts with a different length and I want to set these texts to this TextView. It should be automatically resized so it displays the whole text (all characters + not cropped) in the biggest possible textSize.

This is my TextView:

<android.support.v7.widget.AppCompatTextView
        android:id="@+id/vName"
        style="@style/TextView.AutoSize"
        android:layout_width="56dp"
        android:gravity="bottom|center_horizontal"
        android:maxLines="1"
        app:autoSizeMinTextSize="1px"
        app:autoSizeTextType="uniform"
        app:layout_constraintBottom_toTopOf="@id/vGuideline"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent" />

Unfortunately, the text view is cropped. I wanted to set this String as a text to the TextView above: "Groupa" but this is the result:

(TextView is inside ConstraintLayout with yellow circle background.)

As you can see the textview is not resized at all. Do you have any idea what to do?

Thanks.

Body:
Have you tried setting all of the four attributes described in the link you posted?

E.g.

app:autoSizeTextType="uniform"
app:autoSizeMaxTextSize="13sp"
app:autoSizeMinTextSize="5sp"
app:autoSizeStepGranularity="1sp"

You can also try setting both width and height to wrap_content, and setting minWidth and maxWidth to 56dp.

As poss also mentioned in the comments, maxlines seems to cause problems (for me as well), so try removing that (The autosizing should probably take care of this, by reducing the textsize).


问:
ASP.NET MVC - ViewModel for Listing from 2 Models at Once
I have a scenario where a user will submit a form that contains information for 2 models (database tables): Users and Requests. The data will also need to be listed together joined by UserID, i.e. to list all Requests made by all users, or by a specific user. So I also need to output the data from both tables.

My solution was to create ViewModel called UserRequests which would contain both of these models, however I am stuck on the implementation. I am not sure if it should look like the following:

```<code>public class UserRequestModel {
    public User User1 { get; set; }
    public Request Request1 { get; set; }
</code>```

To summarize, what the Index() function in the Controller will do, is get a query of requests by all users and list all fields from both tables (joined). So I need to somehow get the data from that query into the ViewModel to output it and have no idea how to set up the ViewModel in order to do so. Any insight would be appreciated. Thanks!

答:
The only thing I can think of is what you will get is one User and one Request which in your post seams like you will get more than one.

I would change the properties to Lists, IEnumerables or Arrays depending on what you prefer and then when you are getting the posts from the database, make a ToList(), ToArray() or similar.

```<code>public class UserRequestModel {
  public List<User> Users { get; set; }
  public List<Request> Requests { get; set; }
}
</code>```

And when fetching the data you use the extensionmethod you like.

```<code>var Users = dbcontext.Users.Where(x => x.ex == example).ToList()
</code>```

Body:
I have a scenario where a user will submit a form that contains information for 2 models (database tables): Users and Requests. The data will also need to be listed together joined by UserID, i.e. to list all Requests made by all users, or by a specific user. So I also need to output the data from both tables.

My solution was to create ViewModel called UserRequests which would contain both of these models, however I am stuck on the implementation. I am not sure if it should look like the following:

public class UserRequestModel {
    public User User1 { get; set; }
    public Request Request1 { get; set; }

To summarize, what the Index() function in the Controller will do, is get a query of requests by all users and list all fields from both tables (joined). So I need to somehow get the data from that query into the ViewModel to output it and have no idea how to set up the ViewModel in order to do so. Any insight would be appreciated. Thanks!

Body:
The only thing I can think of is what you will get is one User and one Request which in your post seams like you will get more than one.

I would change the properties to Lists, IEnumerables or Arrays depending on what you prefer and then when you are getting the posts from the database, make a ToList(), ToArray() or similar.

public class UserRequestModel {
  public List<User> Users { get; set; }
  public List<Request> Requests { get; set; }
}

And when fetching the data you use the extensionmethod you like.

var Users = dbcontext.Users.Where(x => x.ex == example).ToList()


问:
Excel - Sum values based on strings in separate cell
I have an excel spreadsheet with a long list of names.  The names appear multiple times each in their own row.  I would like to evaluate a cell in each row that corresponds to a name and sum it to only one cell.

```<code>Name  Value  Sum
John    1
John    0
John    1     2
Mike    1
Mike    0     1
Sarah   1
Sarah   1
Sarah   1     3
</code>```

I am not sure of the best and most efficient way of going about this where I can sum all of the values for each specific name into a single value without getting duplicates.

答:
Pivot tables, for sure.  This is the epitome of pivot table applications.  When god created pivot tables, he actually used this exact example when he was presenting his idea to the Board of Microsoft.

Here you go.

Body:
I have an excel spreadsheet with a long list of names.  The names appear multiple times each in their own row.  I would like to evaluate a cell in each row that corresponds to a name and sum it to only one cell.

Name  Value  Sum
John    1
John    0
John    1     2
Mike    1
Mike    0     1
Sarah   1
Sarah   1
Sarah   1     3

I am not sure of the best and most efficient way of going about this where I can sum all of the values for each specific name into a single value without getting duplicates.


问:
I am trying to use a find function to find room and assign a name to the adjacent cell, however I am getting a code 91 in the debugger
I am trying to use a find function to find room and assign a name to the adjacent cell, however I am getting a code 91 in the debugger. I have used this find function multiple time and it has flawlessly worked but when I set it to a new variable and changed the sheet and userform reference, it just stopped working.

The lay out is on sheet3 there is a list of all of the room numbers A:A, and I want a a code to find the room number assigned in the userform and add the name of the person to the second column B:B.

```<code>'Update Occupancy List
Sheet3.Select
Dim FndRng As Range
Set FndRng = Sheet3.Columns("A:A").Find(What:=AddOccupant.txtRoom.Value,  LookIn:=xlFormulas, LookAt:=xlPart, _
            SearchOrder:=xlByRows, SearchDirection:=xlNext,     MatchCase:=False, SearchFormat:=False)
FndRng.Offset(0,1).Value = txtName.Value
</code>```

答:
Error 91 is "Object variable or With block variable not set"

The only undeclared variable I can see here is [AddOccupant] which I assume is the UserForm with the [txtRoom] text box. If my assumptions are correct then you need to declare a form first

Dim frmX as UserForm
Set frmX = [Whatever the form name is]

and mod the search line :   ...(What:=frmX.txtRoom.Value,...

BTW, .Value is a universally default so you do not have to be explicit, that is "frmX.txtRoom.Value" and "frmX.txtRoom" are the same.

Body:
I am trying to use a find function to find room and assign a name to the adjacent cell, however I am getting a code 91 in the debugger. I have used this find function multiple time and it has flawlessly worked but when I set it to a new variable and changed the sheet and userform reference, it just stopped working.

The lay out is on sheet3 there is a list of all of the room numbers A:A, and I want a a code to find the room number assigned in the userform and add the name of the person to the second column B:B.

'Update Occupancy List
Sheet3.Select
Dim FndRng As Range
Set FndRng = Sheet3.Columns("A:A").Find(What:=AddOccupant.txtRoom.Value,  LookIn:=xlFormulas, LookAt:=xlPart, _
            SearchOrder:=xlByRows, SearchDirection:=xlNext,     MatchCase:=False, SearchFormat:=False)
FndRng.Offset(0,1).Value = txtName.Value


问:
Rails 3, no local session cookie with :domain => :all
I have a Rails3 app that uses subdomains. To allow logins etc. to work across all subdomains, I do this in config/initializers/session_store.rb

```<code>MyApp::Application.config.session_store :cookie_store, :key => '_myapp_session', :domain => :all
</code>```

When I deploy my app to Heroku, this works perfectly. I can login and stay logged in across subdomains.

However, when developing locally, this does not work.

My browser does set the session cookie properly:

```<code>$ curl http://test.lhs.com/users/sign_in
...
Set-Cookie: _myapp_session=BAh...3ed; domain=.lhs.com; path=/; HttpOnly
...
</code>```

However, my browser (I tried Safari, FireFox and Chrome) does not set this cookie. So, when I log in I get an InvalidAuthenticityToken error.

I've tried removing the :domain => :all part, which does set the session cookie properly, but only for the current subdomain. Setting it explicitly like this :domain => '.lhs.com' also does not set the cookie.

I'm at a loss here. Why does this work in production on heroku, but not locally. I've even tried different servers (Webrick with rails server and passenger-standalone). I've also tried running locally on port 80 instead of 3000, but this also makes no difference.

Any clues why the session cookie is not set locally? Thanks!

答:
When :domain => :all is set in Rails 3.0.3, local session cookies seem not to be set unless you specify a top-level domain in the browser.  This may be as designed, though I see no  documentation either way.

So your session will fail when you visit localhost, but it should be set normally at mylaptop.local.  The ".local" seems to satisfy the requirement for a TLD.

Body:
I have a Rails3 app that uses subdomains. To allow logins etc. to work across all subdomains, I do this in config/initializers/session_store.rb

MyApp::Application.config.session_store :cookie_store, :key => '_myapp_session', :domain => :all

When I deploy my app to Heroku, this works perfectly. I can login and stay logged in across subdomains.

However, when developing locally, this does not work.

My browser does set the session cookie properly:

$ curl http://test.lhs.com/users/sign_in
...
Set-Cookie: _myapp_session=BAh...3ed; domain=.lhs.com; path=/; HttpOnly
...

However, my browser (I tried Safari, FireFox and Chrome) does not set this cookie. So, when I log in I get an InvalidAuthenticityToken error.

I've tried removing the :domain => :all part, which does set the session cookie properly, but only for the current subdomain. Setting it explicitly like this :domain => '.lhs.com' also does not set the cookie.

I'm at a loss here. Why does this work in production on heroku, but not locally. I've even tried different servers (Webrick with rails server and passenger-standalone). I've also tried running locally on port 80 instead of 3000, but this also makes no difference.

Any clues why the session cookie is not set locally? Thanks!


问:
Xcode 8 Objective-C category warning
I'm using Xcode 8 and Swift 3.0.  What does this error message mean?

ld: warning: Some object files have incompatible Objective-C category definitions. Some category metadata may be lost. All files containing Objective-C categories should be built using the same compiler.

答:
Rather than marking each member as @nonobjc individually, you can instead mark the entire extension as @nonobjc:

```<code>@nonobjc extension UIStoryboard {
  static let main = UIStoryboard(name: "Main", bundle: nil)
  static let welcome = UIStoryboard(name: "Main", bundle: nil)
}
</code>```

Title: Xcode 8 Objective-C category warning

Body:
Rather than marking each member as @nonobjc individually, you can instead mark the entire extension as @nonobjc:

@nonobjc extension UIStoryboard {
  static let main = UIStoryboard(name: "Main", bundle: nil)
  static let welcome = UIStoryboard(name: "Main", bundle: nil)
}


问:
scala: import functions defined inside implicit class
I want to attach static utilities to those classes that extend a trait called Application.

```<code>trait Application {
    def name: String
}

case class TestApp(name: String) extends Application

object ImplicitConf {
  implicit class AppConfig[T <: Application](val app: T) {

    lazy val conf = loadConfig

    def loadConfig = {
      ConfigFactory.load(app.name)
    }

    def getString(path: String): String = conf.getString(path)
  }
}
</code>```

Now the following works fine:

```<code>import Application, TestApp
import ImplicitConf._
import AppUtil._

object TestAppConf extends App {

  val app: Application = TestApp("TestAppConf")
  val test = app.getString("hello")
  println(s"The Config value is $test")

}
</code>```

But I am too greedy, how do I covert the call

```<code>val test = app.getString("hello")
</code>```

Into

```<code>val test = getString("hello")
</code>```

答:
The best option I had was to reference the methods in the parent object:

```<code>object ImplicitConf {

  def getString[T <: Application](str: String)(implicit app: T) = AppConfig(app).getString(str)

  implicit class AppConfig[T <: Application](val app: T) {

    @transient lazy val conf = loadConfig

    def loadConfig = {
      ConfigFactory.load(app.name)
    }

    def getString(path: String): String = conf.getString(path)

  }
}
</code>```

Then I was able to invoke as below:

```<code>object TestAppConf extends App {

  implicit val app: Application = TestApp("TestAppConf")

  val test = getString("hello")

  println(s"The Config value is $test")

}
</code>```

Body:
I want to attach static utilities to those classes that extend a trait called Application.

trait Application {
    def name: String
}

case class TestApp(name: String) extends Application

object ImplicitConf {
  implicit class AppConfig[T <: Application](val app: T) {

    lazy val conf = loadConfig

    def loadConfig = {
      ConfigFactory.load(app.name)
    }

    def getString(path: String): String = conf.getString(path)
  }
}

Now the following works fine:

import Application, TestApp
import ImplicitConf._
import AppUtil._

object TestAppConf extends App {

  val app: Application = TestApp("TestAppConf")
  val test = app.getString("hello")
  println(s"The Config value is $test")

}

But I am too greedy, how do I covert the call

val test = app.getString("hello")

Into

val test = getString("hello")

Body:
The best option I had was to reference the methods in the parent object:

object ImplicitConf {

  def getString[T <: Application](str: String)(implicit app: T) = AppConfig(app).getString(str)

  implicit class AppConfig[T <: Application](val app: T) {

    @transient lazy val conf = loadConfig

    def loadConfig = {
      ConfigFactory.load(app.name)
    }

    def getString(path: String): String = conf.getString(path)

  }
}

Then I was able to invoke as below:

object TestAppConf extends App {

  implicit val app: Application = TestApp("TestAppConf")

  val test = getString("hello")

  println(s"The Config value is $test")

}


问:
How to install Jenkins Master as windows service?
i'm trying to install Jenkins Master as Windows Service, but the access is denied.

FATAL - WMI Operation failure: AccessDenied

I've install Jenkins Master with the java -jar command.

```<code>java -jar C:\Jenkins\jenkins.war
</code>```

I'm using Windows 10. Can someone help me ? Thx.

答: I've used the jenkins.msi and It worked !</p>

Body:
i'm trying to install Jenkins Master as Windows Service, but the access is denied.

FATAL - WMI Operation failure: AccessDenied

I've install Jenkins Master with the java -jar command.

java -jar C:\Jenkins\jenkins.war

I'm using Windows 10. Can someone help me ? Thx.


问:
Moving a VB6's Data folder out of Program Files
I maintain a VB6 application that stores its data (access files) in a subfolder of the application folder. So, when the user installs the application to the default location of C:\Program Files\MyApp the data ends up in the Virtual Store. I have now been given the sweet task of converting the 1000 or so App.Path statements to a path to a Data folder that will not have any security issues. Can someone please help me out by pointing the way to some resources that will spoonfeed to me how to handle data in the Users\< Username>\AppData\Local\ folder?

Should I use the local AppData folder, or can I have the user choose a suitable location?

答:
Well if we assume a couple of things:

This is only an issue for Vista or later.

Your data is in subfolders, under App.Path.

... I have a sort of workaround that might be used.

Note that I only use this trick when I have a bunch of old VB6 programs that were written to use data in folders beneath App.Path, sort of a quick and dirty hack to get a lot of programs working quickly.  I almost always add or update the application manifest as well, mostly to prevent virtualization.

The changes I make are:

Add a little code to Sub Main (inserting a Sub Main if the program doesn't already have one).

Add two Class modules (invoked by the new Sub Main code) to the project.

When the new program is deployed, on Vista or later the program needs to be run once as administrator.  In the newest version of my add-in code the program will prompt the user to rerun it elevated if required, and when OKed it does so and self-terminates.

After the first run everything should be hunky-dory, running much as it did under Win2K, XP, etc.

This startup code that requires elevation provides a list of the App.Path subfolders required to the PathLinks class.

Pathlinks creates a program folder under the Public special folder, then creates matching subfolders for the data under that.  Next it moves any files and subfolders in these App.Path subfolders into the new locations.  Finally it creates symlinks to the new folders back under App.Path.

If running under Windows prior to Vista, PathLinks merely creates any of the list of App.Path subfolders (under App.Path) that don't already exist (i.e. by installation).

From here on the program will find the files in the new location, without needing any changes to its use of App.Path at all.

One of the two add-in Classes is cosmetic and you can remove it.  It just lets the startup code invoke TaskDialog instead of using a MsgBox call.

Be sure to scroll down for the newest version posted at PathLinks - Tame App.Path Under Vista+

Note that the sample project skips running the application when it does that "first time elevated" trick.  It just does an Exit Sub in Sub Main after relocating data and symlinking to it.


问:
Faster way to query Access table
I have two access tables, A and B:

```<code>Table A
Identifier BenefitBase    PlanNav
1        131368.46      131368.46
2        201768.8       201768.79
3        54057.46       54057.46
4        7397.51        7397.51
5        9931.4         9931.4
6        178200         178200
Table B
p      ValidityDate LockInAmount
1      2016-4       3.82
2      2016-4       19.97
3      2016-4       26.85
4      2016-6       34.95
</code>```

I just want to create a query which extracts records from B where the "p" ID is not found in table A.
My current code is:

```<code>SELECT B.p, B.ValidityDate, B.LockInAmount
FROM B
WHERE (((B.p) Not In (select Identifier from A)));
</code>```

Now to me, this code should work fine. However, because the tables are so large (B consists  of 486,000 rows (the "p"'s repeats in this table for different dates) whereas A consists of circa 19,000), whenever I run the query, access fills the query progress bar but freezes when near full.

Is there another way to do this?

Thanks

答:
Since you don't know if the fields are indexed:
Create indexes for both fields (see this page by Microsoft for information on indexes):

Execute these queries to create the indexes (or use the GUI)

```<code>CREATE INDEX TblAIdentifier ON A(Identifier)

CREATE INDEX TblBP ON B(p)
</code>```

As long as you at least create the first index, Access won't even need to open up table A. It can just look in the index which fields are taken.

You can use this answer together with the one provided by @Gustav

Title: Faster way to query Access table

Body:
I have two access tables, A and B:

Table A
Identifier BenefitBase    PlanNav
1        131368.46      131368.46
2        201768.8       201768.79
3        54057.46       54057.46
4        7397.51        7397.51
5        9931.4         9931.4
6        178200         178200
Table B
p      ValidityDate LockInAmount
1      2016-4       3.82
2      2016-4       19.97
3      2016-4       26.85
4      2016-6       34.95

I just want to create a query which extracts records from B where the "p" ID is not found in table A.
My current code is:

SELECT B.p, B.ValidityDate, B.LockInAmount
FROM B
WHERE (((B.p) Not In (select Identifier from A)));

Now to me, this code should work fine. However, because the tables are so large (B consists  of 486,000 rows (the "p"'s repeats in this table for different dates) whereas A consists of circa 19,000), whenever I run the query, access fills the query progress bar but freezes when near full.

Is there another way to do this?

Thanks

Body:
Since you don't know if the fields are indexed:
Create indexes for both fields (see this page by Microsoft for information on indexes):

Execute these queries to create the indexes (or use the GUI)

CREATE INDEX TblAIdentifier ON A(Identifier)

CREATE INDEX TblBP ON B(p)

As long as you at least create the first index, Access won't even need to open up table A. It can just look in the index which fields are taken.

You can use this answer together with the one provided by @Gustav


答:
You need a calendar table and Outer Apply

```<code>;WITH cte
     AS (SELECT Min([date]) AS st,
                Max([date]) ed,
                code
         FROM   Yourtable
         GROUP  BY code
         UNION ALL
         SELECT Dateadd(dd, 1, st) AS st,
                ed,
                code
         FROM   cte
         WHERE  Dateadd(dd, 1, st) <= ed)
SELECT c.code,
       [date]=c.st,
       qty
FROM   cte c
       OUTER apply (SELECT TOP 1 qty
                    FROM   Yourtable a
                    WHERE  a.code = c.code
                           AND c.st >= a.[date]
                    ORDER  BY [date] DESC) oa
ORDER  BY c.code,st
</code>```

Note : For the sake of completeness I have used Recursive CTE to generate the dates you can always create a physical calendar table in your database and use it.

Live Demo

Title: Split the date of same column in multiple rows till the next date value is specified - SQL Server

Body:
I have this table

+------+------------+-----+
| Code |    date    | qty |
+------+------------+-----+
|    1 | 06-07-2017 |  44 |
|    1 | 08-07-2017 |  45 |
|    2 | 07-07-2017 |  32 |
|    2 | 09-07-2017 |  33 |
+------+------------+-----+

and I want to display it this way

+------+------------+-----+
| Code |    date    | qty |
+------+------------+-----+
|    1 | 06-07-2017 |  44 |
|    1 | 07-07-2017 |  44 |
|    1 | 08-07-2017 |  45 |
|    2 | 07-07-2017 |  32 |
|    2 | 08-07-2017 |  32 |
|    2 | 09-07-2017 |  33 |
+------+------------+-----+

I want to split the date of same 'Code' and keep the same value for 'qty' till the next date of same 'Code'.

Body:
You need a calendar table and Outer Apply

;WITH cte
     AS (SELECT Min([date]) AS st,
                Max([date]) ed,
                code
         FROM   Yourtable
         GROUP  BY code
         UNION ALL
         SELECT Dateadd(dd, 1, st) AS st,
                ed,
                code
         FROM   cte
         WHERE  Dateadd(dd, 1, st) <= ed)
SELECT c.code,
       [date]=c.st,
       qty
FROM   cte c
       OUTER apply (SELECT TOP 1 qty
                    FROM   Yourtable a
                    WHERE  a.code = c.code
                           AND c.st >= a.[date]
                    ORDER  BY [date] DESC) oa
ORDER  BY c.code,st

Note : For the sake of completeness I have used Recursive CTE to generate the dates you can always create a physical calendar table in your database and use it.

Live Demo


问:
How to send http request in asp.net without waiting for a response and without tying up resources
In an ASP.Net application, I need to send some data (urlEncodedUserInput) via http POST to an external server in response to user input, without holding up the page response. It doesn't matter what the response from the other server is, and I don't care if the request fails sometimes. This seems to be operating fine (see below) but I'm concerned that it's tying up resources in the background waiting for a response that will never be used.

Here's the code:

```<code>httpRequest = WebRequest.Create(externalServerUrl);

httpRequest.Method = "POST";
httpRequest.ContentType = "application/x-www-form-urlencoded;charset=utf-8";

bytedata = Encoding.UTF8.GetBytes(urlEncodedUserInput);
httpRequest.ContentLength = bytedata.Length;

requestStream = httpRequest.GetRequestStream();
requestStream.Write(bytedata, 0, bytedata.Length);
requestStream.Close();
</code>```

Pretty standard stuff, but usually at this point you would call httpRequest.getResponse() or httpRequest.beginGetResponse() if you wanted to receive the response asynchronously, but this doesn't seem to be necessary in my scenario.

Am I doing the right thing? Should I call httpRequest.Abort() to clean up or could this prevent the request from being sent on a slow connection?

答:
I think Threadpool.QueueUserWorkItem is what you're looking for. With the addition of lambdas and anonymous types, this can be really simple:</p>

```<code>var request = new { url = externalServerUrl, input = urlEncodedUserInput };
ThreadPool.QueueUserWorkItem(
    (data) =>
    {
         httpRequest = WebRequest.Create(data.url);

         httpRequest.Method = "POST";
         httpRequest.ContentType = "application/x-www-form-urlencoded;charset=utf-8";

         bytedata = Encoding.UTF8.GetBytes(data.input);
         httpRequest.ContentLength = bytedata.Length;

         requestStream = httpRequest.GetRequestStream();
         requestStream.Write(bytedata, 0, bytedata.Length);
         requestStream.Close();
         //and so on
     }, request);
</code>```

OwnerDisplayName: Stuart Matheson

Body:
In an ASP.Net application, I need to send some data (urlEncodedUserInput) via http POST to an external server in response to user input, without holding up the page response. It doesn't matter what the response from the other server is, and I don't care if the request fails sometimes. This seems to be operating fine (see below) but I'm concerned that it's tying up resources in the background waiting for a response that will never be used.

Here's the code:

httpRequest = WebRequest.Create(externalServerUrl);

httpRequest.Method = "POST";
httpRequest.ContentType = "application/x-www-form-urlencoded;charset=utf-8";

bytedata = Encoding.UTF8.GetBytes(urlEncodedUserInput);
httpRequest.ContentLength = bytedata.Length;

requestStream = httpRequest.GetRequestStream();
requestStream.Write(bytedata, 0, bytedata.Length);
requestStream.Close();

Pretty standard stuff, but usually at this point you would call httpRequest.getResponse() or httpRequest.beginGetResponse() if you wanted to receive the response asynchronously, but this doesn't seem to be necessary in my scenario.

Am I doing the right thing? Should I call httpRequest.Abort() to clean up or could this prevent the request from being sent on a slow connection?

Body:
I think Threadpool.QueueUserWorkItem is what you're looking for. With the addition of lambdas and anonymous types, this can be really simple:

var request = new { url = externalServerUrl, input = urlEncodedUserInput };
ThreadPool.QueueUserWorkItem(
    (data) =>
    {
         httpRequest = WebRequest.Create(data.url);

         httpRequest.Method = "POST";
         httpRequest.ContentType = "application/x-www-form-urlencoded;charset=utf-8";

         bytedata = Encoding.UTF8.GetBytes(data.input);
         httpRequest.ContentLength = bytedata.Length;

         requestStream = httpRequest.GetRequestStream();
         requestStream.Write(bytedata, 0, bytedata.Length);
         requestStream.Close();
         //and so on
     }, request);

OwnerDisplayName: ALassek

LastEditorDisplayName: Adam Lassek


问:
Cannot set UDTs in a jooq insert, consistently getting a StackOverflowError
The SQL is pretty simple:

```<code>CREATE TYPE audit_fields AS (
    creation_time_ms BIGINT
);

CREATE TABLE users(
    ...
    audit AUDIT_FIELDS NOT NULL
);
</code>```

These are two ways I have tried to do this:

```<code>UsersRecord getRecord() {
    return new UsersRecord()
        .setSomeField(...)
        .setOtherField(...)
        .setAudit(new AuditFieldsRecord(System.currentTimeMillis()));
}

create.insertInto(Tables.USERS)
    .set(getRecord())
    .execute();
</code>```

And, this:

```<code>create.insertInto(Tables.USERS)
    .set(getRecord())
    .set(Tables.USERS.AUDIT, new AuditFieldsRecord(System.currentTimemillis()))
    .execute();
</code>```

I am simply getting a StackOverflowError, with the following block repeating throughout (obviously an infinite-recursion):

```<code>at org.jooq.impl.UDTConstant.<init>(UDTConstant.java:62)
at org.jooq.impl.DSL.val(DSL.java:12781)
at org.jooq.impl.DSL.val(DSL.java:12732)
at org.jooq.impl.DSL.inline(DSL.java:12590)
at org.jooq.impl.UDTRecordImpl.toString(UDTRecordImpl.java:141)
at java.lang.String.valueOf(String.java:2994)
at org.jooq.impl.AbstractParam.name(AbstractParam.java:104)
at org.jooq.impl.AbstractParam.<init>(AbstractParam.java:78)
at org.jooq.impl.AbstractParam.<init>(AbstractParam.java:74)
at org.jooq.impl.UDTConstant.<init>(UDTConstant.java:62)
at org.jooq.impl.DSL.val(DSL.java:12781)
at org.jooq.impl.DSL.val(DSL.java:12732)
at org.jooq.impl.DSL.inline(DSL.java:12590)
at org.jooq.impl.UDTRecordImpl.toString(UDTRecordImpl.java:141)
at java.lang.String.valueOf(String.java:2994)
at org.jooq.impl.AbstractParam.name(AbstractParam.java:104)
at org.jooq.impl.AbstractParam.<init>(AbstractParam.java:78)
at org.jooq.impl.AbstractParam.<init>(AbstractParam.java:74)
at org.jooq.impl.UDTConstant.<init>(UDTConstant.java:62)
at org.jooq.impl.DSL.val(DSL.java:12781)
at org.jooq.impl.DSL.val(DSL.java:12732)
at org.jooq.impl.DSL.inline(DSL.java:12590)
at org.jooq.impl.UDTRecordImpl.toString(UDTRecordImpl.java:141)
at java.lang.String.valueOf(String.java:2994)
at org.jooq.impl.AbstractParam.name(AbstractParam.java:104)
at org.jooq.impl.AbstractParam.<init>(AbstractParam.java:78)
at org.jooq.impl.AbstractParam.<init>(AbstractParam.java:74)
at org.jooq.impl.UDTConstant.<init>(UDTConstant.java:62)
</code>```

Any idea what I am doing wrong?

答:
This is an issue that exists in older versions of Jooq 3.7.0. For projects who are using that version and cannot migrate easily to newer versions, this question might be a starting point, so I am not voting to close it (other's are requested to if they see fit).

Upgrading to a later version of jooq fixes this issue.

Body:
The SQL is pretty simple:

CREATE TYPE audit_fields AS (
    creation_time_ms BIGINT
);

CREATE TABLE users(
    ...
    audit AUDIT_FIELDS NOT NULL
);

These are two ways I have tried to do this:

UsersRecord getRecord() {
    return new UsersRecord()
        .setSomeField(...)
        .setOtherField(...)
        .setAudit(new AuditFieldsRecord(System.currentTimeMillis()));
}

create.insertInto(Tables.USERS)
    .set(getRecord())
    .execute();

And, this:

create.insertInto(Tables.USERS)
    .set(getRecord())
    .set(Tables.USERS.AUDIT, new AuditFieldsRecord(System.currentTimemillis()))
    .execute();

I am simply getting a StackOverflowError, with the following block repeating throughout (obviously an infinite-recursion):

at org.jooq.impl.UDTConstant.<init>(UDTConstant.java:62)
at org.jooq.impl.DSL.val(DSL.java:12781)
at org.jooq.impl.DSL.val(DSL.java:12732)
at org.jooq.impl.DSL.inline(DSL.java:12590)
at org.jooq.impl.UDTRecordImpl.toString(UDTRecordImpl.java:141)
at java.lang.String.valueOf(String.java:2994)
at org.jooq.impl.AbstractParam.name(AbstractParam.java:104)
at org.jooq.impl.AbstractParam.<init>(AbstractParam.java:78)
at org.jooq.impl.AbstractParam.<init>(AbstractParam.java:74)
at org.jooq.impl.UDTConstant.<init>(UDTConstant.java:62)
at org.jooq.impl.DSL.val(DSL.java:12781)
at org.jooq.impl.DSL.val(DSL.java:12732)
at org.jooq.impl.DSL.inline(DSL.java:12590)
at org.jooq.impl.UDTRecordImpl.toString(UDTRecordImpl.java:141)
at java.lang.String.valueOf(String.java:2994)
at org.jooq.impl.AbstractParam.name(AbstractParam.java:104)
at org.jooq.impl.AbstractParam.<init>(AbstractParam.java:78)
at org.jooq.impl.AbstractParam.<init>(AbstractParam.java:74)
at org.jooq.impl.UDTConstant.<init>(UDTConstant.java:62)
at org.jooq.impl.DSL.val(DSL.java:12781)
at org.jooq.impl.DSL.val(DSL.java:12732)
at org.jooq.impl.DSL.inline(DSL.java:12590)
at org.jooq.impl.UDTRecordImpl.toString(UDTRecordImpl.java:141)
at java.lang.String.valueOf(String.java:2994)
at org.jooq.impl.AbstractParam.name(AbstractParam.java:104)
at org.jooq.impl.AbstractParam.<init>(AbstractParam.java:78)
at org.jooq.impl.AbstractParam.<init>(AbstractParam.java:74)
at org.jooq.impl.UDTConstant.<init>(UDTConstant.java:62)

Any idea what I am doing wrong?


答:
SELECT B.p, B.ValidityDate, B.LockInAmount
FROM
B
Left join
A
B.p=A.Identifier
WHERE A.Identifier Is Null);</p>

Title: Faster way to query Access table


问:
How to Redirect to another php file using javascript
Okay, so here's my code

```<code><?php
$cn = new mysqli ("localhost", "root", "root", "dbsam");
$username = isset ($_POST['username']) ? $_POST['username']:"";
$password = isset ($_POST['password']) ? $_POST['password']:"";
$sql = "SELECT * FROM tbluser WHERE username=? AND password=?";
$upass = hash("SHA256", $password);
$qry = $cn->prepare($sql);
$qry->bind_param("ss", $username, $upass);
$qry->execute();
$qry->fetch();
if ($qry->num_rows()==1) {
    echo "Logged in!";
}
else {
    echo "<script>alert('Account did not match the database records!')</script>>";
    header ("location: login.php");
}
?>
</code>```

If the username and password did not match, an alert box will appear. So the problem is that it doesn't appear anymore it only executes the header that I put under it but if I remove the header, the alert dialog box will appear. I want the alert box to appear then the user will be redirected to the log-in page after that. How can I do that? Great Thanks!

答:
It is impossible in such way, PHP will redirect and never let the browwer executing the JS.

You can add a variable in the url then make your test in login.php then show the alert

```<code>    .....
    else {
        header ("location: login.php?mode=login_failed");
    }

    //login.php
    $mode = filter_input(INPUT_GET, 'mode');
    if ($mode === 'login_failed') {
         echo '<script>.......';
    }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Okay, so here's my code

<?php
$cn = new mysqli ("localhost", "root", "root", "dbsam");
$username = isset ($_POST['username']) ? $_POST['username']:"";
$password = isset ($_POST['password']) ? $_POST['password']:"";
$sql = "SELECT * FROM tbluser WHERE username=? AND password=?";
$upass = hash("SHA256", $password);
$qry = $cn->prepare($sql);
$qry->bind_param("ss", $username, $upass);
$qry->execute();
$qry->fetch();
if ($qry->num_rows()==1) {
    echo "Logged in!";
}
else {
    echo ">";
    header ("location: login.php");
}
?>

If the username and password did not match, an alert box will appear. So the problem is that it doesn't appear anymore it only executes the header that I put under it but if I remove the header, the alert dialog box will appear. I want the alert box to appear then the user will be redirected to the log-in page after that. How can I do that? Great Thanks!

Body:
It is impossible in such way, PHP will redirect and never let the browwer executing the JS.

You can add a variable in the url then make your test in login.php then show the alert

    .....
    else {
        header ("location: login.php?mode=login_failed");
    }

    //login.php
    $mode = filter_input(INPUT_GET, 'mode');
    if ($mode === 'login_failed') {
         echo '<script>.......';
    }


问:
Weird behaviour with arrays in ColdFusion
I am facing issue with a piece of code, with slight modification I am getting different results which should not be the case.

Version 1 is giving the correct results, I am facing issue with Version 2 which is the actual code.

Version 1:

```<code><cfset keywords = listToArray("1,2,3,4,5,6,7,8,9,10")>

<!--- Common Code Below --->
<cfoutput>#getMetadata(keywords).getName()#</cfoutput>

<cfset toBeAdded = keywords>
<cfset toBeInactivated = listToArray("1,3,4,6,8")>
<cfset toBeActivated = toBeInactivated>

<cfset toBeAdded.removeAll(toBeInactivated)>
<cfset toBeInactivated.removeAll(keywords)>
<cfset toBeActivated.retainAll(keywords)>
</code>```

Version 2:

```<code><cfset keywords = []>
<cfloop from="1" to="10" index="counter">
    <cfset arrayAppend( keywords, counter )>
</cfloop>

<!--- If I add following line here then it is working as expected and similar to version 1:  --->
<!--- <cfset keywords = listToArray(arrayToList(keywords))> --->

<!--- Common Code Below --->
<cfoutput>#getMetadata(keywords).getName()#</cfoutput>

<cfset toBeAdded = keywords>
<cfset toBeInactivated = listToArray("1,3,4,6,8")>
<cfset toBeActivated = toBeInactivated>

<cfset toBeAdded.removeAll(toBeInactivated)>
<cfset toBeInactivated.removeAll(keywords)>
<cfset toBeActivated.retainAll(keywords)>
</code>```

Outputs:

Here are the gists: Version 1 and Version 2.

Any suggestions are greatly appreciated!

答:
A ColdFusion array isn't a Java Collection object. So I question the use of removeAll() and retainAll() with such arrays. Bearing that in mind, my answer is:</p>

```<code><cfset keywords = createobject("java","java.util.Vector").init()>
<cfset toBeAdded = createobject("java","java.util.Vector").init()>
<cfloop from="1" to="10" index="counter">
    <cfset keywords.add(javaCast("int", counter))>
    <cfset toBeAdded.add(javaCast("int", counter))>
</cfloop>

<!--- Common Code Below --->
<cfoutput>#getMetadata(keywords).getName()#</cfoutput>

<cfset listToBeInactivated = "1,3,4,6,8">
<cfset toBeInactivated = createobject("java","java.util.Vector").init()>
<cfset toBeActivated = createobject("java","java.util.Vector").init()>
<cfloop list="#listToBeInactivated#" index="index">
    <cfset toBeInactivated.add(javaCast("int", index))>
    <cfset toBeActivated.add(javaCast("int", index))>
</cfloop>

<cfset toBeAdded.removeAll(toBeInactivated)>
<cfset toBeInactivated.removeAll(keywords)>
<cfset toBeActivated.retainAll(keywords)>

<cfdump var="#toBeAdded#" label="toBeAdded">
<cfdump var="#toBeInactivated#" label="toBeInactivated">
<cfdump var="#toBeActivated#" label="toBeActivated">
</code>```

Body:
I am facing issue with a piece of code, with slight modification I am getting different results which should not be the case.

Version 1 is giving the correct results, I am facing issue with Version 2 which is the actual code.

Version 1:

<cfset keywords = listToArray("1,2,3,4,5,6,7,8,9,10")>

<cfoutput>#getMetadata(keywords).getName()#</cfoutput>

<cfset toBeAdded = keywords>
<cfset toBeInactivated = listToArray("1,3,4,6,8")>
<cfset toBeActivated = toBeInactivated>

<cfset toBeAdded.removeAll(toBeInactivated)>
<cfset toBeInactivated.removeAll(keywords)>
<cfset toBeActivated.retainAll(keywords)>

Version 2:

<cfset keywords = []>
<cfloop from="1" to="10" index="counter">
    <cfset arrayAppend( keywords, counter )>
</cfloop>

<cfoutput>#getMetadata(keywords).getName()#</cfoutput>

<cfset toBeAdded = keywords>
<cfset toBeInactivated = listToArray("1,3,4,6,8")>
<cfset toBeActivated = toBeInactivated>

<cfset toBeAdded.removeAll(toBeInactivated)>
<cfset toBeInactivated.removeAll(keywords)>
<cfset toBeActivated.retainAll(keywords)>

Outputs:

Here are the gists: Version 1 and Version 2.

Any suggestions are greatly appreciated!

Body:
A ColdFusion array isn't a Java Collection object. So I question the use of removeAll() and retainAll() with such arrays. Bearing that in mind, my answer is:

<cfset keywords = createobject("java","java.util.Vector").init()>
<cfset toBeAdded = createobject("java","java.util.Vector").init()>
<cfloop from="1" to="10" index="counter">
    <cfset keywords.add(javaCast("int", counter))>
    <cfset toBeAdded.add(javaCast("int", counter))>
</cfloop>

<!--- Common Code Below --->
<cfoutput>#getMetadata(keywords).getName()#</cfoutput>

<cfset listToBeInactivated = "1,3,4,6,8">
<cfset toBeInactivated = createobject("java","java.util.Vector").init()>
<cfset toBeActivated = createobject("java","java.util.Vector").init()>
<cfloop list="#listToBeInactivated#" index="index">
    <cfset toBeInactivated.add(javaCast("int", index))>
    <cfset toBeActivated.add(javaCast("int", index))>
</cfloop>

<cfset toBeAdded.removeAll(toBeInactivated)>
<cfset toBeInactivated.removeAll(keywords)>
<cfset toBeActivated.retainAll(keywords)>

<cfdump var="#toBeAdded#" label="toBeAdded">
<cfdump var="#toBeInactivated#" label="toBeInactivated">
<cfdump var="#toBeActivated#" label="toBeActivated">


问:
django returned form option selected
I have a drop down menu from which people can select an area and submit.
On being directed to the results page I would like the chosen area to be displayed in the form. Convention is that you use selected as an attibute in the option tag.

Using django,

area = area queryset to populate the drop down list.
q = chosen for area.
Both can be renderd fine in the template seperately.
However when I try,

```<code><form action="/results/" method="GET">
    <select name="q" id="id_area">
        {% if a %}
            {% for area in a %}
                <option value="{{ area }}" {% if area == q %} selected {% endif %}>{{ area }}</option>
            {% endfor %}
        {% endif %}
    </select>
    <p><input class="send_button" type="submit" value="Search" /></p>
</form>
</code>```

It doesn't give the "selected" attibute.

Also tried,

```<code>{% for area in a %}
    <option value="{{ area }}" {% ifequal area q %} selected {% endif %}>{{ area }}</option>
{% endfor %}
</code>```

Any help would be much appreciated.
Thanks

答: I'm quite sure the django template equality operator doesn't support var == var checking. I'd suggest adding a 'selected' property to area so you can say something like {% if area.selected %}.

Title: django returned form option selected

Body:
I have a drop down menu from which people can select an area and submit.
On being directed to the results page I would like the chosen area to be displayed in the form. Convention is that you use selected as an attibute in the option tag.

Using django,

area = area queryset to populate the drop down list.
q = chosen for area.
Both can be renderd fine in the template seperately.
However when I try,

<form action="/results/" method="GET">
    <select name="q" id="id_area">
        {% if a %}
            {% for area in a %}
                <option value="{{ area }}" {% if area == q %} selected {% endif %}>{{ area }}</option>
            {% endfor %}
        {% endif %}
    </select>

<input class="send_button" type="submit" value="Search" />

</form>

It doesn't give the "selected" attibute.

Also tried,

{% for area in a %}
    <option value="{{ area }}" {% ifequal area q %} selected {% endif %}>{{ area }}</option>
{% endfor %}

Any help would be much appreciated.
Thanks


问:
Loading .NetCore DLL's in powershell
I've created some .DLL's compiled using .NetCore 1.1. I now need to load them into Powershell and call their methods. Is this supported or do my DLL's need to be compiled using the full version of .Net? </p>

答: To add a DLL to a powershell script use the following code: Add-Type -Path "C:\locationOfDLL\mydll.dll". See if that works for accessing the dll as needed.

Title: Loading .NetCore DLL's in powershell


问:
Register class-based task in
I am using Celery version 4.0.2.

Compared to previous versions of Celery, it seems that class-based tasks are not registered automatically (i.e. if you configured auto-discovery).

However, I do not even achieve registering a class-based task manually.

According to the Celery change log:

http://docs.celeryproject.org/en/latest/changelog.html#version-4-0-1

since version 4.0.1 it should be possible to register the task manually:

```<code>from celery import Celery, Task
app = Celery()

class CustomTask(Task):

    def run(self):
        return 'hello'

app.register_task(CustomTask())
</code>```

But this does not seem to work. Does anyone know how to achieve this?

I tried a few suggestions which are being discussed (apart from integrating a custom task loader mentioned in https://github.com/celery/celery/issues/3744):

Register Celery Class-based Task

https://github.com/celery/celery/issues/3615

https://github.com/celery/celery/issues/3744

答:
Almost there! You need to call delay() on the task that you registered.

This would work:

```<code>from celery import Celery, Task

app = Celery()

class CustomTask(Task):
    def run(self):
        return 'hello'

task = CustomTask()
app.register_task(task)

task.delay()
</code>```

Title: Register class-based task in

Body:
I am using Celery version 4.0.2.

Compared to previous versions of Celery, it seems that class-based tasks are not registered automatically (i.e. if you configured auto-discovery).

However, I do not even achieve registering a class-based task manually.

According to the Celery change log:

http://docs.celeryproject.org/en/latest/changelog.html#version-4-0-1

since version 4.0.1 it should be possible to register the task manually:

from celery import Celery, Task
app = Celery()

class CustomTask(Task):

    def run(self):
        return 'hello'

app.register_task(CustomTask())

But this does not seem to work. Does anyone know how to achieve this?

I tried a few suggestions which are being discussed (apart from integrating a custom task loader mentioned in https://github.com/celery/celery/issues/3744):

Register Celery Class-based Task

https://github.com/celery/celery/issues/3615

https://github.com/celery/celery/issues/3744

Body:
Almost there! You need to call delay() on the task that you registered.

This would work:

from celery import Celery, Task

app = Celery()

class CustomTask(Task):
    def run(self):
        return 'hello'

task = CustomTask()
app.register_task(task)

task.delay()


问:
FFMPEG Android Storage Access Framework
I'm using FFMPEG on Android to change bitrate etc of videos that weren't recorded within my app.

The problem I'm facing is that I can't get the absolute path for a video the user selects from the SD Card.

I'm using the Android Storage Access Framework and currently get the following Uri:
content://com.android.externalstorage.documents/document/9C33-6BBD%3AVideos%2Freaps-driving.mp4

The FFMPEG command I use:

```<code>String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
                    String[] cmd = {"-y", "-i", mVideoUri.toString(), "-c:v", "libx264", "-preset", "ultrafast", "-strict", "-2", "-s", optimalVideoSize, "-aspect", "16:9", "-b", bitrate, String.format("/storage/emulated/0/Movies/InstaVid/VID_INSTAVID%s.mp4", timeStamp)};
                    executeFFmpegBinary(cmd, timeStamp);
</code>```

It doesn't matter if I use mVideoUri.toString() or mVideoUri.getPath().

Is there any way I can get the absolute path?

答:
The problem I'm facing is that I can't get the absolute path for a video the user selects from the SD Card

First, the Storage Access Framework is not limited to removable storage. If the user chooses something from, say, Google Drive, for all you know, the video is not even on the device at the moment. In another example, Google just released a Samba storage provider, and if the user uses that, the content exists on a file server somewhere on the LAN, not on the device.

Second, you do not have access to removable storage via the filesystem APIs, except for a couple of select areas (e.g., getExternalFilesDirs()). The user may choose a video outside of there.

Is there any way I can get the absolute path?

No. Your choices are:

Stop using the Storage Access Framework, and instead use some file picker library, which will limit you to files that you will be able to pass along to ffmpeg.

Use a ContentResolver and openInputStream() to get an InputStream on the content identified by the Uri, then use that to make a local copy of the content into a file that you control. Then, pass the path to that local copy to ffmpeg. Delete the local copy when you are done.

Title: FFMPEG Android Storage Access Framework

Body:
I'm using FFMPEG on Android to change bitrate etc of videos that weren't recorded within my app.

The problem I'm facing is that I can't get the absolute path for a video the user selects from the SD Card.

I'm using the Android Storage Access Framework and currently get the following Uri:
content://com.android.externalstorage.documents/document/9C33-6BBD%3AVideos%2Freaps-driving.mp4

The FFMPEG command I use:

String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
                    String[] cmd = {"-y", "-i", mVideoUri.toString(), "-c:v", "libx264", "-preset", "ultrafast", "-strict", "-2", "-s", optimalVideoSize, "-aspect", "16:9", "-b", bitrate, String.format("/storage/emulated/0/Movies/InstaVid/VID_INSTAVID%s.mp4", timeStamp)};
                    executeFFmpegBinary(cmd, timeStamp);

It doesn't matter if I use mVideoUri.toString() or mVideoUri.getPath().

Is there any way I can get the absolute path?


问:
Sphinx docs with SVG images won't render on IE11
I am currently building Sphinx documentation and have UML diagram which is built by graphviz and is generated as SVG image. This SVG file is placed in the html template that is auto-generated by Sphinx.

The SVG is displayed on Chrome and Firefox with no problem, however IE11 does not show it. Is there anything I have to adjust in the html to get the image displayed?

By the way, same html with PNG images instead works everywhere (Chrome, Firefox and IE11).

This is the piece of html which should render the svg file.

```<code><div class="section" id="uml-class-diagram">
  <h1>UML Class Diagram<a class="headerlink" href="#uml-class-diagram" title="Permalink to this headline">¶</a></h1>
  <object data="_images/graphviz- 9fe511f008ffbdc169ab624ae589b7c8a000c75f.svg" type="image/svg+xml"><p class="warning">digraph "classes_kats4" {SOME GRAPH TO BE DISPLAYED}</p></object>
</div>
</code>```

This is the header:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>UML Class Diagram — xx documentation</title>

  <link rel="stylesheet" href="_static/sphinxdoc.css" type="text/css" />
  <link rel="stylesheet" href="_static/pygments.css" type="text/css" />

  <script type="text/javascript">
    var DOCUMENTATION_OPTIONS = {
      URL_ROOT:    './',
      VERSION:     'xx',
      COLLAPSE_INDEX: false,
      FILE_SUFFIX: '.html',
      HAS_SOURCE:  true,
      SOURCELINK_SUFFIX: '.txt'
    };
  </script>
  <script type="text/javascript" src="_static/jquery.js"></script>
  <script type="text/javascript" src="_static/underscore.js"></script>
  <script type="text/javascript" src="_static/doctools.js"></script>
</head>
</code>```

答:
I figured it out, the problem was not with the SVG itself, because I was able to open the image using IE11.

The solution was here SVG as source in  tag not displaying in Internet Explorer 11.

I had to disable Compatibility View by adding tag:

```<code><meta http-equiv="X-UA-Compatible" content="IE=edge">
</code>```

Body:
I am currently building Sphinx documentation and have UML diagram which is built by graphviz and is generated as SVG image. This SVG file is placed in the html template that is auto-generated by Sphinx.

The SVG is displayed on Chrome and Firefox with no problem, however IE11 does not show it. Is there anything I have to adjust in the html to get the image displayed?

By the way, same html with PNG images instead works everywhere (Chrome, Firefox and IE11).

This is the piece of html which should render the svg file.

UML Class Diagram¶

  <object data="_images/graphviz- 9fe511f008ffbdc169ab624ae589b7c8a000c75f.svg" type="image/svg+xml">
digraph "classes_kats4" {SOME GRAPH TO BE DISPLAYED}
</object>

This is the header:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>UML Class Diagram — xx documentation</title>

  <link rel="stylesheet" href="_static/sphinxdoc.css" type="text/css" />
  <link rel="stylesheet" href="_static/pygments.css" type="text/css" />

Body:
I figured it out, the problem was not with the SVG itself, because I was able to open the image using IE11.

The solution was here SVG as source in <img> tag not displaying in Internet Explorer 11.

I had to disable Compatibility View by adding tag:

<meta http-equiv="X-UA-Compatible" content="IE=edge">


问:
jQuery if button is not pressed
I want to check wether a button is pressed in jQuery. If the button is pressed the page has to scroll down. If the button it not pressed the page shows an animation and once this is finished it has to scroll down.

Now I have this:

```<code>$('#btmmdl').click(function(){
    $(this).data('clicked', true);
});

if($('#btmmdl').data('clicked')){
    // Scroll down
} else {
    // Show animation and scroll down after 9 seconds
}
</code>```

Am I doing something wrong?

答:
If you are using CSS3 animations, you can use a jQuery selector to listen for the animationend to scroll down after it happens.

The gist of it:

```<code>$("#someSelector").bind("animationend webkitAnimationEnd oAnimationEnd MSAnimationEnd", function(){ ... });
</code>```

For more information check this awesome stackoverflow answer over here.

In that case you could also end the animation on click of the button, which will also trigger the scrolling down afterwards.

For more information on how to end an animation check the jQuery finish() method

Title: jQuery if button is not pressed

Body:
I want to check wether a button is pressed in jQuery. If the button is pressed the page has to scroll down. If the button it not pressed the page shows an animation and once this is finished it has to scroll down.

Now I have this:

$('#btmmdl').click(function(){
    $(this).data('clicked', true);
});

if($('#btmmdl').data('clicked')){
    // Scroll down
} else {
    // Show animation and scroll down after 9 seconds
}

Am I doing something wrong?

Body:
If you are using CSS3 animations, you can use a jQuery selector to listen for the animationend to scroll down after it happens.

The gist of it:

$("#someSelector").bind("animationend webkitAnimationEnd oAnimationEnd MSAnimationEnd", function(){ ... });

For more information check this awesome stackoverflow answer over here.

In that case you could also end the animation on click of the button, which will also trigger the scrolling down afterwards.

For more information on how to end an animation check the jQuery finish() method


问:
Loop through Zapier webhook result
Just trying to figure out if it is possible to loop through Zapier webhook result set and do something with it.

I have a zap that runs once a day and makes a GET request to a specific URL. There's a JSON result that comes back and now I would like to loop through this resultset and fetch emails from each record for using this email list when sending emails with Mailgun.

Any hints?

答:
I think the simpler approach is to use a "Code by Zapier" action and make the HTTP request directly in the code where you can process the response.

Some more info here.

Title: Loop through Zapier webhook result