问:
Why I am getting undefined on using document.write()?
Why I am getting undefined in browser while using document.write() ?

```<code><script type="text/javascript">
    function Person (name) {
        this.name = name;
        this.greeting = function() {
            document.write("Hello " + name +  " Go rock the industry!!");
        };
    }

    var person1 = new Person("Sara");
    var person2 = new Person("Bob");

    document.write(person1.name + "<br>");
    document.write(person1.greeting() + "<br>");
    document.write(person2.name + "<br>");
    document.write(person2.greeting() + "<br>");

</script>
</code>```

In browser I get this output:

```<code>Sara
Hello Sara Go rock the industry!!undefined
Bob
Hello Bob Go rock the industry!!undefined
</code>```

答:
You are trying to use document.write on a function that does not return a value, rather performs document.write itself. Person.greeting() should return a value so you can use it when calling document.write(person2.greeting()).

It should be something like this:

```<code>function Person (name) {
    this.name = name;
    this.greeting = function() {
        return ("Hello " + name +  " Go rock the industry!!");
          ▲
    };
}
</code>```

Body:
Why I am getting undefined in browser while using document.write() ?

In browser I get this output:

Sara
Hello Sara Go rock the industry!!undefined
Bob
Hello Bob Go rock the industry!!undefined

Body:
You are trying to use document.write on a function that does not return a value, rather performs document.write itself. Person.greeting() should return a value so you can use it when calling document.write(person2.greeting()).

It should be something like this:

function Person (name) {
    this.name = name;
    this.greeting = function() {
        return ("Hello " + name +  " Go rock the industry!!");
          ▲
    };
}


来源: stackexchange

问:
Linq to SQL anonymous types return null
I have a query that returns multiple result sets. But if one of the results is null, then nothing is returned. Is it possible to recover the data even if this result set is null?

Example:

```<code>from u in Units
select new
{
    Unit = u,
    AgreementType = from at in AgreementTypes
                    select new { at },
    OptionRightsType = from ortp in OptionRightsTypes
                       select new { ortp }
}
</code>```

In this example, if Unit is null, then no records are returned. Is it possible to recover the other result sets even if unit is null?

UPDATE

Example:

```<code>from u in Units
where u.Id == 1000
select new
{
    Unit = u,
    AgreementType = from at in AgreementTypes
                    select new { at },
    OptionRightsType = from ortp in OptionRightsTypes
                       select new { ortp }
}
</code>```

In the above example, I would exist the result to recover three IQueryable types, Unit, AgreementType, OptionRightsType.

This is the case, but if the query does not find a unit with id equal to 1000, then it returns null.

Can I still recover the AgreementType and OptionRightsType types when the unit return no records?

UPDATE 2

What I am trying to do is:

```<code>from u in Units
where u.Id == 1000
select new
{
    Unit = u
}
</code>```

and

```<code>from at in AgreementTypes
           select new
           {
               at,
               OptionRightsType = from ortp in OptionRightsTypes
                                  select new { ortp }
            }
</code>```

Two completely separate queries.

I just thought that I could join them together as the second query just pulls static data back

答:
if you have some relationship then you can use left outer join:</p>

```<code>var result = from u in units
                         join at in AgreementTypes on u equals at into A
                         from at in A.DefaultIfEmpty()
                         join ortp in OptionRightsTypes on u equals ortp into B
                         from ortp in B.DefaultIfEmpty()
                         where u.Id == 1000
                         select new
                         {
                             Unit = u ? u.SomeValue: "No units",
                             att = att ? att.SomeValue: "No att",
                             ortp = ortp.SomeValue ?? "No ortp"
                         };
</code>```

ContentLicense: CC BY-SA 3.0

Title: Linq to SQL anonymous types return null

Body:
I have a query that returns multiple result sets. But if one of the results is null, then nothing is returned. Is it possible to recover the data even if this result set is null?

Example:

from u in Units
select new
{
    Unit = u,
    AgreementType = from at in AgreementTypes
                    select new { at },
    OptionRightsType = from ortp in OptionRightsTypes
                       select new { ortp }
}

In this example, if Unit is null, then no records are returned. Is it possible to recover the other result sets even if unit is null?

UPDATE

Example:

from u in Units
where u.Id == 1000
select new
{
    Unit = u,
    AgreementType = from at in AgreementTypes
                    select new { at },
    OptionRightsType = from ortp in OptionRightsTypes
                       select new { ortp }
}

In the above example, I would exist the result to recover three IQueryable types, Unit, AgreementType, OptionRightsType.

This is the case, but if the query does not find a unit with id equal to 1000, then it returns null.

Can I still recover the AgreementType and OptionRightsType types when the unit return no records?

UPDATE 2

What I am trying to do is:

from u in Units
where u.Id == 1000
select new
{
    Unit = u
}

and

from at in AgreementTypes
           select new
           {
               at,
               OptionRightsType = from ortp in OptionRightsTypes
                                  select new { ortp }
            }

Two completely separate queries.

I just thought that I could join them together as the second query just pulls static data back

Body:
if you have some relationship then you can use left outer join:

var result = from u in units
                         join at in AgreementTypes on u equals at into A
                         from at in A.DefaultIfEmpty()
                         join ortp in OptionRightsTypes on u equals ortp into B
                         from ortp in B.DefaultIfEmpty()
                         where u.Id == 1000
                         select new
                         {
                             Unit = u ? u.SomeValue: "No units",
                             att = att ? att.SomeValue: "No att",
                             ortp = ortp.SomeValue ?? "No ortp"
                         };


问:
Using when and done and settimeout show hide div

function closecustomBox() {
  $('#dialog').hide();
}
$('#dialog').hide();
$('#anotherdialog').hide();
$("#show").click(function() {
  $('#dialog').show();
  $.when(
    setTimeout(function() {
      closecustomBox();
    }, 3000)
  ).done(function(x) {
    $('#anotherdialog').show();
  });
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#dialog {
  width: 101px;
  height: 101px;
  background-color: red;
}

#anotherdialog {
  width: 100px;
  height: 100px;
  background-color: blue;
}</code>```

show
```

What I want to happened is after clicking show will show the red box after 3 seconds the red box will hide then the blue box should show.

I want to achieve here is to not make the 2 div appear together

答:
If you wanted to use $.when then you need to pass in a $.Deferred() as an argument. Then resolve the $.Deferred() once the timeout completes which will call the method that we passed to .done() previously.

I also set the initial state of the dialogs via CSS to display: none; to avoid the need for hiding them via JS initially.

I've also provided an alternative which doesn't use jQuery deferred's which achieves the same results.

function closecustomBox() {
  $('#dialog').hide();
}

var dialog = $('#dialog');
var anotherDialog = $('#anotherdialog');
var timeout;

$("#show").click(function() {
  dialog.show();
  anotherDialog.hide();

  def = $.Deferred();
  $.when(def).done(function() {
    closecustomBox();
    anotherDialog.show();
  });

  if (timeout) clearTimeout(timeout); // Clear out any old timeouts to avoid flickers and strange behavior
  timeout = setTimeout(function() {
    def.resolve(); // Resolve the Deferred which will call def.done's callback
  }, 3000);
})

// Or if you don't want to use promises you can just elminate them entirely and simplify this example greatly
var timeout2;
 $("#show-2").click(function() {
      dialog.show();
      anotherDialog.hide();

      if (timeout) clearTimeout(timeout); // Clear out any old timeouts to avoid flickers and strange behavior
      timeout = setTimeout(function() {
        closecustomBox();
        anotherDialog.show();
      }, 3000);
    })```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#anotherdialog {
  width: 100px;
  height: 100px;
  background-color: blue;
  display: none;
}

#dialog {
  width: 101px;
  height: 101px;
  background-color: red;
  display: none;
}</code>```

show

Alternate Show
```

Body:
function closecustomBox() {
  $('#dialog').hide();
}
$('#dialog').hide();
$('#anotherdialog').hide();
$("#show").click(function() {
  $('#dialog').show();
  $.when(
    setTimeout(function() {
      closecustomBox();
    }, 3000)
  ).done(function(x) {
    $('#anotherdialog').show();
  });
})

#dialog {
  width: 101px;
  height: 101px;
  background-color: red;
}

#anotherdialog {
  width: 100px;
  height: 100px;
  background-color: blue;
}

show

What I want to happened is after clicking show will show the red box after 3 seconds the red box will hide then the blue box should show.

I want to achieve here is to not make the 2 div appear together

Body:
If you wanted to use $.when then you need to pass in a $.Deferred() as an argument. Then resolve the $.Deferred() once the timeout completes which will call the method that we passed to .done() previously.

I also set the initial state of the dialogs via CSS to display: none; to avoid the need for hiding them via JS initially.

I've also provided an alternative which doesn't use jQuery deferred's which achieves the same results.

function closecustomBox() {
  $('#dialog').hide();
}

var dialog = $('#dialog');
var anotherDialog = $('#anotherdialog');
var timeout;

$("#show").click(function() {
  dialog.show();
  anotherDialog.hide();

  def = $.Deferred();
  $.when(def).done(function() {
    closecustomBox();
    anotherDialog.show();
  });

  if (timeout) clearTimeout(timeout); // Clear out any old timeouts to avoid flickers and strange behavior
  timeout = setTimeout(function() {
    def.resolve(); // Resolve the Deferred which will call def.done's callback
  }, 3000);
})

// Or if you don't want to use promises you can just elminate them entirely and simplify this example greatly
var timeout2;
 $("#show-2").click(function() {
      dialog.show();
      anotherDialog.hide();

      if (timeout) clearTimeout(timeout); // Clear out any old timeouts to avoid flickers and strange behavior
      timeout = setTimeout(function() {
        closecustomBox();
        anotherDialog.show();
      }, 3000);
    })

#anotherdialog {
  width: 100px;
  height: 100px;
  background-color: blue;
  display: none;
}

#dialog {
  width: 101px;
  height: 101px;
  background-color: red;
  display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="dialog"></div>

<div id="anotherdialog"></div>

<div id="show">show</div>

<div id="show-2">Alternate Show</div>


问:
Can I get a specific variable value from Gson converter without creating a bunch of models?
If I have a response like that

```<code>{
    "data": {
        "main_category": {"user":{"name":"Ali","age":5}}
    }
}
</code>```

the expected way to get my userModel >>

```<code>class User{
    String name;
    int age;
}

class MainCategory{
    User user;
}

class Data{
    MainCategory data;
}
</code>```

Is there any way to get my user model directly? Like that

```<code>class Data{
    @SerializedName("data/main_category/user")
    User user;
}
</code>```

答:
Modifying data in such way may be not really a good idea due to data loss. Usually, (de)serialization libraries do not encourage you to do this. For such specific cases, in Gson, you must use custom (de)serializers implicitly if possible, or explicitly. However, you could implement it like this:

final class UserResponse {

    @SerializedName("data")
    @JsonAdapter(UserSkippingJsonDeserializer.class)
    final User user = null;

}
```

<p>The DTO above uses two annotations:</p>

<ul>
<li><code>@SerializedName</code> -- to map a JSON property name to the field name</li>
<li><code>@JsonAdapter</code> -- to associate a specific JSON type adapter for this particular field only</li>
</ul>

<pre class="lang-java prettyprint-override"><code>final class User {

    final String name = null;
    final int age = Integer.valueOf(0); /* disable javac inlining */

}
</code>```

Now, you can create a template method JsonDeserializer to make a primitive remapping job:

```<code>abstract class SkippingJsonDeserializer<T>
        implements JsonDeserializer<T> {

    protected abstract JsonElement extract(JsonElement jsonElement);

    @Override
    public final T deserialize(final JsonElement jsonElement, final Type type, final JsonDeserializationContext context)
            throws JsonParseException {
        return context.deserialize(extract(jsonElement), type);
    }

}
</code>```

And finally, define the User extraction rule:

final class UserSkippingJsonDeserializer
        extends SkippingJsonDeserializer<User> {

    // Gson will instantiate it itself
    private UserSkippingJsonDeserializer() {
    }

    @Override
    protected JsonElement extract(final JsonElement jsonElement) {
        return jsonElement.getAsJsonObject()
                .getAsJsonObject("main_category")
                .getAsJsonObject("user");
    }

}
```

<p>Test it out:</p>

```final UserResponse userResponse = gson.fromJson(jsonReader, UserResponse.class);
System.out.println(userResponse.user.name);
```

will produce:

Ali

If you want a more expressive implementation, you have to use something like JsonPath and implement a more complex JSON deserializer. For example: https://stackoverflow.com/a/42510510/166589

Body:
If I have a response like that

{
    "data": {
        "main_category": {"user":{"name":"Ali","age":5}}
    }
}

the expected way to get my userModel >>

class User{
    String name;
    int age;
}

class MainCategory{
    User user;
}

class Data{
    MainCategory data;
}

Is there any way to get my user model directly? Like that

class Data{
    @SerializedName("data/main_category/user")
    User user;
}

Body:
Modifying data in such way may be not really a good idea due to data loss. Usually, (de)serialization libraries do not encourage you to do this. For such specific cases, in Gson, you must use custom (de)serializers implicitly if possible, or explicitly. However, you could implement it like this:

final class UserResponse {

    @SerializedName("data")
    @JsonAdapter(UserSkippingJsonDeserializer.class)
    final User user = null;

}

The DTO above uses two annotations:

@SerializedName -- to map a JSON property name to the field name

@JsonAdapter -- to associate a specific JSON type adapter for this particular field only

final class User {

    final String name = null;
    final int age = Integer.valueOf(0); /* disable javac inlining */

}

Now, you can create a template method JsonDeserializer to make a primitive remapping job:

abstract class SkippingJsonDeserializer<T>
        implements JsonDeserializer<T> {

    protected abstract JsonElement extract(JsonElement jsonElement);

    @Override
    public final T deserialize(final JsonElement jsonElement, final Type type, final JsonDeserializationContext context)
            throws JsonParseException {
        return context.deserialize(extract(jsonElement), type);
    }

}

And finally, define the User extraction rule:

final class UserSkippingJsonDeserializer
        extends SkippingJsonDeserializer<User> {

    // Gson will instantiate it itself
    private UserSkippingJsonDeserializer() {
    }

    @Override
    protected JsonElement extract(final JsonElement jsonElement) {
        return jsonElement.getAsJsonObject()
                .getAsJsonObject("main_category")
                .getAsJsonObject("user");
    }

}

Test it out:

final UserResponse userResponse = gson.fromJson(jsonReader, UserResponse.class);
System.out.println(userResponse.user.name);

will produce:

Ali

If you want a more expressive implementation, you have to use something like JsonPath and implement a more complex JSON deserializer. For example: https://stackoverflow.com/a/42510510/166589


问:
Creating a new vector in Matlab with the help of a for-loop
Given the vector x, I would like to create a vector u0 componentwise by checking the components of x. Since only 0 <= 0 < 1 is true, and since 0 is the first component of x, the new vector u0 should actually look like [1, 0, 0, 0, 0, 0, 0, 0], but instead, Matlab gives me a vector that only contains 0. What have I done wrong?

```<code>x = [0, 1, 2, 3, 4, 5, 6, 7, 8];
u0 = [];

for i = 1:8
  if (0 <= x(i) < 1)
    u0(i) = 1;
  else
    u0(i) = 0;
  end
end
</code>```

答:
Your if conditional is not correct. You need to check on it. You have to proceed like below.

```<code>x = [0, 1, 2, 3, 4, 5, 6, 7, 8];
u0 = zeros(size(x));

for i = 1:8
    if x(i) >= 0 && x(i)<1
        u0(i) = 1;
    else
        u0(i) = 0;
    end
end
</code>```

Also, you can obtain the task in a single line, using the below:

```<code>u1 = zeros(size(x)) ;
u1(x>=0 & x<1) = 1 ;
</code>```

Body:
Given the vector x, I would like to create a vector u0 componentwise by checking the components of x. Since only 0 <= 0 < 1 is true, and since 0 is the first component of x, the new vector u0 should actually look like [1, 0, 0, 0, 0, 0, 0, 0], but instead, Matlab gives me a vector that only contains 0. What have I done wrong?

x = [0, 1, 2, 3, 4, 5, 6, 7, 8];
u0 = [];

for i = 1:8
  if (0 <= x(i) < 1)
    u0(i) = 1;
  else
    u0(i) = 0;
  end
end

Body:
Your if conditional is not correct. You need to check on it. You have to proceed like below.

x = [0, 1, 2, 3, 4, 5, 6, 7, 8];
u0 = zeros(size(x));

for i = 1:8
    if x(i) >= 0 && x(i)<1
        u0(i) = 1;
    else
        u0(i) = 0;
    end
end

Also, you can obtain the task in a single line, using the below:

u1 = zeros(size(x)) ;
u1(x>=0 & x<1) = 1 ;


问:
Comparing objects
I have a class it contains some string members, some double members and some array objects.

I create two objects of this class, is there any simplest, efficient way of comparing these objects and say their equal? Any suggestions?

I know how to write a compare function, but will it be time consuming.

答:
The 'proper' way to do it in .NET is to implement the IEquatable interface for your class:

```<code>public class SomeClass : IEquatable<SomeClass>
{
    public string Name { get; set; }
    public double Value { get; set; }
    public int[] NumberList { get; set; }

    public bool Equals(SomeClass other)
    {
        // whatever your custom equality logic is
        return other.Name == Name &&
            other.Value == Value &&
            other.NumberList == NumberList;
    }
}
</code>```

However, if you really want to do it right, this isn't all you should do. You should also override the Equals(object, object) and GetHashCode(object) methods so that, no matter how your calling code is comparing equality (perhaps in a Dictionary or perhaps in some loosely-typed collection), your code and not reference-type equality will be the determining factor:

```<code>public class SomeClass : IEquatable<SomeClass>
{
    public string Name { get; set; }
    public double Value { get; set; }
    public int[] NumberList { get; set; }

    /// <summary>
    /// Explicitly implemented IEquatable method.
    /// </summary>
    public bool IEquatable<SomeClass>.Equals(SomeClass other)
    {
        return other.Name == Name &&
            other.Value == Value &&
            other.NumberList == NumberList;
    }

    public override bool Equals(object obj)
    {
        var other = obj as SomeClass;
        if (other == null)
            return false;
        return ((IEquatable<SomeClass>)(this)).Equals(other);
    }

    public override int GetHashCode()
    {
        // Determine some consistent way of generating a hash code, such as...
        return Name.GetHashCode() ^ Value.GetHashCode() ^ NumberList.GetHashCode();
    }
}
</code>```

Title: Comparing objects

Body:
The 'proper' way to do it in .NET is to implement the IEquatable interface for your class:

public class SomeClass : IEquatable<SomeClass>
{
    public string Name { get; set; }
    public double Value { get; set; }
    public int[] NumberList { get; set; }

    public bool Equals(SomeClass other)
    {
        // whatever your custom equality logic is
        return other.Name == Name &&
            other.Value == Value &&
            other.NumberList == NumberList;
    }
}

However, if you really want to do it right, this isn't all you should do. You should also override the Equals(object, object) and GetHashCode(object) methods so that, no matter how your calling code is comparing equality (perhaps in a Dictionary or perhaps in some loosely-typed collection), your code and not reference-type equality will be the determining factor:

public class SomeClass : IEquatable<SomeClass>
{
    public string Name { get; set; }
    public double Value { get; set; }
    public int[] NumberList { get; set; }

    /// <summary>
    /// Explicitly implemented IEquatable method.
    /// </summary>
    public bool IEquatable<SomeClass>.Equals(SomeClass other)
    {
        return other.Name == Name &&
            other.Value == Value &&
            other.NumberList == NumberList;
    }

    public override bool Equals(object obj)
    {
        var other = obj as SomeClass;
        if (other == null)
            return false;
        return ((IEquatable<SomeClass>)(this)).Equals(other);
    }

    public override int GetHashCode()
    {
        // Determine some consistent way of generating a hash code, such as...
        return Name.GetHashCode() ^ Value.GetHashCode() ^ NumberList.GetHashCode();
    }
}

ContentLicense: CC BY-SA 2.5


问:
R vector - return all items of vector if vector is defined by minimum/maximum
Let's say I have the following vector:

```<code>vector <- c(0, 5)
</code>```

0 here defines my minimum, 10 defines my my maximum.

```<code>min <- min(vector)
</code>```

now I want to return all values, that are between 0 and 5:

```<code>fullvector <- c(min, min+1, min+2, min+3, min+4)
</code>```

Of course that fails If the number of items changes, so what is a better way to write this?

答:
I assume that in your question 10 should be replaced with 5?

Then what you ask for is obtained as follows

```<code>vector <- c(0, 5)
min_value <- min(vector)
max_value <- max(vector)
fullvector <- min_value:max_value
## [1] 0 1 2 3 4 5
</code>```

Body:
Let's say I have the following vector:

vector <- c(0, 5)

0 here defines my minimum, 10 defines my my maximum.

min <- min(vector)

now I want to return all values, that are between 0 and 5:

fullvector <- c(min, min+1, min+2, min+3, min+4)

Of course that fails If the number of items changes, so what is a better way to write this?

Body:
I assume that in your question 10 should be replaced with 5?

Then what you ask for is obtained as follows

vector <- c(0, 5)
min_value <- min(vector)
max_value <- max(vector)
fullvector <- min_value:max_value
## [1] 0 1 2 3 4 5


问:
Invalidate Cache using VaryByCustom
I want to invalidate cache using VaryByCustom attribute.
Following code is being used for cache setup.</p>

```<code>public override string GetVaryByCustomString(HttpContext context, string arg)
{
    if (!string.IsNullOrWhiteSpace(arg))
    {
        if (context.User.Identity.Name != null)
        {
            return context.User.Identity.Name;
        }
    }
    return base.GetVaryByCustomString(context, arg);
}
</code>```

答:
Are you using it like this:

Make sure you decorate your action with attribute:

```<code> [OutputCache(Duration = 3600, VaryByParam = "*", Location = OutputCacheLocation.Server, VaryByCustom =
  "YourStringThatIsArgParamInYourGlobalAsaxMethod")]
  public ActionResult MyActionOnTheController(string myParam)
 {
 }
</code>```

Title: Invalidate Cache using VaryByCustom

Body:
I want to invalidate cache using VaryByCustom attribute.
Following code is being used for cache setup.

public override string GetVaryByCustomString(HttpContext context, string arg)
{
    if (!string.IsNullOrWhiteSpace(arg))
    {
        if (context.User.Identity.Name != null)
        {
            return context.User.Identity.Name;
        }
    }
    return base.GetVaryByCustomString(context, arg);
}

Body:
Are you using it like this:

Make sure you decorate your action with attribute:

 [OutputCache(Duration = 3600, VaryByParam = "*", Location = OutputCacheLocation.Server, VaryByCustom =
  "YourStringThatIsArgParamInYourGlobalAsaxMethod")]
  public ActionResult MyActionOnTheController(string myParam)
 {
 }


问:
Odoo 10 - Access denied for biller to register payment
I've two server environments, One for testing and the other for production.
Both are working on Ubuntu server 16 and running Odoo 10 Enterprise edition. The only difference is that on the production server I used Nginx to allow Odoo working on port 80 instead of 8069.

Before we migrate our database to the production server, everything was working smoothly. Now the problem is when the sales person who has permissions of "Sales / User: All Documents" and "Accounting & Finance / Billing" tries to register payments for an invoice he gets this message

However he doesn't get the same message in the test server in which the database is the same as the production server db. I checked the access control list of model "account.journal" in both databases and there was no difference between them. I checked the log file and found this error.

```<code>odoo.addons.base.ir.ir_model: Access Denied by ACLs for operation: write, uid: 38, model: account.journal
</code>```

I understand the problem lies in the access permissions. But my question here is why the Sales person was able to register the payment in the test server but not in production server. can anyone help me to understand why this could happen and how to fix it. Could it be due to Nginx?!

答:
Hi you can check your odoo version release, if you download odoo using git you can check it using git log command in your odoo directory, if your last commit is deferent ( local and productio ) maybe that is the problem.

Actually, you can update manually the access right for account.journal table.

Body:
I've two server environments, One for testing and the other for production.
Both are working on Ubuntu server 16 and running Odoo 10 Enterprise edition. The only difference is that on the production server I used Nginx to allow Odoo working on port 80 instead of 8069.

Before we migrate our database to the production server, everything was working smoothly. Now the problem is when the sales person who has permissions of "Sales / User: All Documents" and "Accounting & Finance / Billing" tries to register payments for an invoice he gets this message

However he doesn't get the same message in the test server in which the database is the same as the production server db. I checked the access control list of model "account.journal" in both databases and there was no difference between them. I checked the log file and found this error.

odoo.addons.base.ir.ir_model: Access Denied by ACLs for operation: write, uid: 38, model: account.journal

I understand the problem lies in the access permissions. But my question here is why the Sales person was able to register the payment in the test server but not in production server. can anyone help me to understand why this could happen and how to fix it. Could it be due to Nginx?!


问:
Custom search through ArrayList for array names
I'm trying to implement search filter with getFilter method in my custom adapter.

There are two models of search through the list.

search for title of an item,

search for genre[] of an item.

(But I'm just talking about genre here).

The below code is working fine, but what I need is just a little more customized way to search in genre[].

What I'm trying to achieve is: (What I want):

multi-keyword searching, each category separated with,. example: genre1,genre2

(What I have done):

When I type genre1,genre2 then it gives the items that have this sequence in genres, it won't give  genre1,genre3,genre2 , or just genre1.

Can you help, please?

getFilter:

```<code>@Override
public Filter getFilter() {
    Filter filter = new Filter() {
        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            dataList = (List<ProductLocal>) results.values;
            notifyDataSetChanged();
        }
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            FilterResults results = new FilterResults();
            List<ProductLocal> filteredList = new ArrayList<>();
            constraint = constraint.toString().toLowerCase();
            for (int i = 0; i < dataListFilter.size(); i++) {
                ProductLocal dataNames = dataListFilter.get(i);

                String genreStr = "";
                for (String str : dataNames.getGenre()) {
                    genreStr += str + ",";
                }

                if (dataNames.getTitle().toLowerCase().startsWith(constraint.toString())
                 || genreStr.toLowerCase().contains(constraint.toString())) {
                    filteredList.add(dataNames);
                }
            }
            results.count = filteredList.size();
            results.values = filteredList;
            return results;
        }

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

答:
You can split search term by ,

```<code>   String[] searmTearmArray= serachTerm.split(",");
</code>```

now using for loop you can search these terms.

Body:
I'm trying to implement search filter with getFilter method in my custom adapter.

There are two models of search through the list.

search for title of an item,

search for genre[] of an item.

(But I'm just talking about genre here).

The below code is working fine, but what I need is just a little more customized way to search in genre[].

What I'm trying to achieve is: (What I want):

multi-keyword searching, each category separated with,. example: genre1,genre2

(What I have done):

When I type genre1,genre2 then it gives the items that have this sequence in genres, it won't give  genre1,genre3,genre2 , or just genre1.

Can you help, please?

getFilter:

@Override
public Filter getFilter() {
    Filter filter = new Filter() {
        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            dataList = (List<ProductLocal>) results.values;
            notifyDataSetChanged();
        }
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            FilterResults results = new FilterResults();
            List<ProductLocal> filteredList = new ArrayList<>();
            constraint = constraint.toString().toLowerCase();
            for (int i = 0; i < dataListFilter.size(); i++) {
                ProductLocal dataNames = dataListFilter.get(i);

                String genreStr = "";
                for (String str : dataNames.getGenre()) {
                    genreStr += str + ",";
                }

                if (dataNames.getTitle().toLowerCase().startsWith(constraint.toString())
                 || genreStr.toLowerCase().contains(constraint.toString())) {
                    filteredList.add(dataNames);
                }
            }
            results.count = filteredList.size();
            results.values = filteredList;
            return results;
        }

    };
    return filter;
}

Body:
You can split search term by ,

   String[] searmTearmArray= serachTerm.split(",");

now using for loop you can search these terms.


问:
Get variable GET in Yii2 not working
Basiclly I have an url that have a parameter.

So, I need to access those parameter using GET. This is the GET that coming:

```<code>Array
   (
     [r] => hanwa/incoming-pipe/assign-incoming
     [1] => Array
            (
              [min_urut] => 1
              [max_urut] => 44
            )

     [_] => 1496645704980
    )
</code>```

In docs, docs,
We can use like this :

```<code> echo $request->get('min_urut');
</code>```

But, I got nothing. Please Advise.

答:
Use Concept of ArrayHelper class :-> http://www.yiiframework.com/doc-2.0/guide-helper-array.html#getting-values
ex:

```<code>$data = ArrayHelper::getValue($request->get(), 'Temp.yourvalue.yourindex');
</code>```

Main use of $request->get() method mainly returns to you a value from $_GET,
 so example is

```<code>$temp = $request->get('Temp'); // Here $temp variable contains $_GET['Temp']
$data = $temp['yourvaluename'][0];
</code>```

Title: Get variable GET in Yii2 not working

Body:
Basiclly I have an url that have a parameter.

So, I need to access those parameter using GET. This is the GET that coming:

Array
   (
     [r] => hanwa/incoming-pipe/assign-incoming
     [1] => Array
            (
              [min_urut] => 1
              [max_urut] => 44
            )

     [_] => 1496645704980
    )

In docs, docs,
We can use like this :

 echo $request->get('min_urut');

But, I got nothing. Please Advise.

Body:
Use Concept of ArrayHelper class :-> http://www.yiiframework.com/doc-2.0/guide-helper-array.html#getting-values
ex:

$data = ArrayHelper::getValue($request->get(), 'Temp.yourvalue.yourindex');

Main use of $request->get() method mainly returns to you a value from $_GET,
 so example is

$temp = $request->get('Temp'); // Here $temp variable contains $_GET['Temp']
$data = $temp['yourvaluename'][0];


问:
Receiving spam from AWS SMS short code
I've been using AWS SNS to send SMS short codes, which I have been able to do successfully (The short code I receive AWS SMS messages from is 37083). However, I noticed that if I respond to any of these messages, I get spam back.

AWS SNS does not provide two way communication, but if I respond to the short code 37083 "STOP" I receive spam back. I received the following message:

You are unsubscribed from alerts. No more messages will be sent. Reply HELP for help, email help@smshelps.com or 1-xxx-xxx-xxxx.

This seemed odd, so I replied "HELP" and got the folloiwng message back:

For Daily Job Match Alerts: Help email Support@smshelps.com or 1-xxx-xxx-xxxx. Msg and data rates may apply. text STOP to cancel. 3 msgs/week****

If AWS doesn't support two way communication, who/which provider is responding and why are we getting this spam?

I understand that we are using a shared short code, but aren't the pooled AWS short codes only shared by AWS users? Clearly this one seems to becoming from a different provider.

I dug a bit deeper and found that the short code 37083 is leased to amazon and no one else. I also found a list of Amazon Short codes. I tried sending "HELP" to some of the other Amazon short codes and did receive messages back, such as following message when I sent "HELP" to 58988 (58988 is a shared short code leased by Amazon)

Where is my Truck. Delivery alerts. Recurring messages...

Is there some other provider that is also leasing the same short code? My understanding was that only one provider leases a short code at a time. That provider then managers that shared short code and shares it with users.

答:
There are no providers using the same short code and it wasn't spam.

The US and Canada require that short codes must accept STOP/HELP messages for end-users to opt-out from receiving any further messages, and to receive more information, respectively. That was the default message replied from any short code that didn't request a specific message for these HELP/STOP keywords.

The message replied to these keywords has been replaced with a generic one.

2-way communication is not supported yet.

Source (disclosure): I work in that team.

Title: Receiving spam from AWS SMS short code


问:
How to pass an older date in echo?
I'm using the below script to echo a dynamic date to a file;

```<code>purgedate=$(date +"$%m/%d/%Y %r" --date='6 month ago')

echo "6 months ago was" \"$purgedate\" > myFile.txt
</code>```

The output I get is:

```<code>6 months ago was "$12/05/2016 12:20:11 AM"
</code>```

How do I echo without the "$" sign before the date?
I want the following output, without the "$" before the date.

```<code>6 months ago was "12/05/2016 12:20:11 AM"
</code>```

答:
You accidentally add '$' in your string: "$%m/%d/%Y %r".

By removing it, it works:

```<code>purgedate=$(date +"%m/%d/%Y %r" --date='6 month ago')
echo "6 months ago was" \"$purgedate\" > myFile.txt
</code>```

Title: How to pass an older date in echo?

Body:
I'm using the below script to echo a dynamic date to a file;

purgedate=$(date +"$%m/%d/%Y %r" --date='6 month ago')

echo "6 months ago was" \"$purgedate\" > myFile.txt

The output I get is:

6 months ago was "$12/05/2016 12:20:11 AM"

How do I echo without the "$" sign before the date?
I want the following output, without the "$" before the date.

6 months ago was "12/05/2016 12:20:11 AM"

Body:
You accidentally add '$' in your string: "$%m/%d/%Y %r".

By removing it, it works:

purgedate=$(date +"%m/%d/%Y %r" --date='6 month ago')
echo "6 months ago was" \"$purgedate\" > myFile.txt


问:
Capitalise the first letter of every word as user types unless user insists on lower case
I am working on the script where I want the first letter and the letter after a space to be capitalized. If a word follows a hyphen (-), it should not be capitalized until and unless a space follows after the hyphen (-). If the user wants to lower case the first letter of any word, it should work dynamically.

This I achieved using the below script.

The challenge here is, that it should be possible for the user to change the uppercased letter to a lower case while typing

I am not able to achieve that feature.

Example:

If the user types "hello world", the output will be "Hello World", and if the user wants to lower case the letter "W"  from the word "World" by deleting the letter "W" and retyping the letter "w", the expected result should be "Hello world".

$.fn.capitalize = function() {
  $.each(this, function() {
    var split = this.value.split(' ');
    for (var i = 0, len = split.length; i < len; i++) {
      split[i] = split[i].charAt(0).toUpperCase() + split[i].slice(1);
    }
    this.value = split.join(' ');
  });
  return this;
};

$('textarea').on('keyup', function() {
  $(this).capitalize();
}).capitalize();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<textarea></textarea></code>```

答:
There you go :)</p>

```<code>function useName (str) {
  if(!str) return '';
  return str
  .split(' ')
  .map(function (word) {
    if(word && word[0])
      return (word[0].toUpperCase() + word.substring(1).toLowerCase());
     else
      return '';
   })
  .join(' ')
}
</code>```

Body:
I am working on the script where I want the first letter and the letter after a space to be capitalized. If a word follows a hyphen (-), it should not be capitalized until and unless a space follows after the hyphen (-). If the user wants to lower case the first letter of any word, it should work dynamically.

This I achieved using the below script.

The challenge here is, that it should be possible for the user to change the uppercased letter to a lower case while typing

I am not able to achieve that feature.

Example:

If the user types "hello world", the output will be "Hello World", and if the user wants to lower case the letter "W"  from the word "World" by deleting the letter "W" and retyping the letter "w", the expected result should be "Hello world".

$.fn.capitalize = function() {
  $.each(this, function() {
    var split = this.value.split(' ');
    for (var i = 0, len = split.length; i < len; i++) {
      split[i] = split[i].charAt(0).toUpperCase() + split[i].slice(1);
    }
    this.value = split.join(' ');
  });
  return this;
};

$('textarea').on('keyup', function() {
  $(this).capitalize();
}).capitalize();

<textarea></textarea>

Body:
There you go :)

function useName (str) {
  if(!str) return '';
  return str
  .split(' ')
  .map(function (word) {
    if(word && word[0])
      return (word[0].toUpperCase() + word.substring(1).toLowerCase());
     else
      return '';
   })
  .join(' ')
}


问:
MySQL no longer shows error message, only code
Since I upgraded to MYSQL 5.7.16, I no longer have error messages, which is annoying (I now have to remember all codes) and gets very very annoying when it comes to SQL 1064 (Error: 1064 SQLSTATE: 42000 (ER_PARSE_ERROR) %s near '%s' at line %d says the doc... so easy to debug with no info nor line number).

Same goes for warnings: if a line returns a warning, I can no longer read it (show warnings doesn't crash, but it returns no result).

So I bet (hope!) MySQL made a configuration change: what's the option to get the MySQL error messages back?

答:
The problem is related to the lc-messages-dir directive.
In last versions, the default dir is wrong (at least under Debian).

Put this into your mysql.cnf :

```<code>lc-messages-dir = /usr/share/mysql/english/
</code>```

And error messages will be back ;)

Body:
The problem is related to the lc-messages-dir directive.
In last versions, the default dir is wrong (at least under Debian).

Put this into your mysql.cnf :

lc-messages-dir = /usr/share/mysql/english/

And error messages will be back ;)


问:
Activity cannot be cast to android.app.Application
When I start the application, it force close.

This is the LogCat:

```<code>java.lang.RuntimeException: Unable to instantiate application com.blocktrekacademy.officialblocktrek.Authentication: java.lang.ClassCastException: com.blocktrekacademy.officialblocktrek.Authentication cannot be cast to android.app.Application
</code>```

[UPDATED] : This is my AndroidManifest.xml:

```<code>    ...
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".Authentication"
            android:label="@string/title_activity_authentication"
            android:screenOrientation="portrait"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>
</code>```

This is my Authentication.java

```<code>package com.blocktrekacademy.officialblocktrek;

import ...

public class Authentication extends AppCompatActivity {
    ...
</code>```

答:
First, remove android:name=".Authentication" property in <application> tag.

Your Authentication class is an Activity, not an Application. So, you have to declare it as such:

```<code><application>

    ...

    <activity android:name=".Authentication"
      <intent-filter>
          <action android:name="android.intent.action.MAIN"/>
          <category android:name="android.intent.category.LAUNCHER"/>
      </intent-filter>
    </activity>

</application>
</code>```

That intent-filter declares the Activity as the "main" activity, so it will be launched when your app starts.

Body:
When I start the application, it force close.

This is the LogCat:

java.lang.RuntimeException: Unable to instantiate application com.blocktrekacademy.officialblocktrek.Authentication: java.lang.ClassCastException: com.blocktrekacademy.officialblocktrek.Authentication cannot be cast to android.app.Application

[UPDATED] : This is my AndroidManifest.xml:

    ...
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".Authentication"
            android:label="@string/title_activity_authentication"
            android:screenOrientation="portrait"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

This is my Authentication.java

package com.blocktrekacademy.officialblocktrek;

import ...

public class Authentication extends AppCompatActivity {
    ...

Body:
First, remove android:name=".Authentication" property in <application> tag.

Your Authentication class is an Activity, not an Application. So, you have to declare it as such:

<application>

    ...

    <activity android:name=".Authentication"
      <intent-filter>
          <action android:name="android.intent.action.MAIN"/>
          <category android:name="android.intent.category.LAUNCHER"/>
      </intent-filter>
    </activity>

</application>

That intent-filter declares the Activity as the "main" activity, so it will be launched when your app starts.


问:
DWH from multiple schemas
I have a project in postgresql to create a DWH from multiple schemas. The schemas have the same structure(tables, constrains).
I am stuck on this problem : I have a table "employees" in all the schemas that i will use in DWH. The first entry in schema1 table employees is 1 John Dow, the first entry in schema2 table employees is 1 Mary Jane (the id column is auto increment).
Is there a way to create a DWH with this structure ? Is there a way to partition the schemas data ?
Thank you.</p>

答:
Recompute the primary key as

```<code><id> * <# of schemas> + <schema number>
</code>```

For example, if you have three schemas, number 7 from the first schema would become 7 * 3 + 1 = 22, and number 5 from the third schema would become 5 * 3 + 3 = 18.

That way you can easily translate all numbers in a collision-free fashion.

Title: DWH from multiple schemas

Body:
Recompute the primary key as

<id> * <# of schemas> + <schema number>

For example, if you have three schemas, number 7 from the first schema would become 7 * 3 + 1 = 22, and number 5 from the third schema would become 5 * 3 + 3 = 18.

That way you can easily translate all numbers in a collision-free fashion.


问:
How can I confirm that firebase notification was actually sent (fcm)?
I allow users to send notifications out through my website. The notifications are working, however, I would like a way to actually confirm if the notification was sent out (in code), or if that is not possible at least confirmation that the curl worked, so I can show a message on my website that it either succeeded or failed. In my jquery post request, the status seems to always be "success", even if I provide an invalid API_ACCESS_KEY in my php (so it obviously is not sending the notification yet it is still saying success). How can I know for sure that the notification was sent out? Grateful for any help.

Here is my post request in index.html:

```<code>$("#send-button").click(function(){
    if($("#send").val().length == 0) {
        return;
    } else {
        $.post("php/send-notification.php",
        {
            notification_message: $("#send").val()
        },
        function(data, status) {
            alert("Data: " + data + "\nStatus: " + status);
            // status seems to always be "success" even with an invalid API_ACCESS_KEY
        });
    }
});
</code>```

Here is send-notification.php:

```<code><?php
    define( 'API_ACCESS_KEY', 'AAA....AAA' );

    $msg = array
    (
        'body'  => $_POST['notification_message'],
        'vibrate'   => 1,
        'sound'     => 1,
        'badge'     => 1
    );

    $fields = array
    (
        'to'            => "/topics/global",
        'notification'  => $msg,
        'priority'      => 'high'
    );

    $headers = array
    (
        'Authorization: key=' . API_ACCESS_KEY,
        'Content-Type: application/json'
    );

    $ch = curl_init();
    curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' );
    curl_setopt( $ch,CURLOPT_POST, true );
    curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
    curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
    curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
    curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
    $result = curl_exec( $ch );
    curl_close( $ch );
?>
</code>```

答:
You will get Success  result in
$result = curl_exec( $ch );
Result format will be </p>

```<code> "multicast_id": 6581315937669460028,
  "success": 1,
  "failure": 0,
  "canonical_ids": 0,
  "results": [
    {
      "message_id": "0:1495111364345221%d8a1cb15f9fd7ecd"
    }
  ]
}
</code>```

Body:
I allow users to send notifications out through my website. The notifications are working, however, I would like a way to actually confirm if the notification was sent out (in code), or if that is not possible at least confirmation that the curl worked, so I can show a message on my website that it either succeeded or failed. In my jquery post request, the status seems to always be "success", even if I provide an invalid API_ACCESS_KEY in my php (so it obviously is not sending the notification yet it is still saying success). How can I know for sure that the notification was sent out? Grateful for any help.

Here is my post request in index.html:

$("#send-button").click(function(){
    if($("#send").val().length == 0) {
        return;
    } else {
        $.post("php/send-notification.php",
        {
            notification_message: $("#send").val()
        },
        function(data, status) {
            alert("Data: " + data + "\nStatus: " + status);
            // status seems to always be "success" even with an invalid API_ACCESS_KEY
        });
    }
});

Here is send-notification.php:

<?php
    define( 'API_ACCESS_KEY', 'AAA....AAA' );

    $msg = array
    (
        'body'  => $_POST['notification_message'],
        'vibrate'   => 1,
        'sound'     => 1,
        'badge'     => 1
    );

    $fields = array
    (
        'to'            => "/topics/global",
        'notification'  => $msg,
        'priority'      => 'high'
    );

    $headers = array
    (
        'Authorization: key=' . API_ACCESS_KEY,
        'Content-Type: application/json'
    );

    $ch = curl_init();
    curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' );
    curl_setopt( $ch,CURLOPT_POST, true );
    curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
    curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
    curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
    curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
    $result = curl_exec( $ch );
    curl_close( $ch );
?>

Body:
You will get Success  result in
$result = curl_exec( $ch );
Result format will be

 "multicast_id": 6581315937669460028,
  "success": 1,
  "failure": 0,
  "canonical_ids": 0,
  "results": [
    {
      "message_id": "0:1495111364345221%d8a1cb15f9fd7ecd"
    }
  ]
}


答:
Please try by splitting constraint string like below:</p>

```<code>@Override
public Filter getFilter() {
    @SuppressWarnings("UnnecessaryLocalVariable")
    Filter filter = new Filter() {
        @SuppressWarnings("unchecked")
        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            dataList = (List<ProductLocal>) results.values;
            notifyDataSetChanged();
        }

        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            FilterResults results = new FilterResults();
            List<ProductLocal> filteredList = new ArrayList<>();

            for (int i = 0; i < dataListFilter.size(); i++) {
                ProductLocal dataNames = dataListFilter.get(i);

                int count = 0;
                String[] terms = constraint.toString().split(",");

                for (int j = 0; j < terms.length; j++) {

                    String term = terms[j];
                    for (String str : dataNames.getGenre()) {

                        if (str.equals(term) || str.contains(term)) {
                            count++;
                            if (count == terms.length) {
                                filteredList.add(dataNames);
                            }
                        }
                    }
                }
            }

            results.count = filteredList.size();
            results.values = filteredList;
            return results;
        }

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

Title: Custom search through ArrayList for array names

Body:
Please try by splitting constraint string like below:

@Override
public Filter getFilter() {
    @SuppressWarnings("UnnecessaryLocalVariable")
    Filter filter = new Filter() {
        @SuppressWarnings("unchecked")
        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            dataList = (List<ProductLocal>) results.values;
            notifyDataSetChanged();
        }

        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            FilterResults results = new FilterResults();
            List<ProductLocal> filteredList = new ArrayList<>();

            for (int i = 0; i < dataListFilter.size(); i++) {
                ProductLocal dataNames = dataListFilter.get(i);

                int count = 0;
                String[] terms = constraint.toString().split(",");

                for (int j = 0; j < terms.length; j++) {

                    String term = terms[j];
                    for (String str : dataNames.getGenre()) {

                        if (str.equals(term) || str.contains(term)) {
                            count++;
                            if (count == terms.length) {
                                filteredList.add(dataNames);
                            }
                        }
                    }
                }
            }

            results.count = filteredList.size();
            results.values = filteredList;
            return results;
        }

    };
    return filter;
}


问:
How I can take backup of selected Procedures or Functions from Oracle database
I want to save selected procedures and functions for backup purposes in .prc file format. As of now I am doing this manually by the help of PLSQL Developer.

I have found some solutions, but none worked for me. Here is an example.

expdp schemas=Test, include= procedure like 'abc%';

and here is the error while executing the above script.

SP2-0734: unknown command beginning "expdp sche..." - rest of line ignored.

Please help me if there is any way to automate this manual effort.

答:
you can try this

```<code> SELECT TEXT FROM
 ALL_SOURCE
 WHERE NAME LIKE '%abc%'
 TYPE='PACKAGE BODY'
 ORDER BY LINE
</code>```

distinct type

PROCEDURE , PACKAGE  ,PACKAGE BODY, TYPE BODY, TRIGGER ,FUNCTION ,TYPE

Body:
you can try this

 SELECT TEXT FROM
 ALL_SOURCE
 WHERE NAME LIKE '%abc%'
 TYPE='PACKAGE BODY'
 ORDER BY LINE

distinct type

PROCEDURE , PACKAGE  ,PACKAGE BODY, TYPE BODY, TRIGGER ,FUNCTION ,TYPE


问:
How Here counts requests when using their map control?
In the documentation, it is mentioned this: "Map, satellite and traffic tiles, for which a transaction equals 15 requests", but what counts as a request when showing their map on an Android app?

Each user section? Each time he pans/zooms/moves the map?

I've created a sample code based on their routing example, but the Usage Stats on Developer dashboard doesn't show anything.

答: If you are using Starter SDK, then you will pay for requests. For Premium SDK pricing is different. To get details about pricing for Premium SDK go to https://developer.here.com/contact-us</p>


答:
You're getting a dollar sign in your output because you've included a dollar sign in your date format.

```<code>purgedate=$(date +"$%m/%d/%Y %r" --date='6 month ago')
                   ^
</code>```

Remove it, and it will no longer be there. :-)

I should point out that the date format you're using is obsolete and imprecise. For any new development, you should consider ISO 8601 which has existed since 1988 and is THE standard way of representing dates.

And it may even give you opportunities for shortening things, too; '+%Y-%m-%d' can be replaced with '+%F' in most environments.

Title: How to pass an older date in echo?

Body:
You're getting a dollar sign in your output because you've included a dollar sign in your date format.

purgedate=$(date +"$%m/%d/%Y %r" --date='6 month ago')
                   ^

Remove it, and it will no longer be there. :-)

I should point out that the date format you're using is obsolete and imprecise. For any new development, you should consider ISO 8601 which has existed since 1988 and is THE standard way of representing dates.

And it may even give you opportunities for shortening things, too; '+%Y-%m-%d' can be replaced with '+%F' in most environments.


问:
How to send a tall array to a classifier?
I am trying to send a tall array to the classifier to run, however, i am facing this error:

```<code>tt=fitcnb(tall(data),tall(label));
Error using tall/fitcnb (line 39)
Incompatible tall array arguments. The tall arrays must be based on the same datastore.
</code>```

Could someone give me some hints how to tackle this error?
Thanks

答:
When working with tall arrays in MATLAB, the constructor that you're using is really intended only for prototyping - ultimately, it is expected that you will derive your tall arrays from a datastore, and for fitcnb to work correctly, the inputs must derive from the same datastore to ensure they are compatible (the error message is somewhat misleading in this case - the tall arrays are not compatible because they were created with separate invocations of the constructor).

That being said, you can make this prototype version work by creating a single tall table and using that with fitcnb:

```<code>% Get some data for fitcnb
load fisheriris
X = meas(:,3:4);
Y = species;
% Make a single tall table
data = tall(table(X, Y));
% Run 'fitcnb'
fitcnb(data.X, data.Y)
</code>```

Body:
I am trying to send a tall array to the classifier to run, however, i am facing this error:

tt=fitcnb(tall(data),tall(label));
Error using tall/fitcnb (line 39)
Incompatible tall array arguments. The tall arrays must be based on the same datastore.

Could someone give me some hints how to tackle this error?
Thanks

Body:
When working with tall arrays in MATLAB, the constructor that you're using is really intended only for prototyping - ultimately, it is expected that you will derive your tall arrays from a datastore, and for fitcnb to work correctly, the inputs must derive from the same datastore to ensure they are compatible (the error message is somewhat misleading in this case - the tall arrays are not compatible because they were created with separate invocations of the constructor).

That being said, you can make this prototype version work by creating a single tall table and using that with fitcnb:

% Get some data for fitcnb
load fisheriris
X = meas(:,3:4);
Y = species;
% Make a single tall table
data = tall(table(X, Y));
% Run 'fitcnb'
fitcnb(data.X, data.Y)


问:
Database design, for optimized access
I jump straight into the problem, currently I have a table as such

```<code>id | model | CategoryId | etc...
</code>```

Now my new requirement is to have support for multiple categories. So I have two possible solutions in mind but I would like to know problems that both this designs might create. I also know that at most I can have 6 categories, also I can't create a linker table to link product to category.

On first design I would simply create column  CategoryN

```<code>id | model | CategoryId1 | CategoryId2 | CategoryId3 | CategoryId4 | etc...
</code>```

But this would make queries hideous,

```<code>   id | model | CategoryId | etc...
</code>```

My second approach is simply to add product for N categories

```<code>   id | model | CategoryId | etc...
   1 | ABC   | 1           | etc...
   2 | ABC   | 2           | etc...
   3 | ABC   | 3           | etc...
</code>```

I think queries would be cleaner but not necessarily simpler.
Another aspect is that I am looking at the performance of the queries and it looks like the first approach would be better.
I hope this is clear enough.

Thanks for any suggestions.

答:
Can you make the CategoryID values bit-field "flags"?

If so, you could keep your performance high by using the single CategoryID field that you have now, keep your queries simple by not adding a bunch of new columns, and would have up to 32 categories for each product over time (assuming that CategoryID is an int).

So, your CategoryID values would be:

```<code>   id | model | CategoryId | etc...
   1 | ABC   | 1           | etc...
   2 | ABC   | 2           | etc...
   3 | ABC   | 4           | etc...
   3 | ABC   | 8           | etc...
</code>```

You would store the total of all of the CategoryIDs in the CategoryID column (for backward compatibility) and then would have to test the value of the field to find out if a specific category were "set".  Incidentally, you can do that directly in your query as well.

It's not "best practice", which would really require a brand-new table and a lot of joining, but if you are looking for a way to shoe-horn something in there that will work, bit-field flags will do the trick.

Title: Database design, for optimized access

Body:
I jump straight into the problem, currently I have a table as such

id | model | CategoryId | etc...

Now my new requirement is to have support for multiple categories. So I have two possible solutions in mind but I would like to know problems that both this designs might create. I also know that at most I can have 6 categories, also I can't create a linker table to link product to category.

On first design I would simply create column  CategoryN

id | model | CategoryId1 | CategoryId2 | CategoryId3 | CategoryId4 | etc...

But this would make queries hideous,

   id | model | CategoryId | etc...

My second approach is simply to add product for N categories

   id | model | CategoryId | etc...
   1 | ABC   | 1           | etc...
   2 | ABC   | 2           | etc...
   3 | ABC   | 3           | etc...

I think queries would be cleaner but not necessarily simpler.
Another aspect is that I am looking at the performance of the queries and it looks like the first approach would be better.
I hope this is clear enough.

Thanks for any suggestions.

Body:
Can you make the CategoryID values bit-field "flags"?

If so, you could keep your performance high by using the single CategoryID field that you have now, keep your queries simple by not adding a bunch of new columns, and would have up to 32 categories for each product over time (assuming that CategoryID is an int).

So, your CategoryID values would be:

   id | model | CategoryId | etc...
   1 | ABC   | 1           | etc...
   2 | ABC   | 2           | etc...
   3 | ABC   | 4           | etc...
   3 | ABC   | 8           | etc...

You would store the total of all of the CategoryIDs in the CategoryID column (for backward compatibility) and then would have to test the value of the field to find out if a specific category were "set".  Incidentally, you can do that directly in your query as well.

It's not "best practice", which would really require a brand-new table and a lot of joining, but if you are looking for a way to shoe-horn something in there that will work, bit-field flags will do the trick.


问:
name space comprehension in python with if and else
code first:

```<code># case01
def x():
    if False:
        #x2 = 22
        print x1
    else:
        print x2

if __name__ == '__main__':
    if False:
        x1 = 1
    else:
        x2 = 2
    x()
</code>```

case01's output:

```<code>2
</code>```

No problem! but when i uncomment #x2 = 22 in if False: block and rerun, it will got error:

```<code>---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
<ipython-input-4-e36cb32b2c83> in <module>()
     11     else:
     12         x2 = 2
---> 13     x()

<ipython-input-4-e36cb32b2c83> in x()
      4         print x1
      5     else:
----> 6         print x2
      7
      8 if __name__ == '__main__':

UnboundLocalError: local variable 'x2' referenced before assignment
</code>```

As i see, if False: block will not excute, But why x2 = 22 take some effect to the script i worte?

My python version: 2.7.13

答: x2 is not defined in the function x's scope. Try moving "x2 = 22" out of the if statement, and it will work fine. Just for the record, doing "if False" is entirely useless, and is making the computer do an extra calculation. In this small of code it makes no difference but in bigger code there will be a noticeable difference in efficiency. </p>

Body:
code first:

# case01
def x():
    if False:
        #x2 = 22
        print x1
    else:
        print x2

if __name__ == '__main__':
    if False:
        x1 = 1
    else:
        x2 = 2
    x()

case01's output:

2

No problem! but when i uncomment #x2 = 22 in if False: block and rerun, it will got error:

---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
<ipython-input-4-e36cb32b2c83> in <module>()
     11     else:
     12         x2 = 2
---> 13     x()

<ipython-input-4-e36cb32b2c83> in x()
      4         print x1
      5     else:
----> 6         print x2
      7
      8 if __name__ == '__main__':

UnboundLocalError: local variable 'x2' referenced before assignment

As i see, if False: block will not excute, But why x2 = 22 take some effect to the script i worte?

My python version: 2.7.13


问:
Is there any way in C# to automatically set the DefaultValueAttribute for properties that have default values set?
Is there anyway to implicitly carry out the following pattern?

```<code>    [DefaultValue(true)]
    public bool SomeBooleanProperty { get; set; } = true;
</code>```

Repeating the default value in two locations just seems to be begging for mistakes somewhere and in any case seems very redundant. I can imagine some cases where having the DefaultValueAttribute automatically set to the default value (or any value) would be undesirable, but I think those would be the exception rather than the rule. And in those cases the solution would simply be to set the default value in the constructor rather than at declaration which I think is less burdensome than redundant code.

答:
MSDN says this about the DefaultValueAttribute

A DefaultValueAttribute will not cause a member to be automatically
  initialized with the attribute's value. You must set the initial value
  in your code.

This article suggests doing something like this to avoid repeated code

```<code>static public void ApplyDefaultValues(object self)
{
    foreach (PropertyDescriptor prop in TypeDescriptor.GetProperties(self)) {
        DefaultValueAttribute attr = prop.Attributes[typeof(DefaultValueAttribute)] as DefaultValueAttribute;
        if (attr == null) continue;
        prop.SetValue(self, attr.Value);
    }
}
</code>```

Body:
Is there anyway to implicitly carry out the following pattern?

    [DefaultValue(true)]
    public bool SomeBooleanProperty { get; set; } = true;

Repeating the default value in two locations just seems to be begging for mistakes somewhere and in any case seems very redundant. I can imagine some cases where having the DefaultValueAttribute automatically set to the default value (or any value) would be undesirable, but I think those would be the exception rather than the rule. And in those cases the solution would simply be to set the default value in the constructor rather than at declaration which I think is less burdensome than redundant code.

Body:
MSDN says this about the DefaultValueAttribute

A DefaultValueAttribute will not cause a member to be automatically
  initialized with the attribute's value. You must set the initial value
  in your code.

This article suggests doing something like this to avoid repeated code

static public void ApplyDefaultValues(object self)
{
    foreach (PropertyDescriptor prop in TypeDescriptor.GetProperties(self)) {
        DefaultValueAttribute attr = prop.Attributes[typeof(DefaultValueAttribute)] as DefaultValueAttribute;
        if (attr == null) continue;
        prop.SetValue(self, attr.Value);
    }
}


问:
Changing classes in javascript on click
I have this side bar with a bunch of  linked to the same page

I have this JS code, but the previous  link does not change back to tab-title and remains active

I would want it so that when the user clicks a link, the  would change from class="tab-title" to class="tab-title-active"

$(document).ready(function() {
  $('a').click(function() {
    $(this).removeClass('tab-title');
    $(this).addClass('tab-title-active');
    $(this).siblings().removeClass('tab-title-active');
    $(this).siblings().addClass('tab-title');
    console.log($(this).attr("class"));
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>a.tab-title{
    font-size: 18px;
    font-weight: 400;
    list-style: none;
    color: #444;
    margin-top: 10px;
}

a.tab-title-active{
    font-size: 18px;
    font-weight: bold;
    list-style: none;
    color: #0091e4;
    margin-top: 10px;
}</code>```

href="#tab-title-0" class="tab-title-active">Binary

href="#tab-title-1" class="tab-title">About

href="#tab-title-2" class="tab-title">Representation

Binary

About

Representation

```

答:
You need change  All a tag classname .tab-title-active to tab-title.Then add a class with this classname with .tab-title-active

Working snippet

$(document).ready(function() {
  $('a').click(function() {
    $('a').removeClass('tab-title-active').addClass('tab-title');
    $(this).addClass('tab-title-active');
    console.log($(this).attr('class'));
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>a.tab-title {
  font-size: 18px;
  font-weight: 400;
  list-style: none;
  color: #444;
  margin-top: 10px;
}

a.tab-title-active {
  font-size: 18px;
  font-weight: bold;
  list-style: none;
  color: #0091e4;
  margin-top: 10px;
}</code>```

Binary

About

Representation

Binary

About

Representation

```

Title: Changing classes in javascript on click

Body:
I have this side bar with a bunch of  linked to the same page

I have this JS code, but the previous  link does not change back to tab-title and remains active

I would want it so that when the user clicks a link, the  would change from class="tab-title" to class="tab-title-active"

$(document).ready(function() {
  $('a').click(function() {
    $(this).removeClass('tab-title');
    $(this).addClass('tab-title-active');
    $(this).siblings().removeClass('tab-title-active');
    $(this).siblings().addClass('tab-title');
    console.log($(this).attr("class"));
  });
});

a.tab-title{
    font-size: 18px;
    font-weight: 400;
    list-style: none;
    color: #444;
    margin-top: 10px;
}

a.tab-title-active{
    font-size: 18px;
    font-weight: bold;
    list-style: none;
    color: #0091e4;
    margin-top: 10px;
}

Binary

About

Representation

Binary

About

Representation

Body:
You need change  All a tag classname .tab-title-active to tab-title.Then add a class with this classname with .tab-title-active

Working snippet

$(document).ready(function() {
  $('a').click(function() {
    $('a').removeClass('tab-title-active').addClass('tab-title');
    $(this).addClass('tab-title-active');
    console.log($(this).attr('class'));
  });
});

a.tab-title {
  font-size: 18px;
  font-weight: 400;
  list-style: none;
  color: #444;
  margin-top: 10px;
}

a.tab-title-active {
  font-size: 18px;
  font-weight: bold;
  list-style: none;
  color: #0091e4;
  margin-top: 10px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<div class="sidebar" style="position: fixed;">
  <div class="tab">
    <h5><a href="#tab-title-0" class="tab-title-active">Binary</a></h5>
  </div>
  <div class="tab">
    <h5><a href="#tab-title-1" class="tab-title">About</a></h5>
  </div>
  <div class="tab">
    <h5><a href="#tab-title-2" class="tab-title">Representation</a></h5>
  </div>
</div>

<div class="content">
  <h1 class="tab-title" id="tab-title-0">Binary</h1>
  <p>
    <!-- stuff written -->
  </p>

  <h1 class="tab-title" id="tab-title-1">About</h1>
  <p>
    <!-- stuff written -->
  </p>

  <h1 class="tab-title" id="tab-title-2">Representation</h1>
  <p>
    <!-- stuff written -->
  </p>
</div>


问:
Invalid Memory Access when calling Delphi method via JNA
I am attempting to call the following Delphi method:

However, I get this exception:

Here is my code:

```<code>public static void main(String[] args) throws Exception {
    //解决中文乱码a
    System.setProperty("jna.encoding", "GBK");
    byte[] b = FileUtil.file2ByteArray("C:/Users/Administrator/Desktop/work/jyp/dll/钻孔检验批质量验收记录表.LIL");
    System.out.println(b);
    String nn = "llllllllllll";

    //System.out.println(testdll.Instance.PBF_RepToPDF_File("C:/Users/Administrator/Desktop/work/jyp/dll/1啊.LIL","C:/Users/Administrator/Desktop/work/jyp/dll/1_File.PDF" ));
    //JYP_TK_ReportDLL.Instance.PBF_RepToPDF_File("C:/Users/Administrator/Desktop/work/jyp/dll/1啊.LIL","C:/Users/Administrator/Desktop/work/jyp/dll/1_File.PDF" );
    JYP_TK_ReportDLL.Instance.PBF_RepToPDF_Stream("C:/Users/Administrator/Desktop/work/jyp/dll/1.PDF",nn);
    //JYP_TK_ReportDLL.Instance.PBF_RepToJPG_File("C:/Users/Administrator/Desktop/work/jyp/dll/1啊.LIL","C:/Users/Administrator/Desktop/work/jyp/dll/1_File.JPG" );
}

public interface JYP_TK_ReportDLL extends Library {
    JYP_TK_ReportDLL Instance = (JYP_TK_ReportDLL) Native.loadLibrary("JYP_TK_ReportDLL",
            JYP_TK_ReportDLL.class);

    boolean PBF_RepToPDF_Stream(String SaveFile, String arr);
    boolean PBF_RepToPDF_File(String SourceFile, String  SaveFile);
    boolean PBF_RepToJPG_File(String SourceFile, String  SaveFile);
}
</code>```

答:
It's not readily possible to call that method from a non Delphi module. The second parameter is a Delphi native dynamic array. You can't directly make one of those from your Java module.

Contact the vendor and request a library that is amenable to use from languages other than Delphi. That would require the dynamic array to be replaced by two arguments. The length of the array, and the address of the start of the array.

If that is not possible you will need to write an adapter module in Delphi.

Body:
I am attempting to call the following Delphi method:

However, I get this exception:

Here is my code:

public static void main(String[] args) throws Exception {
    //解决中文乱码a
    System.setProperty("jna.encoding", "GBK");
    byte[] b = FileUtil.file2ByteArray("C:/Users/Administrator/Desktop/work/jyp/dll/钻孔检验批质量验收记录表.LIL");
    System.out.println(b);
    String nn = "llllllllllll";

    //System.out.println(testdll.Instance.PBF_RepToPDF_File("C:/Users/Administrator/Desktop/work/jyp/dll/1啊.LIL","C:/Users/Administrator/Desktop/work/jyp/dll/1_File.PDF" ));
    //JYP_TK_ReportDLL.Instance.PBF_RepToPDF_File("C:/Users/Administrator/Desktop/work/jyp/dll/1啊.LIL","C:/Users/Administrator/Desktop/work/jyp/dll/1_File.PDF" );
    JYP_TK_ReportDLL.Instance.PBF_RepToPDF_Stream("C:/Users/Administrator/Desktop/work/jyp/dll/1.PDF",nn);
    //JYP_TK_ReportDLL.Instance.PBF_RepToJPG_File("C:/Users/Administrator/Desktop/work/jyp/dll/1啊.LIL","C:/Users/Administrator/Desktop/work/jyp/dll/1_File.JPG" );
}

public interface JYP_TK_ReportDLL extends Library {
    JYP_TK_ReportDLL Instance = (JYP_TK_ReportDLL) Native.loadLibrary("JYP_TK_ReportDLL",
            JYP_TK_ReportDLL.class);

    boolean PBF_RepToPDF_Stream(String SaveFile, String arr);
    boolean PBF_RepToPDF_File(String SourceFile, String  SaveFile);
    boolean PBF_RepToJPG_File(String SourceFile, String  SaveFile);
}


问:
Changing default font in Windows messes up my Win Forms buttons
We have a collection of C# (.NET 2.0) applications that have custom dialog windows. When the user changes the default font size and resolution etc in Windows the edges of the form lose controls (they get pushed off the visible portion of the form) typically dropping off buttons from the bottom. This is problematic for us and will cause issues across other applications using the standard look-and-feel framework we are creating around these applications.

How would you make your entire application independent from windows font changes? How would you integrate this into multiple solutions?

Or better still how can one adapt the entire application to be able to adjust itself with the Windows appearance changes?

答:
WinForms have the AutoScaleMode property, which can be set to either Font, DPI, Inherit, or None. The default is "Font" which, in my experience, doesn't always scale things right. You might try one of the other options (maybe "None" if you don't want your form to scale at all?)

As for making the entire application able to adjust itself, look into the "Inherit" option (you still need to set something other than "Inherit" on the parent or startup form of your application, though).

OwnerDisplayName: bdwakefield

LastEditorDisplayName: Matt Hamilton

OwnerDisplayName: Keithius


答:
Remove the class tab-title-active from all anchor tags then add it back on the current target

$(document).ready(function() {
  $('a').click(function() {
    // removing the class from element which have this class
    $('.tab-title-active').removeClass('tab-title-active');
    // adding it to the selected element
    $(this).addClass('tab-title-active')

  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.tab-title {
  color: green
}

.tab-title-active {
  color: red
}</code>```

Binary

About

Representation

Binary

About

Representation

```

Title: Changing classes in javascript on click

Body:
Remove the class tab-title-active from all anchor tags then add it back on the current target

$(document).ready(function() {
  $('a').click(function() {
    // removing the class from element which have this class
    $('.tab-title-active').removeClass('tab-title-active');
    // adding it to the selected element
    $(this).addClass('tab-title-active')

  });
});

.tab-title {
  color: green
}

.tab-title-active {
  color: red
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="sidebar" style="position: fixed;">
  <div class="tab">
    <h5><a href="#tab-title-0" class="tab-title tab-title-active">Binary</a></h5>
  </div>
  <div class="tab">
    <h5><a href="#tab-title-1" class="tab-title">About</a></h5>
  </div>
  <div class="tab">
    <h5><a href="#tab-title-2" class="tab-title">Representation</a></h5>
  </div>
</div>

<div class="content">
  <h1 class="tab-title" id="tab-title-0">Binary</h1>
  <p>
    <!-- stuff written -->
  </p>

  <h1 class="tab-title" id="tab-title-1">About</h1>
  <p>
    <!-- stuff written -->
  </p>

  <h1 class="tab-title" id="tab-title-2">Representation</h1>
  <p>
    <!-- stuff written -->
  </p>
</div>


问:
Get variable GET in Yii2 not working
Basiclly I have an url that have a parameter.

So, I need to access those parameter using GET. This is the GET that coming:

```<code>Array
   (
     [r] => hanwa/incoming-pipe/assign-incoming
     [1] => Array
            (
              [min_urut] => 1
              [max_urut] => 44
            )

     [_] => 1496645704980
    )
</code>```

In docs, docs,
We can use like this :

```<code> echo $request->get('min_urut');
</code>```

But, I got nothing. Please Advise.

答:
Judging by the fact that you have an array with the key [r] you have an associative array, method get() you will not get it, you need to do it just like this ..</p>

```<code>echo $request->get()[1]['min_urut'];
</code>```

Title: Get variable GET in Yii2 not working

Body:
Basiclly I have an url that have a parameter.

So, I need to access those parameter using GET. This is the GET that coming:

Array
   (
     [r] => hanwa/incoming-pipe/assign-incoming
     [1] => Array
            (
              [min_urut] => 1
              [max_urut] => 44
            )

     [_] => 1496645704980
    )

In docs, docs,
We can use like this :

 echo $request->get('min_urut');

But, I got nothing. Please Advise.

Body:
Judging by the fact that you have an array with the key [r] you have an associative array, method get() you will not get it, you need to do it just like this ..

echo $request->get()[1]['min_urut'];


问:
iOS Duration of Splash Screen (Default.png)
im using a Default.png file for my iPad-app. It appears correctly but i could'nt find a way to modify the duration of the splash screen. Has somebody any suggestions? Google has many sites that show how to setup the startscreen but could'nt find a solution for my problem.

答:
As @Conrad Shultz answered, splash screen should be used only via the supplied LaunchScreen.storyboard file by Xcode.

However, in rare situations you do want to prolong the splash screen:

Download A LOT of files before the app starts since the app depends on them.

Other reason...

This is the way to do it:

Inside AppDelegate, under didFinishLaunchingWithOptions you should:

Create a VC that has the same splash image and the same constraints

Present it

Dismiss it after a given time

The code:

```<code>let splashVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "splash")

    window?.makeKeyAndVisible()

    if let root = window?.rootViewController
    {
        root.present(splashVC, animated: false, completion: nil)
        let dispatchTime = DispatchTime.now() + 3

        // didFinishLaunchingWithOptions will return and this block will be executed afterwards, hence, async..
        DispatchQueue.main.asyncAfter(deadline: dispatchTime, execute: {
            root.presentedViewController?.dismiss(animated: false, completion: nil)
        })
    }
}
</code>```

Body:
As @Conrad Shultz answered, splash screen should be used only via the supplied LaunchScreen.storyboard file by Xcode.

However, in rare situations you do want to prolong the splash screen:

Download A LOT of files before the app starts since the app depends on them.

Other reason...

This is the way to do it:

Inside AppDelegate, under didFinishLaunchingWithOptions you should:

Create a VC that has the same splash image and the same constraints

Present it

Dismiss it after a given time

The code:

let splashVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "splash")

    window?.makeKeyAndVisible()

    if let root = window?.rootViewController
    {
        root.present(splashVC, animated: false, completion: nil)
        let dispatchTime = DispatchTime.now() + 3

        // didFinishLaunchingWithOptions will return and this block will be executed afterwards, hence, async..
        DispatchQueue.main.asyncAfter(deadline: dispatchTime, execute: {
            root.presentedViewController?.dismiss(animated: false, completion: nil)
        })
    }
}


问:
Use OpenCV to receive from Gstreamer
Mac:

```<code>cv::VideoCapture cap("tcpclientsrc host=129.31.224.100 port=8888 ! gdpdepay ! rtph264depay ! avdec_h264 ! "
                                 "videoconvert ! appsink");
    if (!cap.isOpened()) {
        printf("=ERR= can't create video capture\n");
        return -1;
    }
</code>```

RPi:

```<code>gst-launch-1.0 wrappercamerabinsrc ! video/x-raw,
framerate=30/1, width=1280, height=720, format=RGB !
videoconvert ! vtenc_h264 ! h264parse !
rtph264pay config-interval=1 pt=96 ! gdppay !
tcpserversink host=129.31.224.100 port=8888
</code>```

The error message is:

```<code>VIDEOIO(cvCreateFileCapture_AVFoundation (filename)): raised unknown C++ exception!

=ERR= can't create video capture
</code>```

The thing I want to achieve is to read frames from gstreamer by using OpenCV.

The above command works in command line, but not working in C++ code.

Thank you in advance!

答:
cap.open (const String &filename, int apiPreference) from here could be what you are looking for.

You would need CAP_GSTREAMER (from this list).

I would post this as a comment, but i dont have the reputation.

Title: Use OpenCV to receive from Gstreamer

Body:
Mac:

cv::VideoCapture cap("tcpclientsrc host=129.31.224.100 port=8888 ! gdpdepay ! rtph264depay ! avdec_h264 ! "
                                 "videoconvert ! appsink");
    if (!cap.isOpened()) {
        printf("=ERR= can't create video capture\n");
        return -1;
    }

RPi:

gst-launch-1.0 wrappercamerabinsrc ! video/x-raw,
framerate=30/1, width=1280, height=720, format=RGB !
videoconvert ! vtenc_h264 ! h264parse !
rtph264pay config-interval=1 pt=96 ! gdppay !
tcpserversink host=129.31.224.100 port=8888

The error message is:

VIDEOIO(cvCreateFileCapture_AVFoundation (filename)): raised unknown C++ exception!

=ERR= can't create video capture

The thing I want to achieve is to read frames from gstreamer by using OpenCV.

The above command works in command line, but not working in C++ code.

Thank you in advance!


问:
method in class can not be applied to given type
I made a class called that creates a constructer and a method.

```<code>public class Car
{
private double speed;
private String make;
private int year;

public Car(int year, String make, double speed) {
this.year = year;
this.make = make;
this.speed = speed;
}

public String getMake(){
  return make;
}
public double getSpeed(){
  return speed;
}
public int getYear(){
     return year;
}

  public void accelerate (double speed)
{
        speed = speed + 1.00;
}

}
</code>```

the only problem i am having here is that when I go to my driver class to try and run it, this is the error I'm receiving

```<code>public class CarTester
{
public static void main (String[] args){

Car p1 = new Car(2010, "toyota", 4.50);
Car.accelerate();
Car.accelerate();

}
}
</code>```

"error: method accelerate in class Car cannot be applied to given types"

why is that so? because it says "required: double" but the "speed" variable is a double?

答:
The method shouldn't require parameters

```<code>public void accelerate () {
    speed = speed + 1.00;
}
</code>```

and must be called from the instance p1

```<code>public static void main (String[] args){
    Car p1 = new Car(2010, "toyota", 4.50);
    p1.accelerate();
    p1.accelerate();
    System.out.println(p1.getSpeed());
}
</code>```

Body:
I made a class called that creates a constructer and a method.

public class Car
{
private double speed;
private String make;
private int year;

public Car(int year, String make, double speed) {
this.year = year;
this.make = make;
this.speed = speed;
}

public String getMake(){
  return make;
}
public double getSpeed(){
  return speed;
}
public int getYear(){
     return year;
}

  public void accelerate (double speed)
{
        speed = speed + 1.00;
}

}

the only problem i am having here is that when I go to my driver class to try and run it, this is the error I'm receiving

public class CarTester
{
public static void main (String[] args){

Car p1 = new Car(2010, "toyota", 4.50);
Car.accelerate();
Car.accelerate();

}
}

"error: method accelerate in class Car cannot be applied to given types"

why is that so? because it says "required: double" but the "speed" variable is a double?

Body:
The method shouldn't require parameters

public void accelerate () {
    speed = speed + 1.00;
}

and must be called from the instance p1

public static void main (String[] args){
    Car p1 = new Car(2010, "toyota", 4.50);
    p1.accelerate();
    p1.accelerate();
    System.out.println(p1.getSpeed());
}


问:
Codeigniter: Iinfinite scroll is not working with database
I am new to Codeigniter. I am applying infinite scrolling.
I am getting reference from Infinite scroll. I want to work it with database records. But it is not working.

Let me show Code:

In News Controller:

```<code>//Rendering view
    public function infiniteScroll() {
        $total_data = $this->news_model->get_all_count();
        $data['title'] = 'News List';

        $offset = 30;
        $all_content = $this->news_model->get_all_content(0,$offset);
        $data['news'] = $all_content;
        $data['content'] = "news/scrollNews";
        $this->load->view('templates/main', $data,FALSE);
    }

// Load More data on page scroll
    public function loadMore($page=1, $count = 30)
    {
        $offset = ($page - 1)*$count;
        $data['title'] = 'News List';
        $all_content = $this->news_model->get_all_content($count,$offset);

        $data['news'] = $all_content;
        $data['content'] = "news/scrollNews";
        $this->load->view('templates/main', $data,FALSE);
    }
</code>```

My view page:

```<code><div id="posts">
    <?php foreach ($news as $nw){ ?>
    <div class="post">
        <?= $nw->log_id ?>
    </div>
  <?php } ?>
</div>

<div id="pagination">
    <a href="loadMore" class="next">next</a>
</div>

<script>
var ias = jQuery.ias({
  container:  '#posts',
  item:       '.post',
  pagination: '#pagination',
  next:       '.next',
});
</script>
</code>```

Here my loadMore function is called on click but i can't get any parameter to set offset. I am new so i don't know how to get next records on click.

Also i need data to be loaded on scroll. Not in click.

Any help please.

答:
when we click on next button it's getting the URL from "anchor href attribute"

change

```<code><div id="pagination">
<a href="loadMore" class="next">next</a>
</code>```

to

```<code><div id="pagination">
            <a href="base_url/controller/action/$page" class="next-posts">next</a>
        </div>
</code>```

I am not sure, but I think it's working for you

Body:
I am new to Codeigniter. I am applying infinite scrolling.
I am getting reference from Infinite scroll. I want to work it with database records. But it is not working.

Let me show Code:

In News Controller:

//Rendering view
    public function infiniteScroll() {
        $total_data = $this->news_model->get_all_count();
        $data['title'] = 'News List';

        $offset = 30;
        $all_content = $this->news_model->get_all_content(0,$offset);
        $data['news'] = $all_content;
        $data['content'] = "news/scrollNews";
        $this->load->view('templates/main', $data,FALSE);
    }

// Load More data on page scroll
    public function loadMore($page=1, $count = 30)
    {
        $offset = ($page - 1)*$count;
        $data['title'] = 'News List';
        $all_content = $this->news_model->get_all_content($count,$offset);

        $data['news'] = $all_content;
        $data['content'] = "news/scrollNews";
        $this->load->view('templates/main', $data,FALSE);
    }

My view page:

    <?php foreach ($news as $nw){ ?>

        <?= $nw->log_id ?>

  <?php } ?>

    next

Here my loadMore function is called on click but i can't get any parameter to set offset. I am new so i don't know how to get next records on click.

Also i need data to be loaded on scroll. Not in click.

Any help please.

Body:
when we click on next button it's getting the URL from "anchor href attribute"

change

<div id="pagination">
<a href="loadMore" class="next">next</a>

to

<div id="pagination">
            <a href="base_url/controller/action/$page" class="next-posts">next</a>
        </div>

I am not sure, but I think it's working for you


问:
lodash multi-column sortBy
There's a nifty method to sort an array of objects based on several properties:

```<code>var data = _.sortBy(array_of_objects, ['type', 'name']);</code>```

However that is only for ascending sorting. Is there some handy way of defining direction per column? E.g.

```<code>var data = _.sortBy(array_of_objects, [{'type': 'asc'}, {'name': 'desc'}]);</code>```

答:
You can also try this:</p>

```<code>var data= _.reverse(_.sortBy(res.locals.subscriptionList.items, ['type', 'name']));
</code>```

ContentLicense: CC BY-SA 4.0

Title: lodash multi-column sortBy

Body:
There's a nifty method to sort an array of objects based on several properties:

var data = _.sortBy(array_of_objects, ['type', 'name']);

However that is only for ascending sorting. Is there some handy way of defining direction per column? E.g.

var data = _.sortBy(array_of_objects, [{'type': 'asc'}, {'name': 'desc'}]);

Body:
You can also try this:

var data= _.reverse(_.sortBy(res.locals.subscriptionList.items, ['type', 'name']));


问:
Tweak Focus Visual Properties at app level in UWP
I want to alter the focus visual properties at app level.(like the Mail App).
As per the Focus Visual Docucmentation, it is possible to change the primary and secondary border color at app level by changing the respective system brush resources.

There are only two color properties for the focus visuals: the primary
   border color, and the secondary border color. These focus visual
   border colors can be changed per-control on an page level, and
   globally on an app-wide level:

To brand focus visuals app-wide, override the system brushes:

```<code> <SolidColorBrush x:Key="SystemControlFocusVisualPrimaryBrush" Color="DarkRed"/>
 <SolidColorBrush x:Key="SystemControlFocusVisualSecondaryBrush" Color="Pink"/>
</code>```

But no such thing is provided in the doc for the thickness of the focus visual. Is there any resource available or any other way to specify the thickness at app level?

答:
Unfortunately there are no such resources for primary and secondary system focus visuals. But assuming you are using the default styles for your controls, you can try defining a base style and then have all the controls that you need a focus visual with inherit from it.

You can even define the colors and margin within the base style so this way you have one centralized place to manage all global focus styling.

```<code><Style x:Name="DefaultFrameworkElementStyle" TargetType="FrameworkElement">
    <Setter Property="FocusVisualPrimaryThickness" Value="4" />
    <Setter Property="FocusVisualSecondaryThickness" Value="2" />
    <Setter Property="FocusVisualPrimaryBrush" Value="DarkRed" />
    <Setter Property="FocusVisualSecondaryBrush" Value="Red" />
   <Setter Property="FocusVisualMargin" Value="2" />
</Style>

<Style TargetType="Button" BasedOn="{StaticResource DefaultFrameworkElementStyle}" />
<Style TargetType="ListViewItem" BasedOn="{StaticResource DefaultFrameworkElementStyle}" />
</code>```

Body:
I want to alter the focus visual properties at app level.(like the Mail App).
As per the Focus Visual Docucmentation, it is possible to change the primary and secondary border color at app level by changing the respective system brush resources.

There are only two color properties for the focus visuals: the primary
   border color, and the secondary border color. These focus visual
   border colors can be changed per-control on an page level, and
   globally on an app-wide level:

To brand focus visuals app-wide, override the system brushes:

 <SolidColorBrush x:Key="SystemControlFocusVisualPrimaryBrush" Color="DarkRed"/>
 <SolidColorBrush x:Key="SystemControlFocusVisualSecondaryBrush" Color="Pink"/>

But no such thing is provided in the doc for the thickness of the focus visual. Is there any resource available or any other way to specify the thickness at app level?

Body:
Unfortunately there are no such resources for primary and secondary system focus visuals. But assuming you are using the default styles for your controls, you can try defining a base style and then have all the controls that you need a focus visual with inherit from it.

You can even define the colors and margin within the base style so this way you have one centralized place to manage all global focus styling.

<Style x:Name="DefaultFrameworkElementStyle" TargetType="FrameworkElement">
    <Setter Property="FocusVisualPrimaryThickness" Value="4" />
    <Setter Property="FocusVisualSecondaryThickness" Value="2" />
    <Setter Property="FocusVisualPrimaryBrush" Value="DarkRed" />
    <Setter Property="FocusVisualSecondaryBrush" Value="Red" />
   <Setter Property="FocusVisualMargin" Value="2" />
</Style>

<Style TargetType="Button" BasedOn="{StaticResource DefaultFrameworkElementStyle}" />
<Style TargetType="ListViewItem" BasedOn="{StaticResource DefaultFrameworkElementStyle}" />