问:
Using Rails polymorphism for nested comments
I need to build a nested comments system in a Rails 3 application that allows for comments on many models (articles, posts, etc) and am debating rolling my own solution along the lines of this post.  There are gems available like acts_as_commentable_with_threading with awesome_nested_set, but they feel bloated for my needs.

I need to be able to add comments to multiple models

I need to be able to add comments to comments, infinitely deep

I need to be able to efficiently retrieve all descendants for a post, article, etc

I need to be able to efficiently present the comments in their appropriate nesting

My question is, were I to roll my own solution what potential hiccups I could face.  I want to avoid going down one path only to reach a dead end.  My initial concerns relate to efficiently querying for children.  Say, for instance, getting a list of an articles descendant comments (children and children of children).

Anyone have input on this?  Thanks.

答:
There are two kinds of nesting you can do: a tree and a nested set.

acts_as_tree stores only a parent_id and so it is really fast to write new entries, but you have to recursively walk the chain of id numbers to get a list of all the children. This is not a good choice when you need to do lots of reads.

awesome_nested_set records three bits of information: parent_id, lft and rgt. The left and right values are calculated so that they contain all the children ids for that entry. This is very fast for read operations but slower to write.

In your case I think awesome_nested_set is more appropriate. You might think it seems overkill, but nested sets get complicated in a hurry. You need to use the nested set pattern to efficiently query children.

You only need to use two methods to render the entire tree of comments: iterate over Comment.roots and for each comment, render comment.children.

```<code>class ModelController < ApplicationController
  def show
    @model = Model.find_by_id(params[:id])
    @comments = @model.comments.roots
  end
end

<ul id="comments">
<% @comments.each do |comment| %>
  <%= render :partial => 'comment', :object => comment %>
<% end %>
</ul>

<!-- _comment partial -->
<li class="comment">
  <!-- comment markup -->
  <% if comment.children.present? %>
  <ul>
    <%= render :partial => 'comment', :collection => comment.children %>
  </ul>
  <% end %>
</li>
</code>```

To save a nested comment, simply fill in the parent_id and awesome_nested_set will do the rest. I don't think rolling your own solution will be any more elegant than this.

Update: Looks like the awesome_nested_set hasn't been updated in some time. Check out ancestry instead. Does basically the same things.

Body:
There are two kinds of nesting you can do: a tree and a nested set.

acts_as_tree stores only a parent_id and so it is really fast to write new entries, but you have to recursively walk the chain of id numbers to get a list of all the children. This is not a good choice when you need to do lots of reads.

awesome_nested_set records three bits of information: parent_id, lft and rgt. The left and right values are calculated so that they contain all the children ids for that entry. This is very fast for read operations but slower to write.

In your case I think awesome_nested_set is more appropriate. You might think it seems overkill, but nested sets get complicated in a hurry. You need to use the nested set pattern to efficiently query children.

You only need to use two methods to render the entire tree of comments: iterate over Comment.roots and for each comment, render comment.children.

class ModelController < ApplicationController
  def show
    @model = Model.find_by_id(params[:id])
    @comments = @model.comments.roots
  end
end

<ul id="comments">
<% @comments.each do |comment| %>
  <%= render :partial => 'comment', :object => comment %>
<% end %>
</ul>

<!-- _comment partial -->
<li class="comment">
  <!-- comment markup -->
  <% if comment.children.present? %>
  <ul>
    <%= render :partial => 'comment', :collection => comment.children %>
  </ul>
  <% end %>
</li>

To save a nested comment, simply fill in the parent_id and awesome_nested_set will do the rest. I don't think rolling your own solution will be any more elegant than this.

Update: Looks like the awesome_nested_set hasn't been updated in some time. Check out ancestry instead. Does basically the same things.


来源: stackexchange

问:
Combine field_weights with ORDER by in Sphinx
I seem to have had my question answered on how to order results by relevance using OPTION field_weights. However I'm finding it does not work when using an ORDER by in the same SphinxQL Query e.g.

Select * from Items where MATCH('@(Listing_Title) London @(Listing_Title,Description) Jack') ORDER By Featured_Flag DESC OPTION field_weights=(Author=1000)

Which basically is trying to say:

"Find me all the books with 'Jack' and 'London', put all the books by featured sellers first and non-features sellers after, and in each group put the records where both 'Jack' and 'London' appear in the Listing_Title itself"

So a sample return should look like this where the field order is:

```<code>Listing_Title                Description                      Featured_Flag

Jack London Books for Sale   New buy now!                     1
London, Steinbeck and more   Call of the Wild by Jack London  1
Jack London Classics!        In great shape write or call     0
Call of Wild - London        THE Jack London                  0
</code>```

Once I add the ORDER by Featured_Flag DESC however the field_weights=(Listing_Title=1000) is no longer obeyed.

Is there some other way to do this? I've read that querying two indexes can act as a union perhaps a Listing_Title_Index and a All_Index would work?

答:
Well, the field_weights just modify the computed weight (giving extra weight to specific field(s). So need to ensure that WEIGHT() is still factored into your ORDER BY somehow.

If there is no ORDER BY (and there is a MATCH(...)) then sphinx will automatically order by WEIGHT(), but if supply a sort order, need to add it yourself

For example:

```<code>... ORDER By Featured_Flag DESC, WEIGHT() DESC
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I seem to have had my question answered on how to order results by relevance using OPTION field_weights. However I'm finding it does not work when using an ORDER by in the same SphinxQL Query e.g.

Select * from Items where MATCH('@(Listing_Title) London @(Listing_Title,Description) Jack') ORDER By Featured_Flag DESC OPTION field_weights=(Author=1000)

Which basically is trying to say:

"Find me all the books with 'Jack' and 'London', put all the books by featured sellers first and non-features sellers after, and in each group put the records where both 'Jack' and 'London' appear in the Listing_Title itself"

So a sample return should look like this where the field order is:

Listing_Title                Description                      Featured_Flag

Jack London Books for Sale   New buy now!                     1
London, Steinbeck and more   Call of the Wild by Jack London  1
Jack London Classics!        In great shape write or call     0
Call of Wild - London        THE Jack London                  0

Once I add the ORDER by Featured_Flag DESC however the field_weights=(Listing_Title=1000) is no longer obeyed.

Is there some other way to do this? I've read that querying two indexes can act as a union perhaps a Listing_Title_Index and a All_Index would work?

Body:
Well, the field_weights just modify the computed weight (giving extra weight to specific field(s). So need to ensure that WEIGHT() is still factored into your ORDER BY somehow.

If there is no ORDER BY (and there is a MATCH(...)) then sphinx will automatically order by WEIGHT(), but if supply a sort order, need to add it yourself

For example:

... ORDER By Featured_Flag DESC, WEIGHT() DESC


问:
How to search a string based key/value collection fast
Hello fellow stackoverflowers!

I have a word list of 200.000 string entries, average string length is around 30 characters. This list of words are the key and to each key i have a domain object. I would like to find the domain objects in this collection by only knowing a part of the key. I.E. the search string "kov" would for example match the key "stackoverflow".

Currently I am using a Ternary Search Tree (TST), which usually will find the items within 100 milliseconds. This is however too slow for my requirements. The TST implementation could be improved with some minor optimizations and I could try to balance the tree. But i figured that these things would not give me the 5x - 10x speed improvement I am aiming at. I am assuming that the reason for being so slow is that i basically have to visit most nodes in the tree.

Any ideas on how to improve the speed of the algorithm? Are there any other algorithms that I should be looking at?

Thanks in advance,
Oskar

答:
To query a large set of text in efficient manner you can use the concept of Edit Distance/ Prefix Edit Distance.

Edit Distance ED(x,y): minimal number of transfroms to get from x to y

But computing ED between each term and query text is resource and time consuming. Therefore instead of calculating ED for each term first we can extract possible matching terms using a technique called Qgram Index. and then apply ED calculation on those selected terms.

An advantage of Qgram index technique is it supports for Fuzzy Search.

One possible approach to adapt QGram index is build an Inverted Index using Qgrams. In there we store all the words which consists with particular Qgram(Instead of storing full string you can use unique ID for each string).

col : colmbia, colombo, gancola, tacolama

Then when querying, we calculate the number of common Qgrams between query text and available terms.

```<code>Example: x = HILLARY, y = HILARI(query term)
Qgrams
$$HILLARY$$ -> $$H, $HI, HIL, ILL, LLA, LAR, ARY, RY$, Y$$
$$HILARI$$ -> $$H, $HI, HIL, ILA, LAR, ARI, RI$, I$$
number of q-grams in common = 4
</code>```

For the terms with high number of common Qgrams, we calculate the ED/PED against the query term and then suggest the term to the end user.

you can find an implementation of this theory in following project. Feel free to ask any questions.
https://github.com/Bhashitha-Gamage/City_Search

To study more about Edit Distance, Prefix Edit Distance Qgram index please watch the following video of Prof. Dr Hannah Bast
https://www.youtube.com/embed/6pUg2wmGJRo (Lesson starts from 20:06)

OwnerDisplayName: Oskar

LastEditorDisplayName: Oskar

ContentLicense: CC BY-SA 2.5

Body:
To query a large set of text in efficient manner you can use the concept of Edit Distance/ Prefix Edit Distance.

Edit Distance ED(x,y): minimal number of transfroms to get from x to y

But computing ED between each term and query text is resource and time consuming. Therefore instead of calculating ED for each term first we can extract possible matching terms using a technique called Qgram Index. and then apply ED calculation on those selected terms.

An advantage of Qgram index technique is it supports for Fuzzy Search.

One possible approach to adapt QGram index is build an Inverted Index using Qgrams. In there we store all the words which consists with particular Qgram(Instead of storing full string you can use unique ID for each string).

col : colmbia, colombo, gancola, tacolama

Then when querying, we calculate the number of common Qgrams between query text and available terms.

Example: x = HILLARY, y = HILARI(query term)
Qgrams
$$HILLARY$$ -> $$H, $HI, HIL, ILL, LLA, LAR, ARY, RY$, Y$$
$$HILARI$$ -> $$H, $HI, HIL, ILA, LAR, ARI, RI$, I$$
number of q-grams in common = 4

For the terms with high number of common Qgrams, we calculate the ED/PED against the query term and then suggest the term to the end user.

you can find an implementation of this theory in following project. Feel free to ask any questions.
https://github.com/Bhashitha-Gamage/City_Search

To study more about Edit Distance, Prefix Edit Distance Qgram index please watch the following video of Prof. Dr Hannah Bast
https://www.youtube.com/embed/6pUg2wmGJRo (Lesson starts from 20:06)


问:
TestBench license and Jenkins on AWS
I've setup several headless UI tests using Vaadin TestBench but Jenkins fails due to licensing when running:

```<code>License for Vaadin TestBench 4 not found. Go to vaadin.com/pro for more details.
</code>```

The Vaadin documentation states to put the license file in the home directory, specifically stating /Users/<home> but that isn't a valid location for a RHEL EC2 instance.

I have tried placing my license file in /home/<user> and /home/<user>/ and even tried creating the /Users/ directory in case it is hardcoded to only check that location.

I've tried modifying the Jenkins Maven job to add the following into MAVEN_OPTS:

```<code>-Dvaadin.testbench.developer.license=<LICENSE>
</code>```

So far it always fails to find my license when running the test jobs.

What is the correct way to add licenses that Jenkins can access running on an AWS EC2 instance?

答:
You need to set the license as a java property, I guess in jenkens it's done in another way.
System properties management</p>

Title: TestBench license and Jenkins on AWS

Body:
I've setup several headless UI tests using Vaadin TestBench but Jenkins fails due to licensing when running:

License for Vaadin TestBench 4 not found. Go to vaadin.com/pro for more details.

The Vaadin documentation states to put the license file in the home directory, specifically stating /Users/<home> but that isn't a valid location for a RHEL EC2 instance.

I have tried placing my license file in /home/<user> and /home/<user>/ and even tried creating the /Users/ directory in case it is hardcoded to only check that location.

I've tried modifying the Jenkins Maven job to add the following into MAVEN_OPTS:

-Dvaadin.testbench.developer.license=<LICENSE>

So far it always fails to find my license when running the test jobs.

What is the correct way to add licenses that Jenkins can access running on an AWS EC2 instance?


问:
multiple dex files define landroid/support/annotation/AnimRes
The moment I added the android support annotations to my dependencies

compile 'com.android.support:support-annotations:20.0.0'

I got this error:

Error Code:
      2   Output:
      UNEXPECTED TOP-LEVEL EXCEPTION:
      com.android.dex.DexException: Multiple dex files define Landroid/support/annotation/AnimRes;
          at com.android.dx.merge.DexMerger.readSortableTypes(DexMerger.java:594)
          at com.android.dx.merge.DexMerger.getSortedTypes(DexMerger.java:552)
          at com.android.dx.merge.DexMerger.mergeClassDefs(DexMerger.java:533)
          at com.android.dx.merge.DexMerger.mergeDexes(DexMerger.java:170)
          at com.android.dx.merge.DexMerger.merge(DexMerger.java:188)
          at com.android.dx.command.dexer.Main.mergeLibraryDexBuffers(Main.java:439)
          at com.android.dx.command.dexer.Main.runMonoDex(Main.java:287)
          at com.android.dx.command.dexer.Main.run(Main.java:230)
          at com.android.dx.command.dexer.Main.main(Main.java:199)
          at com.android.dx.command.Main.main(Main.java:103)

build.gradle

```<code>android {
    compileSdkVersion 19
    buildToolsVersion '20.0.0'

    defaultConfig {
        minSdkVersion 10
        targetSdkVersion 19
    }
}

dependencies {
    compile 'com.android.support:support-v4:19.0.0'
    compile 'com.crashlytics.android:crashlytics:1.+'
    compile 'com.android.support:support-annotations:20.0.0'
}
</code>```

Anybody else experienced this issue? I have tried the solutions from here.

答:
From /platforms/android/libs/
delete android-support-v4.jar.
It works for me.</p>

Body:
The moment I added the android support annotations to my dependencies

compile 'com.android.support:support-annotations:20.0.0'

I got this error:

Error Code:
      2   Output:
      UNEXPECTED TOP-LEVEL EXCEPTION:
      com.android.dex.DexException: Multiple dex files define Landroid/support/annotation/AnimRes;
          at com.android.dx.merge.DexMerger.readSortableTypes(DexMerger.java:594)
          at com.android.dx.merge.DexMerger.getSortedTypes(DexMerger.java:552)
          at com.android.dx.merge.DexMerger.mergeClassDefs(DexMerger.java:533)
          at com.android.dx.merge.DexMerger.mergeDexes(DexMerger.java:170)
          at com.android.dx.merge.DexMerger.merge(DexMerger.java:188)
          at com.android.dx.command.dexer.Main.mergeLibraryDexBuffers(Main.java:439)
          at com.android.dx.command.dexer.Main.runMonoDex(Main.java:287)
          at com.android.dx.command.dexer.Main.run(Main.java:230)
          at com.android.dx.command.dexer.Main.main(Main.java:199)
          at com.android.dx.command.Main.main(Main.java:103)

build.gradle

android {
    compileSdkVersion 19
    buildToolsVersion '20.0.0'

    defaultConfig {
        minSdkVersion 10
        targetSdkVersion 19
    }
}

dependencies {
    compile 'com.android.support:support-v4:19.0.0'
    compile 'com.crashlytics.android:crashlytics:1.+'
    compile 'com.android.support:support-annotations:20.0.0'
}

Anybody else experienced this issue? I have tried the solutions from here.


问:
Angular Google OAuth redirect not working with html5mode enabled
I am working on project in which we are using Google OAuth API to signup and login users to ower application.

The project is based on angularjs and asp.net.

The login process works fine when html5mode is not enabled, but for SEO reasons we are required to remove the hash (#) from the url using :

```<code>$locationProvider.html5Mode(true);
</code>```

in this case the response received after the authentication is always in the form

```<code>http://site/#access_token=...
</code>```

and for the route configuration in angular we are using

```<code>$routeProvider.when('/access_token=:accessToken', {
      templateUrl: '/app/identification/identification.html',
      controller: 'identificationGoogle'
});
</code>```

the problem is when html5 mode is enabled, after the redirection is done, the associated controller is never activated even if the browser window url is in the previous form.

it does not work until you refresh the page.

so is there any solution to this problem to avoid the need to reload the page.

the angular version used is : 1.3.15.

答:
I found the solution.

the solution was by adding the base tag which is required for angular when using html5 mode

```<code><base href="/">
</code>```

and changing the redirect_uri in the key configuration on Google's Developer Console to

```<code>http://site/
</code>```

instead of

```<code>http://site/index.cshtml
</code>```

the problem happened because the redirect url was not the same as the base url.

so when the redirect is done to the old url, this later didnt match the base url and so angular's routing didnt work.
in this case the browser is automatically redirected to

```<code>http://site/#access_token=...
</code>```

so after the page is reloaded explicitly, the base url and the loaded url are a match in this case, so the routing works fine.

Body:
I am working on project in which we are using Google OAuth API to signup and login users to ower application.

The project is based on angularjs and asp.net.

The login process works fine when html5mode is not enabled, but for SEO reasons we are required to remove the hash (#) from the url using :

$locationProvider.html5Mode(true);

in this case the response received after the authentication is always in the form

http://site/#access_token=...

and for the route configuration in angular we are using

$routeProvider.when('/access_token=:accessToken', {
      templateUrl: '/app/identification/identification.html',
      controller: 'identificationGoogle'
});

the problem is when html5 mode is enabled, after the redirection is done, the associated controller is never activated even if the browser window url is in the previous form.

it does not work until you refresh the page.

so is there any solution to this problem to avoid the need to reload the page.

the angular version used is : 1.3.15.

Body:
I found the solution.

the solution was by adding the base tag which is required for angular when using html5 mode

<base href="/">

and changing the redirect_uri in the key configuration on Google's Developer Console to

http://site/

instead of

http://site/index.cshtml

the problem happened because the redirect url was not the same as the base url.

so when the redirect is done to the old url, this later didnt match the base url and so angular's routing didnt work.
in this case the browser is automatically redirected to

http://site/#access_token=...

so after the page is reloaded explicitly, the base url and the loaded url are a match in this case, so the routing works fine.


问:
Issue with background color and Google Chrome
Sometimes I get a broken background in Chrome. I do not get this error with any other browser.

This is the simple CSS line responsible for the background color of body:

```<code>body
{
   background: black;
   color: white;
   font-family: Chaparral Pro, lucida grande, verdana, sans-serif;
}
</code>```

This is exactly how I get this problem. I click a link included in an Gmail's email and I get something wrong (no background). I then refresh the page and the background is colored completely.

How do fix this problem?

答:
Everybody has said your code is fine, and you know it works on other browsers without problems. So it's time to drop the science and just try stuff :)

Try putting the background color IN the body tag itself instead of/as-well-as in the CSS. Maybe insist again (redudantly) in Javascript. At some point, Chrome will have to place the background as you want it every time. Might be a timing-interpreting issue...

[Should any of this work, of course, you can toggle it on the server-side so the funny code only shows up in Chrome. And in a few months, when Chrome has changed and the problem disappears... well, worry about that later.]

OwnerDisplayName: Sergio del Amo

Body:
Sometimes I get a broken background in Chrome. I do not get this error with any other browser.

This is the simple CSS line responsible for the background color of body:

body
{
   background: black;
   color: white;
   font-family: Chaparral Pro, lucida grande, verdana, sans-serif;
}

This is exactly how I get this problem. I click a link included in an Gmail's email and I get something wrong (no background). I then refresh the page and the background is colored completely.

How do fix this problem?

OwnerDisplayName: Daniel Rosenstark


问:
Is it possible to have @OneToOne relation between 2 objects but not having the child automatically persisted in Hibernate
I'm using jpa persistance annotations. I have 2 objects, Order(parent) and Transaction(child). I want to be able to fetch my oder and get its transaction. The problem is I don't want my transaction to be automatically saved when I save my order. I need to do some special processing on it before I save it.

Is there a way to tell hybernate not to persist the child object but still fetch it when I retreive the order?

I tried something like this

```<code>@OneToOne(cascade=CascadeType.REFRESH)
@JoinColumn(name = "commande_id", insertable=false, updatable=false)
</code>```

This didn't work. I keep getting this message:

object references an unsaved transient instance - save the transient instance before flushing

When I try to save the order object. The first time I save the order the transaction object contains some data but its not ready to be saved yet.

Thanks in advance

答:
What if you detach the Transaction from the Session?

```<code>session.evict(transaction);
</code>```

Not sure if that will work but just an idea.

Body:
I'm using jpa persistance annotations. I have 2 objects, Order(parent) and Transaction(child). I want to be able to fetch my oder and get its transaction. The problem is I don't want my transaction to be automatically saved when I save my order. I need to do some special processing on it before I save it.

Is there a way to tell hybernate not to persist the child object but still fetch it when I retreive the order?

I tried something like this

@OneToOne(cascade=CascadeType.REFRESH)
@JoinColumn(name = "commande_id", insertable=false, updatable=false)

This didn't work. I keep getting this message:

object references an unsaved transient instance - save the transient instance before flushing

When I try to save the order object. The first time I save the order the transaction object contains some data but its not ready to be saved yet.

Thanks in advance

Body:
What if you detach the Transaction from the Session?

session.evict(transaction);

Not sure if that will work but just an idea.


问:
Stop JavaScript Timer from another Function
I have the following Javascript code

```<code> function scrollOpenTimed() {
            var openTimer = setTimeout(function(){ scrollOpen(); }, 3000);
        }

function a() {
      var _ouibounce = ouibounce(document.getElementById('modal'), {
        aggressive: true,
        timer: 0,
        callback: function() {
        console.log('ouibounce fired!');
        // cancel the openTimer
        }
      });
}
</code>```

At the moment I have scrollOpen being triggered after 3 seconds.

I want to cancel the timer and stop scrollOpen function being triggered When the callback function in function a() / ouibounce() function is triggered.

Any ideas how to do this appreciated.

Thanks

答:
You need to declare a publicly accessible variable to hold the instance of your timer.:

<button onClick="startTimer();">Start Timer</button>

<button onClick="stopTimer();">Stop Timer</button>```

Body:
I have the following Javascript code

 function scrollOpenTimed() {
            var openTimer = setTimeout(function(){ scrollOpen(); }, 3000);
        }

function a() {
      var _ouibounce = ouibounce(document.getElementById('modal'), {
        aggressive: true,
        timer: 0,
        callback: function() {
        console.log('ouibounce fired!');
        // cancel the openTimer
        }
      });
}

At the moment I have scrollOpen being triggered after 3 seconds.

I want to cancel the timer and stop scrollOpen function being triggered When the callback function in function a() / ouibounce() function is triggered.

Any ideas how to do this appreciated.

Thanks

Body:
You need to declare a publicly accessible variable to hold the instance of your timer.:

<script>
 var openTimer = null;
 function startTimer() {
    if(openTimer == null)
    {
      openTimer = setTimeout(function(){console.log("I'll beprinted after 10 seconds") }, 10000);
     }
}

function stopTimer(){
  clearTimeout(openTimer);
  openTimer = null;
}
</script>

<button onClick="startTimer();">Start Timer</button>
<br/>
<button onClick="stopTimer();">Stop Timer</button>


问:
Why do I get "TypeError: not all arguments converted during string formatting" trying to format a tuple?
I want to use %-style string formatting to print a tuple:

```<code>tup = (1,2,3)
print("this is a tuple: %s." % (tup))
</code>```

I expect it to print like This is a tuple: (1,2,3)., but instead I get an error that says TypeError: not all arguments converted during string formatting.

What is wrong, and how do I fix it?

In editing this question for clarity and modernization, I preserved one interesting aspect of the original example: the parentheses around tup. These are not necessary for the % syntax, and also do not create a tuple. It's possible that OP understood that the tuple wrapping (described in the answers here) was necessary, but simply got it wrong. For more information on that issue, see How to create a "singleton" tuple with only one element.

答:
The right way to do it is:

```<code>>>> thetuple = (1, 2, 3)
>>> print("this is a tuple: %s" % (thetuple,))
this is a tuple: (1, 2, 3)
</code>```

The % string operator is still supported in Python 3.x, and makes it easier to format a tuple (or list) as separate values. Using .format for this case will require some additional work - either the values need to be passed as separate arguments, or the sequence will need to be indexed:

```<code>>>> tup = (1,2,3)
>>> print("First: %d, Second: %d, Third: %d" % tup)
First: 1, Second: 2, Third: 3
>>> print('First: {}, Second: {}, Third: {}'.format(1,2,3))
First: 1, Second: 2, Third: 3
>>> print('First: {0[0]}, Second: {0[1]}, Third: {0[2]}'.format(tup))
First: 1, Second: 2, Third: 3
</code>```

The % operator is also useful for validating the type of the arguments, using different formatting codes (%s, %d, %i), while .format() only supports two conversion flags: '!s' and '!r'.

ContentLicense: CC BY-SA 4.0

Body:
I want to use %-style string formatting to print a tuple:

tup = (1,2,3)
print("this is a tuple: %s." % (tup))

I expect it to print like This is a tuple: (1,2,3)., but instead I get an error that says TypeError: not all arguments converted during string formatting.

What is wrong, and how do I fix it?

In editing this question for clarity and modernization, I preserved one interesting aspect of the original example: the parentheses around tup. These are not necessary for the % syntax, and also do not create a tuple. It's possible that OP understood that the tuple wrapping (described in the answers here) was necessary, but simply got it wrong. For more information on that issue, see How to create a "singleton" tuple with only one element.

Body:
The right way to do it is:

>>> thetuple = (1, 2, 3)
>>> print("this is a tuple: %s" % (thetuple,))
this is a tuple: (1, 2, 3)

The % string operator is still supported in Python 3.x, and makes it easier to format a tuple (or list) as separate values. Using .format for this case will require some additional work - either the values need to be passed as separate arguments, or the sequence will need to be indexed:

>>> tup = (1,2,3)
>>> print("First: %d, Second: %d, Third: %d" % tup)
First: 1, Second: 2, Third: 3
>>> print('First: {}, Second: {}, Third: {}'.format(1,2,3))
First: 1, Second: 2, Third: 3
>>> print('First: {0[0]}, Second: {0[1]}, Third: {0[2]}'.format(tup))
First: 1, Second: 2, Third: 3

The % operator is also useful for validating the type of the arguments, using different formatting codes (%s, %d, %i), while .format() only supports two conversion flags: '!s' and '!r'.


问:
How to prevent user to enter specific key using Javascript
I have a text field and I want to allow only alphabet. So I write the below Javascript method to prevent other keys. Unfortunately my text field is allowing uparrow(^).
Can any one tell me how to restrict uparrow(^) ?

```<code>function onlyAlphabet(evt) {
    var theEvent = evt || window.event;
    var key = theEvent.keyCode || theEvent.which;

    var keychar = String.fromCharCode(key);
    var keycheck = /[a-zA-z\s]/;

    if (!(key == 8 || key == 27 || key == 46 || key == 9 || key == 39)) // backspace delete  escape arrows
    {
        if (!keycheck.test(keychar)) {
            theEvent.returnValue = false;//for IE
            if (theEvent.preventDefault)
                theEvent.preventDefault();//Firefox
        }
    }
}
</code>```

html code

```<code><div class="form-group">
   <label class="form-text">Travels Name</label>
   <h:inputText value="#{bean.travelName}" maxlength="50" onkeypress="return onlyAlphabet(event)" />
</div>
</code>```

答:
The most elegant way (not supported in Safari) is to use the pattern attribute of the input element.

```<code><input pattern="[A-Za-z\s\^]+" type="text" />
</code>```

Read more here

For the `javascript` approach, codes for arrow keys are:

    {
      left_arrow   : 37,
      up_arrow     : 38,
      right_arrow  : 39,
      down_arrow  : 40
    }

In your if condition you have to eliminate 38 and 40.

Oh, you mean the ^ itself? :)))

It is enough to update your regular expression:

```<code>var keycheck = /[a-zA-z\s\^]/;
</code>```

Body:
I have a text field and I want to allow only alphabet. So I write the below Javascript method to prevent other keys. Unfortunately my text field is allowing uparrow(^).
Can any one tell me how to restrict uparrow(^) ?

function onlyAlphabet(evt) {
    var theEvent = evt || window.event;
    var key = theEvent.keyCode || theEvent.which;

    var keychar = String.fromCharCode(key);
    var keycheck = /[a-zA-z\s]/;

    if (!(key == 8 || key == 27 || key == 46 || key == 9 || key == 39)) // backspace delete  escape arrows
    {
        if (!keycheck.test(keychar)) {
            theEvent.returnValue = false;//for IE
            if (theEvent.preventDefault)
                theEvent.preventDefault();//Firefox
        }
    }
}

html code

   Travels Name
   <h:inputText value="#{bean.travelName}" maxlength="50" onkeypress="return onlyAlphabet(event)" />

Body:
The most elegant way (not supported in Safari) is to use the pattern attribute of the input element.

<input pattern="[A-Za-z\s\^]+" type="text" />

Read more here

For the `javascript` approach, codes for arrow keys are:

    {
      left_arrow   : 37,
      up_arrow     : 38,
      right_arrow  : 39,
      down_arrow  : 40
    }

In your if condition you have to eliminate 38 and 40.

Oh, you mean the ^ itself? :)))

It is enough to update your regular expression:

var keycheck = /[a-zA-z\s\^]/;


答:
```<code>var openTimer = null;

 function scrollOpenTimed() {
     openTimer = setTimeout(function(){ scrollOpen(); }, 3000);
 }

function a() {
      var _ouibounce = ouibounce(document.getElementById('modal'), {
        aggressive: true,
        timer: 0,
        callback: function() {
        console.log('ouibounce fired!');
            if(openTimer ){
               clearTimeout(openTimer );
            }

        }
      });
}
</code>```

Title: Stop JavaScript Timer from another Function


问:
How to solve fixing div at certain position by using jquery?
I am facing problem in fixing a div at certain position, I have to fix the div at certain position at right side, the middle part must be scrollable, but after logged in when I go to profile page, at first time the div is not fixed but when I refreshed the profile page it is fixed.

This is my jQuery code:

```<code>$(document).ready(function() {
    function profileInfo() {
        var element = $('.follow-scroll');
        var originalY = element.offset().top;
        var topMargin = 0;
        element.css('position', 'relative');
        $(window).on('scroll', function (event) {
            var scrollTop = $(window).scrollTop();
            element.stop(false, false).animate(
            {
                top: scrollTop < originalY ? 0 : scrollTop - originalY + topMargin
            }, 0);
        });
    }
})
</code>```

Html code:

```<code>  <div class="col-xs-12 col-sm-12 col-lg-2 ord-3 npd visible-lg">
            <div class="pfasdfxd follow-scroll">
                <div class="prfsdbg">
                    <div class="prfasdr text-center">
                        <img src="/images/Latte-image.png">
                    </div>
                    <div class="ntfsnt">Don't be basic</div>
                    <p class="prsntxt">
                        Upgrade to premium today!<br>
                        Starting at just $15
                    </p>
                    <div class="text-center">
                        <a href="#" type="button" class="ntfbtn btsm">View plans</a>
                    </div>
                </div>
            </div>
        </div>
</code>```

答:
If you are required to using jQuery I should do this to fix the div at a certain location (in this case fixed to the right side and Y in top is the number of pixels you want from top)

```<code>function profileInfo() {
    $('.follow-scroll').css({position: 'fixed', right: 0, top: "Ypx"});
}
</code>```

If you always should have it fixed to a certain location I should have done this in CSS instead.

```<code>.follow-scroll {position:fixed, right:0; top: Ypx;}
</code>```

Body:
I am facing problem in fixing a div at certain position, I have to fix the div at certain position at right side, the middle part must be scrollable, but after logged in when I go to profile page, at first time the div is not fixed but when I refreshed the profile page it is fixed.

This is my jQuery code:

$(document).ready(function() {
    function profileInfo() {
        var element = $('.follow-scroll');
        var originalY = element.offset().top;
        var topMargin = 0;
        element.css('position', 'relative');
        $(window).on('scroll', function (event) {
            var scrollTop = $(window).scrollTop();
            element.stop(false, false).animate(
            {
                top: scrollTop < originalY ? 0 : scrollTop - originalY + topMargin
            }, 0);
        });
    }
})

Html code:

Don't be basic

                        Upgrade to premium today!

                        Starting at just $15

                        View plans

Body:
If you are required to using jQuery I should do this to fix the div at a certain location (in this case fixed to the right side and Y in top is the number of pixels you want from top)

function profileInfo() {
    $('.follow-scroll').css({position: 'fixed', right: 0, top: "Ypx"});
}

If you always should have it fixed to a certain location I should have done this in CSS instead.

.follow-scroll {position:fixed, right:0; top: Ypx;}


问:
how to get sum of integer value from recyclerview
i am want to implement something like invoice. i am using recyclerview in fragment. and textview. i have some item in recyclerview. which content title,unit and price. now i want to get sum of all item's price in my textview which is in fragment. here is image what i want to achive.

here is image for understanding

here is my code for adapter class

```<code>public class Checkout_fragment2_confermation_Adapter extends RecyclerView.Adapter<Checkout_fragment2_confermation_Adapter.ViewHolder>  {

static List<Cart_datamodel> data;
static Context context;

public Checkout_fragment2_confermation_Adapter(Context context , List<Cart_datamodel> data1) {
    data = new ArrayList<Cart_datamodel>();
    this.context = context;
    this.data = data1;
}

@Override
public Checkout_fragment2_confermation_Adapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    final View itemLayoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.checkout_fragmet2confermation_listviwe_single_row, null);
    itemLayoutView.setLayoutParams(new RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.WRAP_CONTENT));
    Checkout_fragment2_confermation_Adapter.ViewHolder viewHolder = new Checkout_fragment2_confermation_Adapter.ViewHolder(itemLayoutView);

    return viewHolder;
}

@Override
public void onBindViewHolder(Checkout_fragment2_confermation_Adapter.ViewHolder holder, int position) {

    holder.title.setText(data.get(position).getTitle());
    holder.price.setText(data.get(position).getPrice());
    holder.product_img.setImageBitmap(getImage(data.get(position).getImg()));

}

@Override
public int getItemCount() {
    return data.size();
}

public class ViewHolder extends RecyclerView.ViewHolder {
    public TextView  title,price;
    public ImageView img,product_img;

    public ViewHolder(View itemView) {
        super(itemView);
        title = (TextView)itemView.findViewById(R.id.title_checkout_fgment2);
        price =(TextView)itemView.findViewById(R.id.price_checkout_fragment2);
        product_img =(ImageView)itemView.findViewById(R.id.image_checkout_fragment2);
    }
}
public static Bitmap getImage(byte[] image) {
    return BitmapFactory.decodeByteArray(image, 0, image.length);
}

}
</code>```

here is my fragment class

```<code>public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.fragmenttab2, container, false);

    dataBaseAdapter = new AddressDataBaseAdapter(getContext());
    cart_adapter = new Item_adding_cart(getContext());
    dbList = cart_adapter.getDataFromDB();

   // listview = (ListView)view.findViewById(R.id.listview);

    recyclerView =(RecyclerView)view.findViewById(R.id.my_recycler_view_checkout_fgrment2);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
    recycleradapter = new Checkout_fragment2_confermation_Adapter(getContext(),dbList);
    recyclerView.setAdapter(recycleradapter);

    fname =(TextView)view.findViewById(R.id.firstname_conformation);
    lname =(TextView)view.findViewById(R.id.lastname_conformation);
    mobile =(TextView)view.findViewById(R.id.mobile_conformaton);
    address =(TextView)view.findViewById(R.id.address_conformation);
    zipcode =(TextView)view.findViewById(R.id.zipcode_conformation);
    city =(TextView)view.findViewById(R.id.city_conformation);

    addresslist= new ArrayList<Address_Activity_DataModel>();
    addresslist=dataBaseAdapter.getDataFromDB();

    int count = dataBaseAdapter.getrowcount();
    if(count==0){

    }
    else
    {
        showRecords();
    }

   // loaddata();

    return view;

}
</code>```

答:
Please try following show your total count view only if last element</p>

```<code>  int total=0;
    @Override
    public void onBindViewHolder(Checkout_fragment2_confermation_Adapter.ViewHolder holder, int position) {

        holder.title.setText(data.get(position).getTitle());
        holder.price.setText(data.get(position).getPrice());
        holder.product_img.setImageBitmap(getImage(data.get(position).getImg()));
    total+=data.get(position).getPrice();

    if(position==data.size()-1){//check if list last element
    //show your total count view here---- and add total amount
    }

}
</code>```

Body:
i am want to implement something like invoice. i am using recyclerview in fragment. and textview. i have some item in recyclerview. which content title,unit and price. now i want to get sum of all item's price in my textview which is in fragment. here is image what i want to achive.

here is image for understanding

here is my code for adapter class

public class Checkout_fragment2_confermation_Adapter extends RecyclerView.Adapter<Checkout_fragment2_confermation_Adapter.ViewHolder>  {

static List<Cart_datamodel> data;
static Context context;

public Checkout_fragment2_confermation_Adapter(Context context , List<Cart_datamodel> data1) {
    data = new ArrayList<Cart_datamodel>();
    this.context = context;
    this.data = data1;
}

@Override
public Checkout_fragment2_confermation_Adapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    final View itemLayoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.checkout_fragmet2confermation_listviwe_single_row, null);
    itemLayoutView.setLayoutParams(new RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.WRAP_CONTENT));
    Checkout_fragment2_confermation_Adapter.ViewHolder viewHolder = new Checkout_fragment2_confermation_Adapter.ViewHolder(itemLayoutView);

    return viewHolder;
}

@Override
public void onBindViewHolder(Checkout_fragment2_confermation_Adapter.ViewHolder holder, int position) {

    holder.title.setText(data.get(position).getTitle());
    holder.price.setText(data.get(position).getPrice());
    holder.product_img.setImageBitmap(getImage(data.get(position).getImg()));

}

@Override
public int getItemCount() {
    return data.size();
}

public class ViewHolder extends RecyclerView.ViewHolder {
    public TextView  title,price;
    public ImageView img,product_img;

    public ViewHolder(View itemView) {
        super(itemView);
        title = (TextView)itemView.findViewById(R.id.title_checkout_fgment2);
        price =(TextView)itemView.findViewById(R.id.price_checkout_fragment2);
        product_img =(ImageView)itemView.findViewById(R.id.image_checkout_fragment2);
    }
}
public static Bitmap getImage(byte[] image) {
    return BitmapFactory.decodeByteArray(image, 0, image.length);
}

}

here is my fragment class

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.fragmenttab2, container, false);

    dataBaseAdapter = new AddressDataBaseAdapter(getContext());
    cart_adapter = new Item_adding_cart(getContext());
    dbList = cart_adapter.getDataFromDB();

   // listview = (ListView)view.findViewById(R.id.listview);

    recyclerView =(RecyclerView)view.findViewById(R.id.my_recycler_view_checkout_fgrment2);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
    recycleradapter = new Checkout_fragment2_confermation_Adapter(getContext(),dbList);
    recyclerView.setAdapter(recycleradapter);

    fname =(TextView)view.findViewById(R.id.firstname_conformation);
    lname =(TextView)view.findViewById(R.id.lastname_conformation);
    mobile =(TextView)view.findViewById(R.id.mobile_conformaton);
    address =(TextView)view.findViewById(R.id.address_conformation);
    zipcode =(TextView)view.findViewById(R.id.zipcode_conformation);
    city =(TextView)view.findViewById(R.id.city_conformation);

    addresslist= new ArrayList<Address_Activity_DataModel>();
    addresslist=dataBaseAdapter.getDataFromDB();

    int count = dataBaseAdapter.getrowcount();
    if(count==0){

    }
    else
    {
        showRecords();
    }

   // loaddata();

    return view;

}

Body:
Please try following show your total count view only if last element

  int total=0;
    @Override
    public void onBindViewHolder(Checkout_fragment2_confermation_Adapter.ViewHolder holder, int position) {

        holder.title.setText(data.get(position).getTitle());
        holder.price.setText(data.get(position).getPrice());
        holder.product_img.setImageBitmap(getImage(data.get(position).getImg()));
    total+=data.get(position).getPrice();

    if(position==data.size()-1){//check if list last element
    //show your total count view here---- and add total amount
    }

}


问:
jQuery, converting from a .POST to .AJAX with a method?
I have the following:

```<code>    $.post(this.href, { _method: 'delete' }, null, "script");
</code>```

How can I convert that to a:

```<code>$.ajax({
    type: "POST",
    url: ,
    data: ,
    beforeSend: function() {
    },
    success: function() {
</code>```

I'm not use how to deal with URL or how to add the _method: 'delete' where does that go with .ajax?

thanks

答:
The URL is going to remain the same, and the _method:'delete' is going to go into the data section:</p>

```<code>$.ajax({
    type: "POST",
    url: this.href,
    data: { _method: 'delete' },
    beforeSend: function() {},
    success: function() {},
    dataType: 'script'
    });
</code>```

Body:
I have the following:

    $.post(this.href, { _method: 'delete' }, null, "script");

How can I convert that to a:

$.ajax({
    type: "POST",
    url: ,
    data: ,
    beforeSend: function() {
    },
    success: function() {

I'm not use how to deal with URL or how to add the _method: 'delete' where does that go with .ajax?

thanks

Body:
The URL is going to remain the same, and the _method:'delete' is going to go into the data section:

$.ajax({
    type: "POST",
    url: this.href,
    data: { _method: 'delete' },
    beforeSend: function() {},
    success: function() {},
    dataType: 'script'
    });


问:
Label disappear when table is reloaded / scrolled
I have a UITableview with two UILabels like in the chat. When the visible UITableview is filled and when I add extra cells, my UILabels get disappeared.

There are may other UILabels which is visible. Only those 2 chat UILabels is hidden. Can anyone suggest me the possible solution?

```<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
ChatScreenViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ChatCell" forIndexPath:indexPath];
index = indexPath.row + 1;
indexx = indexPath;

cell.ChatLabel1.layer.cornerRadius = 8;
cell.ChatLabel1.layer.masksToBounds = YES;
cell.ChatLabel2.layer.cornerRadius = 8;
cell.ChatLabel2.layer.masksToBounds = YES;

cell.ImageviewLabel1.layer.cornerRadius = 20;
cell.ImageviewLabel1.layer.masksToBounds = YES;
cell.ImageviewLabel2.layer.cornerRadius = 20;
cell.ImageviewLabel2.layer.masksToBounds = YES;
cell.ImageviewLabel2.backgroundColor = [UIColor greenColor];

if([Replychat[indexPath.row] valueForKey:@"bot"] != NULL)
{

    cell.ChatLabel1.text = [Replychat[indexPath.row] valueForKey:@"bot"];
    cell.ChatLabel2.hidden = YES;
    cell.ImageviewLabel2.hidden = YES;

    cell.TimeLabel1.text = TimeArray[indexPath.row];
}
else
{

    cell.ChatLabel2.text = [Replychat[indexPath.row] valueForKey:@"User"];
    cell.ChatLabel1.hidden = YES;
    cell.ImageviewLabel1.hidden = YES;
    cell.TimeLabel2.text = TimeArray[indexPath.row];
}

return cell;
</code>```

}

答:
Try this way

(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{

ChatScreenViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ChatCell" forIndexPath:indexPath];

if (cell == nil) {

```<code>cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                               reuseIdentifier:@"ChatCell"];
</code>```

}

index = indexPath.row + 1;

indexx = indexPath;

cell.ChatLabel1.layer.cornerRadius = 8;

cell.ChatLabel1.layer.masksToBounds = YES;

cell.ChatLabel2.layer.cornerRadius = 8;

cell.ChatLabel2.layer.masksToBounds = YES;

cell.ImageviewLabel1.layer.cornerRadius = 20;

cell.ImageviewLabel1.layer.masksToBounds = YES;

cell.ImageviewLabel2.layer.cornerRadius = 20;

cell.ImageviewLabel2.layer.masksToBounds = YES;

cell.ImageviewLabel2.backgroundColor = [UIColor greenColor];

if([Replychat[indexPath.row] valueForKey:@"bot"] != NULL)
{

cell.ChatLabel1.hidden = NO;

cell.ChatLabel1.text = [Replychat[indexPath.row] valueForKey:@"bot"];

cell.ChatLabel2.hidden = YES;

cell.ImageviewLabel2.hidden = YES;

cell.TimeLabel1.text = TimeArray[indexPath.row];

}

else{

cell.ChatLabel2.hidden = NO;

cell.ChatLabel2.text = [Replychat[indexPath.row] valueForKey:@"User"];

cell.ChatLabel1.hidden = YES;

cell.ImageviewLabel1.hidden = YES;

cell.TimeLabel2.text = TimeArray[indexPath.row];

}

return cell;

}

Body:
I have a UITableview with two UILabels like in the chat. When the visible UITableview is filled and when I add extra cells, my UILabels get disappeared.

There are may other UILabels which is visible. Only those 2 chat UILabels is hidden. Can anyone suggest me the possible solution?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
ChatScreenViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ChatCell" forIndexPath:indexPath];
index = indexPath.row + 1;
indexx = indexPath;

cell.ChatLabel1.layer.cornerRadius = 8;
cell.ChatLabel1.layer.masksToBounds = YES;
cell.ChatLabel2.layer.cornerRadius = 8;
cell.ChatLabel2.layer.masksToBounds = YES;

cell.ImageviewLabel1.layer.cornerRadius = 20;
cell.ImageviewLabel1.layer.masksToBounds = YES;
cell.ImageviewLabel2.layer.cornerRadius = 20;
cell.ImageviewLabel2.layer.masksToBounds = YES;
cell.ImageviewLabel2.backgroundColor = [UIColor greenColor];

if([Replychat[indexPath.row] valueForKey:@"bot"] != NULL)
{

    cell.ChatLabel1.text = [Replychat[indexPath.row] valueForKey:@"bot"];
    cell.ChatLabel2.hidden = YES;
    cell.ImageviewLabel2.hidden = YES;

    cell.TimeLabel1.text = TimeArray[indexPath.row];
}
else
{

    cell.ChatLabel2.text = [Replychat[indexPath.row] valueForKey:@"User"];
    cell.ChatLabel1.hidden = YES;
    cell.ImageviewLabel1.hidden = YES;
    cell.TimeLabel2.text = TimeArray[indexPath.row];
}

return cell;

}

Body:
Try this way

(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{

ChatScreenViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ChatCell" forIndexPath:indexPath];

if (cell == nil) {

cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                               reuseIdentifier:@"ChatCell"];

}

index = indexPath.row + 1;

indexx = indexPath;

cell.ChatLabel1.layer.cornerRadius = 8;

cell.ChatLabel1.layer.masksToBounds = YES;

cell.ChatLabel2.layer.cornerRadius = 8;

cell.ChatLabel2.layer.masksToBounds = YES;

cell.ImageviewLabel1.layer.cornerRadius = 20;

cell.ImageviewLabel1.layer.masksToBounds = YES;

cell.ImageviewLabel2.layer.cornerRadius = 20;

cell.ImageviewLabel2.layer.masksToBounds = YES;

cell.ImageviewLabel2.backgroundColor = [UIColor greenColor];

if([Replychat[indexPath.row] valueForKey:@"bot"] != NULL)
{

cell.ChatLabel1.hidden = NO;

cell.ChatLabel1.text = [Replychat[indexPath.row] valueForKey:@"bot"];

cell.ChatLabel2.hidden = YES;

cell.ImageviewLabel2.hidden = YES;

cell.TimeLabel1.text = TimeArray[indexPath.row];

}

else{

cell.ChatLabel2.hidden = NO;

cell.ChatLabel2.text = [Replychat[indexPath.row] valueForKey:@"User"];

cell.ChatLabel1.hidden = YES;

cell.ImageviewLabel1.hidden = YES;

cell.TimeLabel2.text = TimeArray[indexPath.row];

}

return cell;

}


问:
why multiple files not post: laravel 5.4
In my project i want to post some information with multiple images.. All the data has been posted except Files data ..i got only text input values not file value so help me out what i am doing wrong why the images can't be posted??

<form action="{{url('/createAlbum')}}" method="post" enctype="multipart/form-data">
 {{  csrf_field() }}

       <input type="text" class="form-control" name="title" id="title" placeholder="Untitle Album" required>

        <input type="text" class="form-control" name="albumLocation" id="album-loc" placeholder="Where were these taken?" required>

      <input type="file" name="album[]" id="filer_input2" multiple="multiple" value="test">

   <button type="submit" class="btn btn-primary btn-block">Create</button>

</form>```
</div>
</div>
</p>

<p><strong>Controller method:</strong></p>

``` public function createalbum(Request $request){
 dd($request->all());

}
```

Find JS files:

Custom-Filer.js

Jquery.filer.min.js

答:
Files can be accessed like this:

$request->allFiles();

To get a single file:

$request->file('key');

Body:
In my project i want to post some information with multiple images.. All the data has been posted except Files data ..i got only text input values not file value so help me out what i am doing wrong why the images can't be posted??

<form action="{{url('/createAlbum')}}" method="post" enctype="multipart/form-data">
 {{  csrf_field() }}

       <input type="text" class="form-control" name="title" id="title" placeholder="Untitle Album" required>

        <input type="text" class="form-control" name="albumLocation" id="album-loc" placeholder="Where were these taken?" required>

      <input type="file" name="album[]" id="filer_input2" multiple="multiple" value="test">

   <button type="submit" class="btn btn-primary btn-block">Create</button>

</form>

Controller method:

 public function createalbum(Request $request){
 dd($request->all());

}

Find JS files:

Custom-Filer.js

Jquery.filer.min.js


问:
Informix SP not returning mapped beans with MyBatis
We have an Informix Stored Procedure that works perfectly, goes to the database and returns us some registers with various values.

The problem comes when we want to use this SP on MyBatis. We have a test case where we are calling a method that invokes the stored procedure with a mapper, and when we execute it, it seems that it did his job (the list's size is 5, the same number of registers the SP on the database returns) but all of the registers are nulls.

We think that the mapper is not mapping the values to the bean, so the registers are null. But we are not sure.

We are calling the store procedure like this

```<code>      <select id="requestAllCoberturasPlan"
      parameterType="RequestCoberturasPlanEvent"
      statementType="CALLABLE">

{
    #{lstCoberturasPlan, jdbcType=CURSOR, mode=OUT, resultMap=requestAllCoberturasPlanResultMap, javaType=java.sql.ResultSet} =
    call sp_plan_cobervida
    (
        #{cveLinea, jdbcType = SMALLINT, mode = IN},
        #{cveProd, jdbcType = SMALLINT, mode = IN},
        #{cvePlan, jdbcType = SMALLINT, mode = IN},
        #{idSolicitud, jdbcType = SMALLINT, mode = IN}
    )
}
    </select>
</code>```

Does anybody face a problem like that? Please, we need all the help we can.

答:
When you're using Informix Stored Procedures it's important to name return parameters.

See https://www.ibm.com/support/knowledgecenter/SSGU8G_11.50.0/com.ibm.udr.doc/ids_udr_096.htm

```<code>The syntax for the CREATE PROCEDURE/FUNCTION statement is:
RETURNS/RETURNING data_type AS return_param_name [{, data_type AS
return_param_name}]
</code>```

Body:
We have an Informix Stored Procedure that works perfectly, goes to the database and returns us some registers with various values.

The problem comes when we want to use this SP on MyBatis. We have a test case where we are calling a method that invokes the stored procedure with a mapper, and when we execute it, it seems that it did his job (the list's size is 5, the same number of registers the SP on the database returns) but all of the registers are nulls.

We think that the mapper is not mapping the values to the bean, so the registers are null. But we are not sure.

We are calling the store procedure like this

      <select id="requestAllCoberturasPlan"
      parameterType="RequestCoberturasPlanEvent"
      statementType="CALLABLE">

{
    #{lstCoberturasPlan, jdbcType=CURSOR, mode=OUT, resultMap=requestAllCoberturasPlanResultMap, javaType=java.sql.ResultSet} =
    call sp_plan_cobervida
    (
        #{cveLinea, jdbcType = SMALLINT, mode = IN},
        #{cveProd, jdbcType = SMALLINT, mode = IN},
        #{cvePlan, jdbcType = SMALLINT, mode = IN},
        #{idSolicitud, jdbcType = SMALLINT, mode = IN}
    )
}
    </select>

Does anybody face a problem like that? Please, we need all the help we can.

Body:
When you're using Informix Stored Procedures it's important to name return parameters.

See https://www.ibm.com/support/knowledgecenter/SSGU8G_11.50.0/com.ibm.udr.doc/ids_udr_096.htm

The syntax for the CREATE PROCEDURE/FUNCTION statement is:
RETURNS/RETURNING data_type AS return_param_name [{, data_type AS
return_param_name}]


问:
Why doesn't the value change in Java
I just thought of this question: Using Java

```<code>int x = 1
int y = x;
x = 5;
</code>```

why doesn't y = 5 now?

答:
Take out two pieces of paper.

Write "x" on one, and "y" on the other.

Now write "1" on the paper you labelled "x". (int x = 1;)

Then take the number you see on the "x" paper and write that same number on the "y" paper. (int y = x;)

Then erase the number on the "x" paper and write "5" there instead. (x = 5;)

Observe that the number on the paper you labelled "y" did not change.

Variables work exactly like that.

Title: Why doesn't the value change in Java

Body:
I just thought of this question: Using Java

int x = 1
int y = x;
x = 5;

why doesn't y = 5 now?


问:
cannot load html file when using angularjs with webpack
I'm webpack beginner.

I want to build angular project with webpack but when I set route with angular-ui-router ( like '/home' ), 'home' page was empty. Nothing loaded.

I use 'raw-loader' of webpack to load html files but didn't work ..

Please give me little help. I feel desperate :(

project repo

答: I guess you are missing <ui-view><ui-view> in you index.html


问:
Developing A Simple Game without using Game Engines?
I am trying to develop a simple soccer game including penalty kicks in which i have to animate a ball from player to the goal post...earlier i have been using simple animations using a timer to add to the axis of ball image so that it moves from 1 point to another..but i did not have the desired result as animations were not that smooth...So i was thinking of using a Game Engine...Since i am a New Programmer i have no idea about game engine and neither can i find any proper documentation regarding engines like box2d or chipmunks or sparrow..i was also thinking of using UIView animations instead of the earlier animations as i think that can achieve far better animations without scratching my head trying to work on a game engine....I am going no where with this so it would be really great if someone can put some light on this issue of mine???

答:
Use UIView animations, like in:

```<code>[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.3]; // or whatever time
object.center=CGPointMake(object.center.x+2, object.center.y+4);
// or whatever
[UIView commitAnimations];
</code>```

You should also use an NSTimer with the same interval so that you can call animations smoothly.

```<code>NSTimer *timer=[NSTimer scheduledTimerWithTimeInterval:0.3 target: self
selector:@selector(animation) userInfo: nil repeats: YES];
</code>```

Then, implement the method:

```<code>- (void)animation {
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.3]; // or whatever time
    object.center=CGPointMake(object.center.x+5, object.center.y+7);
    // or whatever
    [UIView commitAnimations];
}
</code>```

This should do for ANY simple game.

Body:
Use UIView animations, like in:

[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.3]; // or whatever time
object.center=CGPointMake(object.center.x+2, object.center.y+4);
// or whatever
[UIView commitAnimations];

You should also use an NSTimer with the same interval so that you can call animations smoothly.

NSTimer *timer=[NSTimer scheduledTimerWithTimeInterval:0.3 target: self
selector:@selector(animation) userInfo: nil repeats: YES];

Then, implement the method:

- (void)animation {
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.3]; // or whatever time
    object.center=CGPointMake(object.center.x+5, object.center.y+7);
    // or whatever
    [UIView commitAnimations];
}

This should do for ANY simple game.


答:
Using jQuery, simple & elegant :</p>

```<code>jQuery('#id').on('keypress', limitChars);

function limitChars(e){
     return event.charCode >= 97 && event.charCode <= 122;
}
</code>```

Title: How to prevent user to enter specific key using Javascript

Body:
Using jQuery, simple & elegant :

jQuery('#id').on('keypress', limitChars);

function limitChars(e){
     return event.charCode >= 97 && event.charCode <= 122;
}


问:
Module build failed: ReferenceError: Unknown plugin "import" specified in "base" at 0
I'm working on a ReactJS project, and I'm using create-react-app and suddenly I got the following error and I don't know why. Before getting the error I remember I used "yarn add react-rte" , then I realized I didn't need it so I ran "yarn remove react-rte" . After that my project wouldn't work and I get the following error every time I start my project: Error in ./src/index.js
Module build failed: ReferenceError: Unknown plugin "import" specified in "base" at 0, attempted to resolve relative to "projectFolder/src"
    at Array.map (native)
 @ multi main

Package.json

```<code>{
"name": "client",
  "version": "0.1.0",
  "private": true,
  "devDependencies": {
    "autoprefixer": "6.7.2",
    "babel-core": "6.22.1",
    "babel-eslint": "7.1.1",
    "babel-jest": "18.0.0",
    "babel-loader": "6.2.10",
    "babel-preset-react-app": "^2.1.0",
    "case-sensitive-paths-webpack-plugin": "1.1.4",
    "chalk": "1.1.3",
    "connect-history-api-fallback": "1.3.0",
    "cross-spawn": "4.0.2",
    "css-loader": "0.26.1",
    "detect-port": "1.0.1",
    "dotenv": "2.0.0",
    "eslint": "3.8.1",
    "eslint-config-react-app": "^0.5.1",
    "eslint-loader": "1.6.0",
    "eslint-plugin-flowtype": "2.21.0",
    "eslint-plugin-import": "2.0.1",
    "eslint-plugin-jsx-a11y": "2.2.3",
    "eslint-plugin-react": "6.4.1",
    "extract-text-webpack-plugin": "1.0.1",
    "file-loader": "0.10.0",
    "fs-extra": "0.30.0",
    "html-webpack-plugin": "2.24.0",
    "http-proxy-middleware": "0.17.3",
    "jest": "18.1.0",
    "json-loader": "0.5.4",
    "node-sass": "^3.13.0",
    "object-assign": "4.1.1",
    "postcss-loader": "1.2.2",
    "promise": "7.1.1",
    "react-dev-utils": "^0.5.0",
    "sass-loader": "^4.0.2",
    "style-loader": "0.13.1",
    "url-loader": "0.5.7",
    "webpack": "1.14.0",
    "webpack-dev-server": "1.16.2",
    "webpack-manifest-plugin": "1.1.0",
    "whatwg-fetch": "2.0.2"
  },
  "dependencies": {
    "antd": "^2.5.0",
    "axios": "^0.15.2",
    "moment-timezone": "^0.5.10",
    "react": "^15.4.2",
    "react-dom": "^15.4.2",
    "react-intl": "2.2.3",
    "react-redux": "^4.4.6",
    "react-router": "^3.0.0",
    "redux": "^3.6.0",
    "redux-form": "^6.5.0",
    "redux-thunk": "^2.1.0"
  },
  "scripts": {
    "start": "node scripts/start.js",
    "build": "node scripts/build.js",
    "test": "node scripts/test.js --env=jsdom"
  },
  "jest": {
    "moduleFileExtensions": [
      "jsx",
      "js",
      "json"
    ],
    "moduleNameMapper": {
      "^.+\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/config/jest/FileStub.js",
      "^.+\\.css$": "<rootDir>/config/jest/CSSStub.js"
    },
    "setupFiles": [
      "<rootDir>/config/polyfills.js"
    ],
    "testPathIgnorePatterns": [
      "<rootDir>/(build|docs|node_modules)/"
    ],
    "testEnvironment": "node"
  },
  "babel": {
    "presets": [
      "react-app"
    ]
  },
  "eslintConfig": {
    "extends": "react-app"
  }
}
</code>```

Any help would be greatly appreciated.
Thank you.

答:
See: https://ant.design/docs/react/use-with-create-react-app

And please make sure that you had installed babel-plugin-import.

To install the plugin:

```<code>npm install babel-plugin-import --save-dev
</code>```

or:

```<code>yarn add babel-plugin-import --dev
</code>```

Body:
I'm working on a ReactJS project, and I'm using create-react-app and suddenly I got the following error and I don't know why. Before getting the error I remember I used "yarn add react-rte" , then I realized I didn't need it so I ran "yarn remove react-rte" . After that my project wouldn't work and I get the following error every time I start my project: Error in ./src/index.js
Module build failed: ReferenceError: Unknown plugin "import" specified in "base" at 0, attempted to resolve relative to "projectFolder/src"
    at Array.map (native)
 @ multi main

Package.json

{
"name": "client",
  "version": "0.1.0",
  "private": true,
  "devDependencies": {
    "autoprefixer": "6.7.2",
    "babel-core": "6.22.1",
    "babel-eslint": "7.1.1",
    "babel-jest": "18.0.0",
    "babel-loader": "6.2.10",
    "babel-preset-react-app": "^2.1.0",
    "case-sensitive-paths-webpack-plugin": "1.1.4",
    "chalk": "1.1.3",
    "connect-history-api-fallback": "1.3.0",
    "cross-spawn": "4.0.2",
    "css-loader": "0.26.1",
    "detect-port": "1.0.1",
    "dotenv": "2.0.0",
    "eslint": "3.8.1",
    "eslint-config-react-app": "^0.5.1",
    "eslint-loader": "1.6.0",
    "eslint-plugin-flowtype": "2.21.0",
    "eslint-plugin-import": "2.0.1",
    "eslint-plugin-jsx-a11y": "2.2.3",
    "eslint-plugin-react": "6.4.1",
    "extract-text-webpack-plugin": "1.0.1",
    "file-loader": "0.10.0",
    "fs-extra": "0.30.0",
    "html-webpack-plugin": "2.24.0",
    "http-proxy-middleware": "0.17.3",
    "jest": "18.1.0",
    "json-loader": "0.5.4",
    "node-sass": "^3.13.0",
    "object-assign": "4.1.1",
    "postcss-loader": "1.2.2",
    "promise": "7.1.1",
    "react-dev-utils": "^0.5.0",
    "sass-loader": "^4.0.2",
    "style-loader": "0.13.1",
    "url-loader": "0.5.7",
    "webpack": "1.14.0",
    "webpack-dev-server": "1.16.2",
    "webpack-manifest-plugin": "1.1.0",
    "whatwg-fetch": "2.0.2"
  },
  "dependencies": {
    "antd": "^2.5.0",
    "axios": "^0.15.2",
    "moment-timezone": "^0.5.10",
    "react": "^15.4.2",
    "react-dom": "^15.4.2",
    "react-intl": "2.2.3",
    "react-redux": "^4.4.6",
    "react-router": "^3.0.0",
    "redux": "^3.6.0",
    "redux-form": "^6.5.0",
    "redux-thunk": "^2.1.0"
  },
  "scripts": {
    "start": "node scripts/start.js",
    "build": "node scripts/build.js",
    "test": "node scripts/test.js --env=jsdom"
  },
  "jest": {
    "moduleFileExtensions": [
      "jsx",
      "js",
      "json"
    ],
    "moduleNameMapper": {
      "^.+\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/config/jest/FileStub.js",
      "^.+\\.css$": "<rootDir>/config/jest/CSSStub.js"
    },
    "setupFiles": [
      "<rootDir>/config/polyfills.js"
    ],
    "testPathIgnorePatterns": [
      "<rootDir>/(build|docs|node_modules)/"
    ],
    "testEnvironment": "node"
  },
  "babel": {
    "presets": [
      "react-app"
    ]
  },
  "eslintConfig": {
    "extends": "react-app"
  }
}

Any help would be greatly appreciated.
Thank you.

Body:
See: https://ant.design/docs/react/use-with-create-react-app

And please make sure that you had installed babel-plugin-import.

To install the plugin:

npm install babel-plugin-import --save-dev

or:

yarn add babel-plugin-import --dev


问:
Laravel only retrieve Model Records if they belong to authenticated user
I'm using Laravel 5.4 and have a Model called Order.
To test things I've created two users and two Orders, each user having one Order.

I've just seen that I'm able to retrieve the order of someone who is not my current user. I'm retrieving a list of user's own orders using Auth::user()->orders. But in order to show the details of a specific order I do this:

```<code>/**
 * Display the specified resource.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function show($id)
{
    $order = CustomerOrder::findOrFail($id)->with('products')->get();
    return view('order.show')
        ->with('order', $order);
}
</code>```

What am I missing out here? Is there a middleware or something to tell the application to only allow access to orders associated with the authenticated user?

Edit: So I've tried to do it using a Policy OrderPolicy (CRUD).

The view() fucntion of the Policy:

```<code>/**
 * Determine whether the user can view the customerOrder.
 *
 * @param  \App\User  $user
 * @param  \App\CustomerOrder  $customerOrder
 * @return mixed
 */
public function view(User $user, CustomerOrder $customerOrder)
{
    return $user->id === $customerOrder->user_id;
}
</code>```

And I've registered it in the AuthServiceProvider.php:

```<code>protected $policies = [
    'App\Model' => 'App\Policies\ModelPolicy',
    Adress::class => AdressPolicy::class, //Doesn't work either
    Order::class => OrderPolicy::class
];
</code>```

I can still check the Order for another user.

答:
If you want to get orders which belong to authenticated user, do this:</p>

```<code>CustomerOrder::where('user_id', auth()->user()->id)->with('products')->find($id);
</code>```

Body:
I'm using Laravel 5.4 and have a Model called Order.
To test things I've created two users and two Orders, each user having one Order.

I've just seen that I'm able to retrieve the order of someone who is not my current user. I'm retrieving a list of user's own orders using Auth::user()->orders. But in order to show the details of a specific order I do this:

/**
 * Display the specified resource.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function show($id)
{
    $order = CustomerOrder::findOrFail($id)->with('products')->get();
    return view('order.show')
        ->with('order', $order);
}

What am I missing out here? Is there a middleware or something to tell the application to only allow access to orders associated with the authenticated user?

Edit: So I've tried to do it using a Policy OrderPolicy (CRUD).

The view() fucntion of the Policy:

/**
 * Determine whether the user can view the customerOrder.
 *
 * @param  \App\User  $user
 * @param  \App\CustomerOrder  $customerOrder
 * @return mixed
 */
public function view(User $user, CustomerOrder $customerOrder)
{
    return $user->id === $customerOrder->user_id;
}

And I've registered it in the AuthServiceProvider.php:

protected $policies = [
    'App\Model' => 'App\Policies\ModelPolicy',
    Adress::class => AdressPolicy::class, //Doesn't work either
    Order::class => OrderPolicy::class
];

I can still check the Order for another user.

Body:
If you want to get orders which belong to authenticated user, do this:

CustomerOrder::where('user_id', auth()->user()->id)->with('products')->find($id);


问:
When to return vector iterator instead of vector?
Let's say we have a function 1 :

```<code>vector<T>::iterator GetSomething()
{
 vector<T> vec;

 // Update vec with something...

 return vec.begin();
}
</code>```

And another function 2:

```<code>vector<T> GetSomething()
{
 vector<T> vec;

 // Update vec with something...

 return vec;
}
</code>```

In what situations would we prefer function 1 ?
Also, what would be the lifetime of that vector object ?
How would we know if the iterator is pointing to empty vector ? Probably need to pass pair of iterators to determine begin / end.

答:
You shouldn't return iterator to locally allocated vector. It is an undefined behavior.

The explanation is pretty simple: vector<T> vec; is destroyed once you leave the function.

The second option is better and most probably will have Return Value Optimization that will construct vector exactly where it should be returned.

Body:
Let's say we have a function 1 :

vector<T>::iterator GetSomething()
{
 vector<T> vec;

 // Update vec with something...

 return vec.begin();
}

And another function 2:

vector<T> GetSomething()
{
 vector<T> vec;

 // Update vec with something...

 return vec;
}

In what situations would we prefer function 1 ?
Also, what would be the lifetime of that vector object ?
How would we know if the iterator is pointing to empty vector ? Probably need to pass pair of iterators to determine begin / end.


问:
How to convert uint8_t[][] to char[] in cpp
I have to convert the number generated by uint8_t[][] to simple char[]. How can I convert uint8_t[][] number to char key[]. I have convert number to char and want to store to the database.

```<code>static const uint8_t blake2s_kat[BLAKE2_KAT_LENGTH][BLAKE2_KAT_LENGTH] =
{
{
    0x69, 0x21, 0x7A, 0x30, 0x79, 0x90, 0x80, 0x94,
    0xE1, 0x11, 0x21, 0xD0, 0x42, 0x35, 0x4A, 0x7C,
    0x1F, 0x55, 0xB6, 0x48, 0x2C, 0xA1, 0xA5, 0x1E,
    0x1B, 0x25, 0x0D, 0xFD, 0x1E, 0xD0, 0xEE, 0xF9
},
{
    0xE3, 0x4D, 0x74, 0xDB, 0xAF, 0x4F, 0xF4, 0xC6,
    0xAB, 0xD8, 0x71, 0xCC, 0x22, 0x04, 0x51, 0xD2,
    0xEA, 0x26, 0x48, 0x84, 0x6C, 0x77, 0x57, 0xFB,
    0xAA, 0xC8, 0x2F, 0xE5, 0x1A, 0xD6, 0x4B, 0xEA
},....};
</code>```

e.g.

```<code>  somenumber = blake2s_kat;
 char key[100] = some function to convert into char(somenumber);
</code>```

答:
What you ask is problematic, since two-dimensional array is not one-dimensional array.

If a cell is like a room

then a one-dimensional array is like a hallway populated with rooms

and a two-dimensional array is like a building populated with hallways

you can't just take a building and convert it into a hallway.

what you can do is to cast each sub-array of uint8_t[] to char*:

```<code>auto pointer = reinterpret_cast<char*>(blake2s_kat[SOME_INDEX]);
</code>```

blake2s_kat[SOME_INDEX] decayes into uint8_t* which than can be casted to char*.

also, each sub array in your example seems to contain only 8x4 numbers, which is not 100. make sure that you consider the size of your arrays.

another possibility is to use memcpy:

```<code>char buffer[8x4];
memcpy(buffer, blake2s_kat[SOME_INDEX], 8x4);
</code>```

Body:
I have to convert the number generated by uint8_t[][] to simple char[]. How can I convert uint8_t[][] number to char key[]. I have convert number to char and want to store to the database.

static const uint8_t blake2s_kat[BLAKE2_KAT_LENGTH][BLAKE2_KAT_LENGTH] =
{
{
    0x69, 0x21, 0x7A, 0x30, 0x79, 0x90, 0x80, 0x94,
    0xE1, 0x11, 0x21, 0xD0, 0x42, 0x35, 0x4A, 0x7C,
    0x1F, 0x55, 0xB6, 0x48, 0x2C, 0xA1, 0xA5, 0x1E,
    0x1B, 0x25, 0x0D, 0xFD, 0x1E, 0xD0, 0xEE, 0xF9
},
{
    0xE3, 0x4D, 0x74, 0xDB, 0xAF, 0x4F, 0xF4, 0xC6,
    0xAB, 0xD8, 0x71, 0xCC, 0x22, 0x04, 0x51, 0xD2,
    0xEA, 0x26, 0x48, 0x84, 0x6C, 0x77, 0x57, 0xFB,
    0xAA, 0xC8, 0x2F, 0xE5, 0x1A, 0xD6, 0x4B, 0xEA
},....};

e.g.

  somenumber = blake2s_kat;
 char key[100] = some function to convert into char(somenumber);

Body:
What you ask is problematic, since two-dimensional array is not one-dimensional array.

If a cell is like a room

then a one-dimensional array is like a hallway populated with rooms

and a two-dimensional array is like a building populated with hallways

you can't just take a building and convert it into a hallway.

what you can do is to cast each sub-array of uint8_t[] to char*:

auto pointer = reinterpret_cast<char*>(blake2s_kat[SOME_INDEX]);

blake2s_kat[SOME_INDEX] decayes into uint8_t* which than can be casted to char*.

also, each sub array in your example seems to contain only 8x4 numbers, which is not 100. make sure that you consider the size of your arrays.

another possibility is to use memcpy:

char buffer[8x4];
memcpy(buffer, blake2s_kat[SOME_INDEX], 8x4);


问:
Set minDate in Jquery
I want how to set minDate. I use this

```<code>$(function () {
    $("#dph-entry").datepicker('option', 'minDate', new Date(2017, 3, 27));
});
</code>```

the input

```<code><input type='text' class="con-input" id='dph-entry' placeholder="Entrada"/>
</code>```

but doesn't works

答:
You need to initialize datepicker() first. Then only option's can be set.

```<code>$("#dph-entry").datepicker();
$("#dph-entry").datepicker('option', 'minDate', new Date(2017, 3, 27));
</code>```

Better pass options while initializing

```<code>$("#dph-entry").datepicker({'minDate': new Date(2017, 3, 27)});
</code>```

$(function() {
  $("#dph-entry").datepicker({
    'minDate': new Date(2017, 3, 27)
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://code.jquery.com/ui/jquery-ui-git.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<input type='text' class="con-input" id='dph-entry' placeholder="Entrada" /></code>```

Title: Set minDate in Jquery

Body:
I want how to set minDate. I use this

$(function () {
    $("#dph-entry").datepicker('option', 'minDate', new Date(2017, 3, 27));
});

the input

<input type='text' class="con-input" id='dph-entry' placeholder="Entrada"/>

but doesn't works

Body:
You need to initialize datepicker() first. Then only option's can be set.

$("#dph-entry").datepicker();
$("#dph-entry").datepicker('option', 'minDate', new Date(2017, 3, 27));

Better pass options while initializing

$("#dph-entry").datepicker({'minDate': new Date(2017, 3, 27)});

$(function() {
  $("#dph-entry").datepicker({
    'minDate': new Date(2017, 3, 27)
  });
});

<link href="https://code.jquery.com/ui/jquery-ui-git.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<input type='text' class="con-input" id='dph-entry' placeholder="Entrada" />


答:
you should chnge your onBindViewHolder as below:

```<code>  @Override
public void onBindViewHolder(Checkout_fragment2_confermation_Adapter.ViewHolder holder, int position) {

    holder.title.setText(data.get(position).getTitle());
    if (position == dat.size()) {
        holder.price.setText(getTotalPrice());
    } else
        holder.price.setText(data.get(position).getPrice());
    holder.product_img.setImageBitmap(getImage(data.get(position).getImg()));

}

public int getTotalPrice() {
    int total = 0;
    for (int i = 0; i < data.size(); i++) {
        total+=data.get(i);
    }
    return total;
}
</code>```

if your total price is not changing again you can calculate the total price at first and for once.

Title: how to get sum of integer value from recyclerview

Body:
i am want to implement something like invoice. i am using recyclerview in fragment. and textview. i have some item in recyclerview. which content title,unit and price. now i want to get sum of all item's price in my textview which is in fragment. here is image what i want to achive.

here is image for understanding

here is my code for adapter class

public class Checkout_fragment2_confermation_Adapter extends RecyclerView.Adapter<Checkout_fragment2_confermation_Adapter.ViewHolder>  {

static List<Cart_datamodel> data;
static Context context;

public Checkout_fragment2_confermation_Adapter(Context context , List<Cart_datamodel> data1) {
    data = new ArrayList<Cart_datamodel>();
    this.context = context;
    this.data = data1;
}

@Override
public Checkout_fragment2_confermation_Adapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    final View itemLayoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.checkout_fragmet2confermation_listviwe_single_row, null);
    itemLayoutView.setLayoutParams(new RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.WRAP_CONTENT));
    Checkout_fragment2_confermation_Adapter.ViewHolder viewHolder = new Checkout_fragment2_confermation_Adapter.ViewHolder(itemLayoutView);

    return viewHolder;
}

@Override
public void onBindViewHolder(Checkout_fragment2_confermation_Adapter.ViewHolder holder, int position) {

    holder.title.setText(data.get(position).getTitle());
    holder.price.setText(data.get(position).getPrice());
    holder.product_img.setImageBitmap(getImage(data.get(position).getImg()));

}

@Override
public int getItemCount() {
    return data.size();
}

public class ViewHolder extends RecyclerView.ViewHolder {
    public TextView  title,price;
    public ImageView img,product_img;

    public ViewHolder(View itemView) {
        super(itemView);
        title = (TextView)itemView.findViewById(R.id.title_checkout_fgment2);
        price =(TextView)itemView.findViewById(R.id.price_checkout_fragment2);
        product_img =(ImageView)itemView.findViewById(R.id.image_checkout_fragment2);
    }
}
public static Bitmap getImage(byte[] image) {
    return BitmapFactory.decodeByteArray(image, 0, image.length);
}

}

here is my fragment class

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.fragmenttab2, container, false);

    dataBaseAdapter = new AddressDataBaseAdapter(getContext());
    cart_adapter = new Item_adding_cart(getContext());
    dbList = cart_adapter.getDataFromDB();

   // listview = (ListView)view.findViewById(R.id.listview);

    recyclerView =(RecyclerView)view.findViewById(R.id.my_recycler_view_checkout_fgrment2);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
    recycleradapter = new Checkout_fragment2_confermation_Adapter(getContext(),dbList);
    recyclerView.setAdapter(recycleradapter);

    fname =(TextView)view.findViewById(R.id.firstname_conformation);
    lname =(TextView)view.findViewById(R.id.lastname_conformation);
    mobile =(TextView)view.findViewById(R.id.mobile_conformaton);
    address =(TextView)view.findViewById(R.id.address_conformation);
    zipcode =(TextView)view.findViewById(R.id.zipcode_conformation);
    city =(TextView)view.findViewById(R.id.city_conformation);

    addresslist= new ArrayList<Address_Activity_DataModel>();
    addresslist=dataBaseAdapter.getDataFromDB();

    int count = dataBaseAdapter.getrowcount();
    if(count==0){

    }
    else
    {
        showRecords();
    }

   // loaddata();

    return view;

}

Body:
you should chnge your onBindViewHolder as below:

  @Override
public void onBindViewHolder(Checkout_fragment2_confermation_Adapter.ViewHolder holder, int position) {

    holder.title.setText(data.get(position).getTitle());
    if (position == dat.size()) {
        holder.price.setText(getTotalPrice());
    } else
        holder.price.setText(data.get(position).getPrice());
    holder.product_img.setImageBitmap(getImage(data.get(position).getImg()));

}

public int getTotalPrice() {
    int total = 0;
    for (int i = 0; i < data.size(); i++) {
        total+=data.get(i);
    }
    return total;
}

if your total price is not changing again you can calculate the total price at first and for once.


问:
Ajax phpmyadmin alternative?
I must say, I'm bored of phpmyadmin. We are in 2009 and I have to work with this useful tool and to wait every page to reload after every action. Are any ajaxed alternatives out there? Maybe phpmyadmin himself is going to be ajaxized?</p>

答: I currently using dbninja.com for my stuff. Amazing web based technology.</p>

Title: Ajax phpmyadmin alternative?


问:
Python.Selenium. Can't find existing element. How switch frame
I wand to get feedbacks from page
url = 'https://ru.aliexpress.com/store/product/Gillette-Fusion-blade-4-pc/2671035_1000003578539.html?spm=2114.12010612.0.0.xL0ySy'

I wait until page loaded. And I can find elements using Google Chrome inspector. But selenium can't find elements. And I alse can't find elements at the source page.

How can i get feedbacks using selenium or other instruments?

Here is my code:

```<code>from selenium import webdriver
import time
import csv
import requests

url = 'https://ru.aliexpress.com/store/product/Gillette-Fusion-blade-4-pc/2671035_1000003578539.html?spm=2114.12010612.0.0.xL0ySy'
driver = webdriver.Chrome()
driver.get(url)

try:
    close_popup = driver.find_element_by_class_name('close-layer')
    close_popup.click()
except:
    print("no alert")

tab_feedback = driver.find_element_by_xpath('//*[@id="j-product-tabbed-pane"]/ul/li[2]')
tab_feedback.click()
time.sleep(8)
try:
    text_feedback = driver.find_element_by_xpath('//*[@id="transction-feedback"]/div[4]/div[1]/div[2]/div[3]/dl')
    print(text_feedback.text)
except:
    print("cant find by xpath")

try:
    text_feedback = driver.find_element_by_class_name('buyer-feedback')
    print(text_feedback.text)
except:
    print("cant find by class_name")

try:
    text_feedback = driver.find_element_by_css_selector('div.f-content.dl.dt.span')
    print(text_feedback.text)
except:
    print("cant find by css_selector")
</code>```

it returns:

```<code>cant find by xpath
cant find by class_name
cant find by css_selector
</code>```

答:
And I also can't find elements at the source page.

This is OK since lots of modern websites uses dynamically loaded content and AJAX and JS frameworks. The source page is just the initial DOM nothing is added.

However the inspector refreshes its DOM. You should look for how to find dynamically added element to DOM.

Body:
I wand to get feedbacks from page
url = 'https://ru.aliexpress.com/store/product/Gillette-Fusion-blade-4-pc/2671035_1000003578539.html?spm=2114.12010612.0.0.xL0ySy'

I wait until page loaded. And I can find elements using Google Chrome inspector. But selenium can't find elements. And I alse can't find elements at the source page.

How can i get feedbacks using selenium or other instruments?

Here is my code:

from selenium import webdriver
import time
import csv
import requests

url = 'https://ru.aliexpress.com/store/product/Gillette-Fusion-blade-4-pc/2671035_1000003578539.html?spm=2114.12010612.0.0.xL0ySy'
driver = webdriver.Chrome()
driver.get(url)

try:
    close_popup = driver.find_element_by_class_name('close-layer')
    close_popup.click()
except:
    print("no alert")

tab_feedback = driver.find_element_by_xpath('//*[@id="j-product-tabbed-pane"]/ul/li[2]')
tab_feedback.click()
time.sleep(8)
try:
    text_feedback = driver.find_element_by_xpath('//*[@id="transction-feedback"]/div[4]/div[1]/div[2]/div[3]/dl')
    print(text_feedback.text)
except:
    print("cant find by xpath")

try:
    text_feedback = driver.find_element_by_class_name('buyer-feedback')
    print(text_feedback.text)
except:
    print("cant find by class_name")

try:
    text_feedback = driver.find_element_by_css_selector('div.f-content.dl.dt.span')
    print(text_feedback.text)
except:
    print("cant find by css_selector")

it returns:

cant find by xpath
cant find by class_name
cant find by css_selector


问:
Single legend at changing categories (!) in subplots from pandas df
Roughly speaking I need to create one legend for several subplots, which have a changing number of categories = legend entries.
But let me clarify this a bit deeper:

I have a figure with 20 subplots, one for each country within my spatial scope:

```<code>fig, ax = plt.subplots(nrows=4, ncols=5, sharex=True, sharey=False, figsize = (32,18))
</code>```

Within a loop, I do some logic to group the data I need into a normal 2-dimensional pandas DataFrame stats and plot it to each of these 20 axes:

```<code>colors = stats.index.to_series().map(type_to_color()).tolist()
stats.T.plot.bar(ax=ax[i,j], stacked=True, legend=False, color=colors)
</code>```

However, the stats DataFrame is changing its size loop by loop, since not every category applies for each of these countries (i.e. in one country there can only two types, in another there are more than 10).
For this reason I pre-defined a specific color for each type.
So far, I am creating one legend for every subplot within the loop:

```<code>ax[i,j].legend(fontsize=9, loc='upper right')
</code>```

This works, however it blows up the subplots unnecessarily. How can I plot one big legend above/below/beside these plots, since I have already defined the according color.
The given approach here with fig.legend(handles, labels, ...)does not work since the line handles are not available from the pandas plot.
Plotting the legend directly with

```<code>plt.legend(loc = 'lower center',bbox_to_anchor = (0,-0.3,1,1),
    bbox_transform = plt.gcf().transFigure)
</code>```

shows only the entries for the very last subplot, which is not sufficient.

Any help is greatly appreciated! Thank you so much!

Edit
For example the DataFrame stats could in one country look like this:

```<code>              2015       2020       2025       2030       2035       2040
Hydro        29.229082  28.964424  28.528139  27.120194  25.932098  24.675778
Natural Gas   0.926800   0.926800   0.926800   0.926800   0.003600        NaN
Wind         25.799950  25.797550   0.776400   0.520800   0.234400        NaN
</code>```

Whereas in another country it might look like this:

```<code>              2015        2020        2025        2030        2035
Bioenergy     0.033690    0.033690    0.030000         NaN         NaN
Hard Coal     5.307300    0.065100    0.021000         NaN         NaN
Hydro        22.834454   23.930642   23.169014   21.639914   19.623791
Natural Gas   8.378116    8.674121    8.013598    6.755498    5.255450
Solar         5.100403    5.100403    5.100403    5.100403    5.093403
Wind          8.983560    8.974740    8.967240    8.378300    0.195800
</code>```

答:
Here's how it works to get the legend into an alphabetical order without messing the colors up:</p>

```<code>import matplotlib.patches as mpatches
import collections

fig, ax = plt.subplots(nrows=4, ncols=5, sharex=True, sharey=False, figsize = (32,18))
labels_mpatches = collections.OrderedDict()

for a, b in enumerate(countries())
    # do some data logic here
    colors = stats.index.to_series().map(type_to_color()).tolist()
    stats.T.plot.bar(ax=ax[i,j],stacked=True,legend=False,color=colors)
    # Pass the legend information into the OrderedDict
    stats_handle, stats_labels = ax[i,j].get_legend_handles_labels()
        for u, v in enumerate(stats_labels):
            if v not in labels_mpatches:
                labels_mpatches[v] = mpatches.Patch(color=colors[u], label=v)
# After the loop, do the legend layouting.
labels_mpatches = collections.OrderedDict(sorted(labels_mpatches.items()))
fig.legend(labels_mpatches.values(), labels_mpatches.keys())
# !!! Please Note: In previous versions this here worked, but does not anymore:
# fig.legend(handles=labels_mpatches.values(),labels=labels_mpatches.keys())
</code>```

Body:
Roughly speaking I need to create one legend for several subplots, which have a changing number of categories = legend entries.
But let me clarify this a bit deeper:

I have a figure with 20 subplots, one for each country within my spatial scope:

fig, ax = plt.subplots(nrows=4, ncols=5, sharex=True, sharey=False, figsize = (32,18))

Within a loop, I do some logic to group the data I need into a normal 2-dimensional pandas DataFrame stats and plot it to each of these 20 axes:

colors = stats.index.to_series().map(type_to_color()).tolist()
stats.T.plot.bar(ax=ax[i,j], stacked=True, legend=False, color=colors)

However, the stats DataFrame is changing its size loop by loop, since not every category applies for each of these countries (i.e. in one country there can only two types, in another there are more than 10).
For this reason I pre-defined a specific color for each type.
So far, I am creating one legend for every subplot within the loop:

ax[i,j].legend(fontsize=9, loc='upper right')

This works, however it blows up the subplots unnecessarily. How can I plot one big legend above/below/beside these plots, since I have already defined the according color.
The given approach here with fig.legend(handles, labels, ...)does not work since the line handles are not available from the pandas plot.
Plotting the legend directly with

plt.legend(loc = 'lower center',bbox_to_anchor = (0,-0.3,1,1),
    bbox_transform = plt.gcf().transFigure)

shows only the entries for the very last subplot, which is not sufficient.

Any help is greatly appreciated! Thank you so much!

Edit
For example the DataFrame stats could in one country look like this:

              2015       2020       2025       2030       2035       2040
Hydro        29.229082  28.964424  28.528139  27.120194  25.932098  24.675778
Natural Gas   0.926800   0.926800   0.926800   0.926800   0.003600        NaN
Wind         25.799950  25.797550   0.776400   0.520800   0.234400        NaN

Whereas in another country it might look like this:

              2015        2020        2025        2030        2035
Bioenergy     0.033690    0.033690    0.030000         NaN         NaN
Hard Coal     5.307300    0.065100    0.021000         NaN         NaN
Hydro        22.834454   23.930642   23.169014   21.639914   19.623791
Natural Gas   8.378116    8.674121    8.013598    6.755498    5.255450
Solar         5.100403    5.100403    5.100403    5.100403    5.093403
Wind          8.983560    8.974740    8.967240    8.378300    0.195800

Body:
Here's how it works to get the legend into an alphabetical order without messing the colors up:

import matplotlib.patches as mpatches
import collections

fig, ax = plt.subplots(nrows=4, ncols=5, sharex=True, sharey=False, figsize = (32,18))
labels_mpatches = collections.OrderedDict()

for a, b in enumerate(countries())
    # do some data logic here
    colors = stats.index.to_series().map(type_to_color()).tolist()
    stats.T.plot.bar(ax=ax[i,j],stacked=True,legend=False,color=colors)
    # Pass the legend information into the OrderedDict
    stats_handle, stats_labels = ax[i,j].get_legend_handles_labels()
        for u, v in enumerate(stats_labels):
            if v not in labels_mpatches:
                labels_mpatches[v] = mpatches.Patch(color=colors[u], label=v)
# After the loop, do the legend layouting.
labels_mpatches = collections.OrderedDict(sorted(labels_mpatches.items()))
fig.legend(labels_mpatches.values(), labels_mpatches.keys())
# !!! Please Note: In previous versions this here worked, but does not anymore:
# fig.legend(handles=labels_mpatches.values(),labels=labels_mpatches.keys())


答:
The way you use it is how you can set the min date after initialization.

Get or set the minDate option, after initialization:

// Getter

var minDate = $( ".selector" ).datepicker( "option", "minDate" );

// Setter

$( ".selector" ).datepicker( "option","minDate", new Date(2007, 1 - 1, 1) );

When you are trying to set the default min date it means you are trying to init the datepicker with min date, that's why you need to add the options a bit differently, property: value:

Initialize the datepicker with the minDate option specified:

$( ".selector" ).datepicker({   minDate: new Date(2007, 1 - 1, 1) });

See the working snippet below please:

$(function() {
  $(document).ready(function() {
    //$("#dp-entry").datepicker('option', 'minDate', new Date(2017, 3, 27));
    $("#dph-entry").datepicker({minDate: new Date(2017, 3, 27)});
  })
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://code.jquery.com/ui/jquery-ui-git.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<input type='text' class="con-input" id='dph-entry' placeholder="Entrada" /></code>```

You can read about what I said here.

Title: Set minDate in Jquery

Body:
The way you use it is how you can set the min date after initialization.

Get or set the minDate option, after initialization:

// Getter

var minDate = $( ".selector" ).datepicker( "option", "minDate" );

// Setter

$( ".selector" ).datepicker( "option","minDate", new Date(2007, 1 - 1, 1) );

When you are trying to set the default min date it means you are trying to init the datepicker with min date, that's why you need to add the options a bit differently, property: value:

Initialize the datepicker with the minDate option specified:

$( ".selector" ).datepicker({   minDate: new Date(2007, 1 - 1, 1) });

See the working snippet below please:

$(function() {
  $(document).ready(function() {
    //$("#dp-entry").datepicker('option', 'minDate', new Date(2017, 3, 27));
    $("#dph-entry").datepicker({minDate: new Date(2017, 3, 27)});
  })
});

<link href="https://code.jquery.com/ui/jquery-ui-git.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<input type='text' class="con-input" id='dph-entry' placeholder="Entrada" />

You can read about what I said here.