问:
Find out where the error happened in Clojure
For the most part I understand what Clojure is telling me with it's error messages. But I am still clueless as to find out where the error happened.

Here is an example of what I mean

```<code>(defn extract [m]
  (keys m))

(defn multiple [xs]
  (map #(* 2 %) xs))

(defn process [xs]
  (-> xs
      (multiple)     ; seq -> seq
      (extract))) ; map -> seq ... fails

(process [1 2 3])
</code>```

Statically typed languages would now tell me that I tried to pass a sequence to a function that expects a map on line X. And Clojure does this in a way:

```<code>ClassCastException java.lang.Long cannot be cast to java.util.Map$Entry
</code>```

But I still have no idea where the error happened. Obviously for this instance it's easy because there are just 3 functions involved, you can easily just read through all of them but as programs grow bigger this gets old very quickly.

Is there a way find out where the errors happened other than just proof reading the code from top to bottom? (which is my current approach)

答:
You can use clojure.spec. It is still in alpha, and there's still a bunch of tooling support coming (hopefully), but instrumenting functions works well.

```<code>(ns foo.core
  (:require
   ;; For clojure 1.9.0-alpha16 and higher, it is called spec.alpha
   [clojure.spec.alpha :as s]
   [clojure.spec.test.alpha :as stest]))

;; Extract takes a map and returns a seq
(s/fdef extract
  :args (s/cat :m map?)
  :ret seq?)

(defn extract [m]
  (keys m))

;; multiple takes a coll of numbers and returns a coll of numbers
(s/fdef multiple
  :args (s/cat :xs (s/coll-of number?))
  :ret (s/coll-of number?))

(defn multiple [xs]
  (map #(* 2 %) xs))

(defn process [xs]
  (-> xs
      (multiple)     ; seq -> seq
      (extract))) ; map -> seq ... fails

;; This needs to come after the definition of the specs,
;; but before the call to process.
;; This is something I imagine can be handled automatically
;; by tooling at some point.
(stest/instrument)

;; The println is to force evaluation.
;; If not it wouldn't run because it's lazy and
;; not used for anything.
(println (process [1 2 3]))
</code>```

Running this file prints (among other info):

```<code>Call to #'foo.core/extract did not conform to spec: In: [0] val: (2
4 6) fails at: [:args :m] predicate: map?  :clojure.spec.alpha/spec
#object[clojure.spec.alpha$regex_spec_impl$reify__1200 0x2b935f0d
"clojure.spec.alpha$regex_spec_impl$reify__1200@2b935f0d"]
:clojure.spec.alpha/value ((2 4 6)) :clojure.spec.alpha/args ((2 4
6)) :clojure.spec.alpha/failure :instrument
:clojure.spec.test.alpha/caller {:file "core.clj", :line 29,
:var-scope foo.core/process}
</code>```

Which can be read as: A call to exctract failed because the value passed in (2 4 6) failed the predicate map?. That call happened in the file "core.clj" at line 29.

A caveat that trips people up is that instrument only checks function arguments and not return values. This is a (strange if you ask me) design decision from Rich Hickey. There's a library for that, though.

Body:
For the most part I understand what Clojure is telling me with it's error messages. But I am still clueless as to find out where the error happened.

Here is an example of what I mean

(defn extract [m]
  (keys m))

(defn multiple [xs]
  (map #(* 2 %) xs))

(defn process [xs]
  (-> xs
      (multiple)     ; seq -> seq
      (extract))) ; map -> seq ... fails

(process [1 2 3])

Statically typed languages would now tell me that I tried to pass a sequence to a function that expects a map on line X. And Clojure does this in a way:

ClassCastException java.lang.Long cannot be cast to java.util.Map$Entry

But I still have no idea where the error happened. Obviously for this instance it's easy because there are just 3 functions involved, you can easily just read through all of them but as programs grow bigger this gets old very quickly.

Is there a way find out where the errors happened other than just proof reading the code from top to bottom? (which is my current approach)

Body:
You can use clojure.spec. It is still in alpha, and there's still a bunch of tooling support coming (hopefully), but instrumenting functions works well.

(ns foo.core
  (:require
   ;; For clojure 1.9.0-alpha16 and higher, it is called spec.alpha
   [clojure.spec.alpha :as s]
   [clojure.spec.test.alpha :as stest]))

;; Extract takes a map and returns a seq
(s/fdef extract
  :args (s/cat :m map?)
  :ret seq?)

(defn extract [m]
  (keys m))

;; multiple takes a coll of numbers and returns a coll of numbers
(s/fdef multiple
  :args (s/cat :xs (s/coll-of number?))
  :ret (s/coll-of number?))

(defn multiple [xs]
  (map #(* 2 %) xs))

(defn process [xs]
  (-> xs
      (multiple)     ; seq -> seq
      (extract))) ; map -> seq ... fails

;; This needs to come after the definition of the specs,
;; but before the call to process.
;; This is something I imagine can be handled automatically
;; by tooling at some point.
(stest/instrument)

;; The println is to force evaluation.
;; If not it wouldn't run because it's lazy and
;; not used for anything.
(println (process [1 2 3]))

Running this file prints (among other info):

Call to #'foo.core/extract did not conform to spec: In: [0] val: (2
4 6) fails at: [:args :m] predicate: map?  :clojure.spec.alpha/spec
#object[clojure.spec.alpha$regex_spec_impl$reify__1200 0x2b935f0d
"clojure.spec.alpha$regex_spec_impl$reify__1200@2b935f0d"]
:clojure.spec.alpha/value ((2 4 6)) :clojure.spec.alpha/args ((2 4
6)) :clojure.spec.alpha/failure :instrument
:clojure.spec.test.alpha/caller {:file "core.clj", :line 29,
:var-scope foo.core/process}

Which can be read as: A call to exctract failed because the value passed in (2 4 6) failed the predicate map?. That call happened in the file "core.clj" at line 29.

A caveat that trips people up is that instrument only checks function arguments and not return values. This is a (strange if you ask me) design decision from Rich Hickey. There's a library for that, though.


来源: stackexchange

问:
has_secure_password, wont create attributes
I am trying to use has_secure_password and bcrypt (3.1.11) on my Rails app.

Here is my setup on Ubuntu:

I installed bcrypt with no issues and have it in my gem file

I have a password_digest:string for my users migrated in the database

I added has_secure_password to my user model

I am getting no errors, however when I go to create a user, it is asking me for a password_digest attribute instead of password and password_confirmation.

why is this? Shouldn't the has_secure_password automatically change the user to need a password and password_confirmation instead of password_digest?

答:
Nope, you don't store the password and password_confirmation, just the password_digest. You never want to store plain text passwords in your db.

When you create a new user you do

```<code>User.create(password: 'something', password_confirmation: 'something', ..other fields..)
</code>```

and then has_secure_password takes care of updating the password_digest in the database.

It's also a good rule to include some validations in your User model.

```<code>validates :password_confirmation, presence: true, on: :create
validates :password, confirmation: true
</code>```

Also don't forget to white list them in your controller

```<code>def user_params
  params.require(:user).permit(:password, :password_confirmation)
end

User.create(user_params)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Nope, you don't store the password and password_confirmation, just the password_digest. You never want to store plain text passwords in your db.

When you create a new user you do

User.create(password: 'something', password_confirmation: 'something', ..other fields..)

and then has_secure_password takes care of updating the password_digest in the database.

It's also a good rule to include some validations in your User model.

validates :password_confirmation, presence: true, on: :create
validates :password, confirmation: true

Also don't forget to white list them in your controller

def user_params
  params.require(:user).permit(:password, :password_confirmation)
end

User.create(user_params)


问:
Setting a property of all objects of an Iterable
is there a smart way to set a property of all objects of an Iterable to a specified value?

I have a class SystemUser that looks like that:

```<code>class SystemUser{
  private String name;
  private String password;
  ...
}
</code>```

and another class that generates an Iterable object like:

```<code>public Iterable<SystemUser> getUsers(){
   ...
   return users;
}
</code>```

Can I set the attribute "password" of all objects of the Iterable to null without iterating?

Thanks!

答:
Unless you've already set the password before amalgamating them into that Iterable, their password (and name) is already set to null by virtue of the initial value for references.

If you have set the password for one or any number of them before their amalgamation, you would have to iterate, either through standard for statements or through the use of forEach and streams.

Body:
is there a smart way to set a property of all objects of an Iterable to a specified value?

I have a class SystemUser that looks like that:

class SystemUser{
  private String name;
  private String password;
  ...
}

and another class that generates an Iterable object like:

public Iterable<SystemUser> getUsers(){
   ...
   return users;
}

Can I set the attribute "password" of all objects of the Iterable to null without iterating?

Thanks!


问:
Problems with variable scope in example swap for powershell
```<code>$global:value1
$global:value2
$global:value3

function initialize {
    $value1 = 100
    $value2 = 500
}

function subtract {
    $value3 = $value1 - $value2
    Write-Host $value3
}

function swap {
    Write-Host Before swap Value1: $value1 "& Value2: "$value2
    $value3 = $value1
    $value1 = $value2
    $value2 = $value3
    Write-Host After swap Value1: $value1 "& Value2: "$value2
}

function run-myscript {
    cls
    initialize
    subtract
    swap
    subtract
}
</code>```

Output:

-400

  Before swap Value1: 100 & Value2:  500

  After swap Value1: 500 & Value2:  100

  -400

Please explain this behaviour why i get both values as -400, i should get once -400 and second time 400

答:
Ok Figured out that i have to call every time the vairable by its scope i.e global</p>

```<code>$global:value1
$global:value2
$global:value3
function initialize
{
$global:value1 = 100
$global:value2 = 500
}
function subtract
{
$global:value3 = $global:value1 - $global:value2
Write-Host $global:value3
}
function swap
{
Write-Host Before swap Value1: $value1 "& Value2: "$value2
$global:value3 = $global:value1
$global:value1 = $global:value2
$global:value2 = $global:value3
Write-Host After swap Value1: $value1 "& Value2: "$value2
}

function run-myscript
{
cls
initialize
subtract
swap
subtract
}
</code>```

Body:
$global:value1
$global:value2
$global:value3

function initialize {
    $value1 = 100
    $value2 = 500
}

function subtract {
    $value3 = $value1 - $value2
    Write-Host $value3
}

function swap {
    Write-Host Before swap Value1: $value1 "& Value2: "$value2
    $value3 = $value1
    $value1 = $value2
    $value2 = $value3
    Write-Host After swap Value1: $value1 "& Value2: "$value2
}

function run-myscript {
    cls
    initialize
    subtract
    swap
    subtract
}

Output:

-400

  Before swap Value1: 100 & Value2:  500

  After swap Value1: 500 & Value2:  100

  -400

Please explain this behaviour why i get both values as -400, i should get once -400 and second time 400

Body:
Ok Figured out that i have to call every time the vairable by its scope i.e global

$global:value1
$global:value2
$global:value3
function initialize
{
$global:value1 = 100
$global:value2 = 500
}
function subtract
{
$global:value3 = $global:value1 - $global:value2
Write-Host $global:value3
}
function swap
{
Write-Host Before swap Value1: $value1 "& Value2: "$value2
$global:value3 = $global:value1
$global:value1 = $global:value2
$global:value2 = $global:value3
Write-Host After swap Value1: $value1 "& Value2: "$value2
}

function run-myscript
{
cls
initialize
subtract
swap
subtract
}


问:
jQuery - Stop form submit depending on ajax response, otherwise let it submit
I setup some jQuery code so that when a user tries to submit this form, it checks to see what the ajax response is from our 'check_bid_locked' function in php. If it's 'assigned', 'expired', or 'yes', then it uses e.prevent_default() to stop the submit and show a modal popup message (which is working).

What I can't seem to figure out is how to let the form be SUBMITTED if the response doesn't match any of these. Basically, if the response is 'no' then we want the form to be submitted. Any ideas?

HTML

```<code>    <form onsubmit="return true check_submits();" method="post" action="<?php echo get_permalink($pid); ?>">
   <input type="hidden" name="control_id" value="<?php echo base64_encode($pid); ?>" />
   <input class="submit_bottom" id="submits_crt" type="submit" name="bid_now_reverse" value="<?php _e("Place Bid",'BidTheme'); ?>" />
  </form>
</code>```

Jquery

```<code>$(document).ready("#bid_now_reverse").submit(function(e) {

var allowSubmit = false;
if (allowSubmit == false) {
e.preventDefault();
}

    var data = {
        'action': 'check_bid_locked',
        'pid': <?php echo $pid; ?>,
        'uid': <?php echo $uid; ?>
    };

    jQuery.post('<?php echo admin_url( 'admin-ajax.php' ); ?>', data,
function(response) {
            //If bid NOT locked
            if(response == 'no') {
            allowSubmit == true;
            }
            //If Assigned
            if(response == 'assigned') {
            confirm('<div class="bid_panel_box_title">Task Has Been
Assigned</div><div class="padd10_center">Your offer can\'t be deleted.
</div>', {
                    /*
                    Define your buttons here, can handle multiple buttons
                    with custom title and values
                    */
                    buttons: [
                        { class: "delete_button15", type: "button", title:
"Close", value: "Cancel" }

                    ],
                    modal: true
                },
                //Reload page START
                function(resp) {
                   console.log(resp);
            if(resp == 'Cancel'){
                window.location.reload(true);
            } }
            //Reload page END
        );
        //If Expired
    }else if(response == 'expired'){
        confirm('<div class="bid_panel_box_title">Task Has Expired</div><div class="padd10_center">Your offer can\'t be deleted.</div>', {
                /*
                Define your buttons here, can handle multiple buttons
                with custom title and values
                */
                buttons: [
                    { class: "delete_button15", type: "button", title: "Close", value: "Cancel" }

                ],
                modal: true
            },
            //Reload page START
            function(resp) {
               console.log(resp);
        if(resp == 'Cancel'){
            window.location.reload(true);
        } }
            //Reload page END
        );
        //If Change Offer Locked
    }else if(response == 'yes'){
    allowSubmit = false;
        confirm('<div class="bid_panel_box_title">Offer Change Locked</div><div class="padd10_center">The Poster is reviewing your offer.<br/><br/>Check back shortly to see if it was accepted or to change it.</div>', {
                /*
                Define your buttons here, can handle multiple buttons
                with custom title and values
                */
                buttons: [
                    { class: "delete_button15", type: "button", title: "Close", value: "Cancel"}

                ],
                modal: true
            },
            //Reload page START
            function(resp) {
               console.log(resp);
        if(resp == 'Cancel'){
            window.location.reload(true);
        } }
            //Reload page END
        );
        }
});
</code>```

});

答:
Use submit :

```<code>if(response == 'no'){
    $('form').submit();
}
</code>```

Body:
I setup some jQuery code so that when a user tries to submit this form, it checks to see what the ajax response is from our 'check_bid_locked' function in php. If it's 'assigned', 'expired', or 'yes', then it uses e.prevent_default() to stop the submit and show a modal popup message (which is working).

What I can't seem to figure out is how to let the form be SUBMITTED if the response doesn't match any of these. Basically, if the response is 'no' then we want the form to be submitted. Any ideas?

HTML

    <form onsubmit="return true check_submits();" method="post" action="<?php echo get_permalink($pid); ?>">
   <input type="hidden" name="control_id" value="<?php echo base64_encode($pid); ?>" />
   <input class="submit_bottom" id="submits_crt" type="submit" name="bid_now_reverse" value="<?php _e("Place Bid",'BidTheme'); ?>" />
  </form>

Jquery

$(document).ready("#bid_now_reverse").submit(function(e) {

var allowSubmit = false;
if (allowSubmit == false) {
e.preventDefault();
}

    var data = {
        'action': 'check_bid_locked',
        'pid': <?php echo $pid; ?>,
        'uid': <?php echo $uid; ?>
    };

    jQuery.post('<?php echo admin_url( 'admin-ajax.php' ); ?>', data,
function(response) {
            //If bid NOT locked
            if(response == 'no') {
            allowSubmit == true;
            }
            //If Assigned
            if(response == 'assigned') {
            confirm('
Task Has Been
Assigned

Your offer can\'t be deleted.

', {
                    /*
                    Define your buttons here, can handle multiple buttons
                    with custom title and values
                    */
                    buttons: [
                        { class: "delete_button15", type: "button", title:
"Close", value: "Cancel" }

                    ],
                    modal: true
                },
                //Reload page START
                function(resp) {
                   console.log(resp);
            if(resp == 'Cancel'){
                window.location.reload(true);
            } }
            //Reload page END
        );
        //If Expired
    }else if(response == 'expired'){
        confirm('
Task Has Expired

Your offer can\'t be deleted.
', {
                /*
                Define your buttons here, can handle multiple buttons
                with custom title and values
                */
                buttons: [
                    { class: "delete_button15", type: "button", title: "Close", value: "Cancel" }

                ],
                modal: true
            },
            //Reload page START
            function(resp) {
               console.log(resp);
        if(resp == 'Cancel'){
            window.location.reload(true);
        } }
            //Reload page END
        );
        //If Change Offer Locked
    }else if(response == 'yes'){
    allowSubmit = false;
        confirm('
Offer Change Locked

The Poster is reviewing your offer.

Check back shortly to see if it was accepted or to change it.
', {
                /*
                Define your buttons here, can handle multiple buttons
                with custom title and values
                */
                buttons: [
                    { class: "delete_button15", type: "button", title: "Close", value: "Cancel"}

                ],
                modal: true
            },
            //Reload page START
            function(resp) {
               console.log(resp);
        if(resp == 'Cancel'){
            window.location.reload(true);
        } }
            //Reload page END
        );
        }
});

});

Body:
Use submit :

if(response == 'no'){
    $('form').submit();
}


问:
Align HTML items
I have one div containing 3 divs.

original

HTML code

.state {
  background-color: rgba(233, 234, 237, 0.9);
  height: 7vh;
  width: 80%;
  border-radius: 14px;
  margin: 10px 0 15px 80px;
  display: flex;
  align-items: stretch;
}

.state-main {
  text-align: center;
  padding-top: 10px;
  font-weight: 900;
  font-size: 14px;
}

.options {
  text-align: right;
  margin-bottom: 10px;
}

.owner-image {
  border-top-left-radius: 14px;
  border-bottom-left-radius: 14px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="state">

  <div class="owner">
    <img class="owner-image" src="img/uk.jpg">
  </div>
  <div class="state-main">
    <p class="state-name">PENNSYLVANIA</p>
  </div>
  <div class="options">
    <p id="time"></p>
    <button>SEND TROOPS</button>
    <button>ATTACK</button>
  </div>

</div></code>```

答:
.State is the div that contains all 3. .state-main is yellow div and should go at the center. .options is green div should go far right. .owner-image is the red div, and should stay at the same place.

Using flex to put the layout into place.

.state {
  display: flex;
  justify-content: space-between;
}

.state-mail {
  text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="state">
  <div class="owner-image">
    <img src="http://placehold.it/100x50" />
  </div>
  <div class="state-main">PENNSYLVANIA</div>
  <div class="options"><button>SEND TROOPS</button><button>ATTACK</button></div>
</div></code>```

Title: Align HTML items

Body:
I have one div containing 3 divs.

original

HTML code

.state {
  background-color: rgba(233, 234, 237, 0.9);
  height: 7vh;
  width: 80%;
  border-radius: 14px;
  margin: 10px 0 15px 80px;
  display: flex;
  align-items: stretch;
}

.state-main {
  text-align: center;
  padding-top: 10px;
  font-weight: 900;
  font-size: 14px;
}

.options {
  text-align: right;
  margin-bottom: 10px;
}

.owner-image {
  border-top-left-radius: 14px;
  border-bottom-left-radius: 14px;
}

PENNSYLVANIA

    <button>SEND TROOPS</button>
    <button>ATTACK</button>

Body:
.State is the div that contains all 3. .state-main is yellow div and should go at the center. .options is green div should go far right. .owner-image is the red div, and should stay at the same place.

Using flex to put the layout into place.

.state {
  display: flex;
  justify-content: space-between;
}

.state-mail {
  text-align: center;
}

<div class="state">
  <div class="owner-image">
    <img src="http://placehold.it/100x50" />
  </div>
  <div class="state-main">PENNSYLVANIA</div>
  <div class="options"><button>SEND TROOPS</button><button>ATTACK</button></div>
</div>


问:
Uncaught TypeError: Cannot read property 'each' of undefined
I am getting : Uncaught TypeError: Cannot read property 'each' of undefined
at animateIfInview
at atonscroll

and heres the code :

```<code> <script>
 function animateIfInView() {
 $.each($("content-img"), function(key, value) {
 if (isElementInViewport($(value))) {
 $(value).addClass("content-img-in-view");
 } else {
  // (Optional) Fade out when out of view
  $(value).removeClass("content-img-in-view");
  }
  });
  }

  // http://stackoverflow.com/a/7557433/5628
   function isElementInViewport(el) {
    //special bonus for those using jQuery
  if (typeof jQuery === "function" && el instanceof jQuery) {
  el = el[0];
  }

  var rect = el.getBoundingClientRect();

  return (
  rect.top >= 0 &&
  rect.left >= 0 &&
  rect.bottom <=
  (window.innerHeight ||
  document.documentElement.clientHeight) /*or $(window).height() */ &&
  rect.right <=
  (window.innerWidth ||
  document.documentElement.clientWidth) /*or $(window).width() */
  );
  }
  </script>
</code>```

How can I fix this error? what am I missing in code? Thanks guys in advance

答:
```<code>jQuery.each(array/object,callback_function);
</code>```

require first parameter as an array or an object. Read documentation
here . I suggest to use var obj = $(document).find(".content-img"); then use
as

```<code>$.each(obj,function(key,value){
//your code goes here
});
</code>```

Body:
I am getting : Uncaught TypeError: Cannot read property 'each' of undefined
at animateIfInview
at atonscroll

and heres the code :

How can I fix this error? what am I missing in code? Thanks guys in advance

Body:
jQuery.each(array/object,callback_function);

require first parameter as an array or an object. Read documentation
here . I suggest to use var obj = $(document).find(".content-img"); then use
as

$.each(obj,function(key,value){
//your code goes here
});


问:
Error in use PostGIS SQL function with two select statement
I am new to PostGIS and SQL with a lot of things I need to learn.

I tried this SQL query:

```<code>Select ST_AsText(Select line from pathway1f)
</code>```

I got errors.

```<code>Select line from pathway1f
</code>```

This query works fine; thousands of lines are returned.

I want to decode the query result using ST_AsText().

It seems like I can't use two select statements. What's the correct syntax?

答:
You can use the geometry column name directly</p>

```<code>Select ST_AsText(line)
from pathway1f;
</code>```

Body:
I am new to PostGIS and SQL with a lot of things I need to learn.

I tried this SQL query:

Select ST_AsText(Select line from pathway1f)

I got errors.

Select line from pathway1f

This query works fine; thousands of lines are returned.

I want to decode the query result using ST_AsText().

It seems like I can't use two select statements. What's the correct syntax?

Body:
You can use the geometry column name directly

Select ST_AsText(line)
from pathway1f;


问:
How can I list all databases and all tables of my databases with a final "Attach" and list total row of each table in SQL Server?
I did this. But unfortunately that return all in many table. I want to return all in one unique table. Maybe using "UNION" but I don't know the way to do.

This is my code:

```<code>EXEC sp_msforeachdb 'select ''?''AS "DataBase", s.name, t.name AS "Tables",max(si.rows) as "Rows Line"
 from [?].sys.tables t inner join [?].sys.schemas s
 on t.schema_id = s.schema_id
 inner join [?].sys.partitions si on t.object_id  = si.object_id
 where t.name like "%ATTACH" group by s.name,t.name'`
</code>```

答:
This will list all the tables in a given database and the number of rows in each. Notice the results are in a table named #results:

```<code>set nocount on

declare @curtable sysname
declare @prevtable sysname
declare @curcount int
declare @tsql varchar(500)

if object_ID('tempdb..#curtables','U') is not null
    drop table #curtables

select name  into #curtables
from sys.objects
where type='U'
order by 1

if object_id('tempdb..#results','U') is not null
    drop table #results

create table #results(name sysname,numrows int)

select top 1 @curtable=name from #curtables order by name
while (1=1)
begin

    set @tsql = 'select '''+quotename(@curtable) +''',count(*) numrows  from '+quotename(@curtable)
    print @tsql
    insert into #results
    exec (@tsql)
    set @prevtable= @curtable
    select top 1 @curtable = name
    from #curtables
    where name > @prevtable
    order by name
    if   @curtable=@prevtable
        break
</code>```

end

Body:
I did this. But unfortunately that return all in many table. I want to return all in one unique table. Maybe using "UNION" but I don't know the way to do.

This is my code:

EXEC sp_msforeachdb 'select ''?''AS "DataBase", s.name, t.name AS "Tables",max(si.rows) as "Rows Line"
 from [?].sys.tables t inner join [?].sys.schemas s
 on t.schema_id = s.schema_id
 inner join [?].sys.partitions si on t.object_id  = si.object_id
 where t.name like "%ATTACH" group by s.name,t.name'`

Body:
This will list all the tables in a given database and the number of rows in each. Notice the results are in a table named #results:

set nocount on

declare @curtable sysname
declare @prevtable sysname
declare @curcount int
declare @tsql varchar(500)

if object_ID('tempdb..#curtables','U') is not null
    drop table #curtables

select name  into #curtables
from sys.objects
where type='U'
order by 1

if object_id('tempdb..#results','U') is not null
    drop table #results

create table #results(name sysname,numrows int)

select top 1 @curtable=name from #curtables order by name
while (1=1)
begin

    set @tsql = 'select '''+quotename(@curtable) +''',count(*) numrows  from '+quotename(@curtable)
    print @tsql
    insert into #results
    exec (@tsql)
    set @prevtable= @curtable
    select top 1 @curtable = name
    from #curtables
    where name > @prevtable
    order by name
    if   @curtable=@prevtable
        break

end


问:
pygame - treat a variable as a variable not string
I am trying to loop round all of the number keys on a keyboard (0-9) and thought to do this you would use this code:

```<code>for i in range (0,10):
    if keys[pygame.K_i]:
        pass
</code>```

But obviously as expected, pygame.K_i treats 'i' as the keyboard input 'i' not the variable. I was wondering how to specify I would like to use the variable not the keyboard input.

Sorry if the title is misleading, thanks.

答: The key constants (like pygame.K_0) are just integers that represent the keyboard keys. pygame.K_0 is 48, pygame.K_1 is 49 and so on. You can use the range range(48, 58).

Body:
I am trying to loop round all of the number keys on a keyboard (0-9) and thought to do this you would use this code:

for i in range (0,10):
    if keys[pygame.K_i]:
        pass

But obviously as expected, pygame.K_i treats 'i' as the keyboard input 'i' not the variable. I was wondering how to specify I would like to use the variable not the keyboard input.

Sorry if the title is misleading, thanks.


问:
Android Studio- Multiple Implementations issue at android:id
I am beginner of Android studio. I got issue in layout at android:id with multiple implementation. I searched but it's showing links with- Include same layout multiple times- and Can I use the same id in different layout-Android Multiple Implementations of one element of the same Layout etc.,...

I tried to search on web too but I didn't find related information .The problem is in a layout I have used. The Button id is android:id="@+id/button_actionpage" and also I have used the Button id below in DatePicker Button with android:layout_below="@+id/button_actionpage". So I got a issue in Activity.java with an error                                                                              "java.lang.NullPointerException" due multiple implementation android:id in layout

I can't get a solution about android:id with multiple implementation in layout.

Here is my screen shot

Here is my layout code:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button_store"
        android:text="Store information"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show Information"
        android:id="@+id/button_show"
        android:layout_alignParentTop="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Date:"
        android:id="@+id/date_reg"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ActionPage"
        android:id="@+id/button_actionpage"
        android:layout_marginTop="116dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <DatePicker
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/datePicker"
        android:layout_below="@+id/button_actionpage"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

</RelativeLayout>
</code>```

Logcat:

07-30 15:58:14.041 29642-29642/com.raj.androidapplication
  E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.raj.androidapplication, PID: 29642
                                                                                java.lang.RuntimeException: Unable to start activity
  ComponentInfo{com.raj.androidapplication/com.raj.androidapplication.LoginPrefActivity}:
  android.view.InflateException: Binary XML file line #25: Error
  inflating class java.lang.reflect.Constructor
                                                                                at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2335)
                                                                                at
  android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2397)
                                                                                at android.app.ActivityThread.access$800(ActivityThread.java:151)
                                                                                at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1310)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:135)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5268)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:902)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:697)
                                                                                Caused by: android.view.InflateException: Binary XML file line #25:
  Error inflating class java.lang.reflect.Constructor
                                                                                at
  android.preference.GenericInflater.createItem(GenericInflater.java:397)
                                                                                at
  android.preference.GenericInflater.onCreateItem(GenericInflater.java:417)
                                                                                at
  android.preference.GenericInflater.createItemFromTag(GenericInflater.java:428)
                                                                                at
  android.preference.GenericInflater.rInflate(GenericInflater.java:481)
                                                                                at
  android.preference.GenericInflater.rInflate(GenericInflater.java:493)
                                                                                at
  android.preference.GenericInflater.inflate(GenericInflater.java:326)
                                                                                at
  android.preference.GenericInflater.inflate(GenericInflater.java:263)
                                                                                at
  android.preference.PreferenceManager.inflateFromResource(PreferenceManager.java:272)
                                                                                at
  android.preference.PreferenceActivity.addPreferencesFromResource(PreferenceActivity.java:1513)
                                                                                at
  com.raj.androidapplication.LoginPrefActivity.onCreate(LoginPrefActivity.java:13)
                                                                                at android.app.Activity.performCreate(Activity.java:6033)
                                                                                at
  android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
                                                                                at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2288)
                                                                                at
  android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2397)
                                                                                at android.app.ActivityThread.access$800(ActivityThread.java:151)
                                                                                at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1310)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:135)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5268)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:902)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:697)
                                                                                Caused by: java.lang.reflect.InvocationTargetException
                                                                                at java.lang.reflect.Constructor.newInstance(Native Method)
                                                                                at java.lang.reflect.Constructor.newInstance(Constructor.java:288)
                                                                                at
  android.preference.GenericInflater.createItem(GenericInflater.java:383)
                                                                                at
  android.preference.GenericInflater.onCreateItem(GenericInflater.java:417)
                                                                                at
  android.preference.GenericInflater.createItemFromTag(GenericInflater.java:428)
                                                                                at
  android.preference.GenericInflater.rInflate(GenericInflater.java:481)
                                                                                at
  android.preference.GenericInflater.rInflate(GenericInflater.java:493)
                                                                                at
  android.preference.GenericInflater.inflate(GenericInflater.java:326)
                                                                                at
  android.preference.GenericInflater.inflate(GenericInflater.java:263)
                                                                                at
  android.preference.PreferenceManager.inflateFromResource(PreferenceManager.java:272)
                                                                                at
  android.preference.PreferenceActivity.addPreferencesFromResource(PreferenceActivity.java:1513)
                                                                                at
  com.raj.androidapplication.LoginPrefActivity.onCreate(LoginPrefActivity.java:13)
                                                                                at android.app.Activity.performCreate(Activity.java:6033)
                                                                                at
  android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
                                                                                at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2288)
                                                                                at
  android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2397)
                                                                                at android.app.ActivityThread.access$800(ActivityThread.java:151)
                                                                                at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1310)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:135)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5268)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:902)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:697)
                                                                                Caused by: java.lang.NullPointerException: Attempt to get length of
  null array
                                                                                at
  android.content.res.AssetManager.getResourceTextArray(AssetManager.java:226)
                                                                                at android.content.res.Resources.getTextArray(Resources.java:518)
                                                                                at android.content.res.TypedArray.getTextArray(TypedArray.java:771)
                                                                                at android.preference.ListPreference.(ListPreference.java:51)
                                                                                at android.preference.ListPreference.(ListPreference.java:65)
                                                                                at android.preference.ListPreference.(ListPreference.java:69)
                                                                                at java.lang.reflect.Constructor.newInstance(Native Method)
                                                                                at java.lang.reflect.Constructor.newInstance(Constructor.java:288)
                                                                                at
  android.preference.GenericInflater.createItem(GenericInflater.java:383)
                                                                                at
  android.preference.GenericInflater.onCreateItem(GenericInflater.java:417)
                                                                                at
  android.preference.GenericInflater.createItemFromTag(GenericInflater.java:428)
                                                                                at
  android.preference.GenericInflater.rInflate(GenericInflater.java:481)
                                                                                at
  android.preference.GenericInflater.rInflate(GenericInflater.java:493)
                                                                                at
  android.preference.GenericInflater.inflate(GenericInflater.java:326)
                                                                                at
  android.preference.GenericInflater.inflate(GenericInflater.java:263)
                                                                                at
  android.preference.PreferenceManager.inflateFromResource(PreferenceManager.java:272)
                                                                                at
  android.preference.PreferenceActivity.addPreferencesFromResource(PreferenceActivity.java:1513)
                                                                                at
  com.raj.androidapplication.LoginPrefActivity.onCreate(LoginPrefActivity.java:13)
                                                                                at android.app.Activity.performCreate(Activity.java:6033)
                                                                                at
  android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
                                                                                at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2288)
                                                                                at
  android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2397)
                                                                                at android.app.ActivityThread.access$800(ActivityThread.java:151)
                                                                                at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1310)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:135)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5268)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:902)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:697)

答:
As per Android Multiple Implementations of one element of the same Layout

File -> Invalidate Cache/ Restart...-> Invalidate and Restart.

should solve the problem

Body:
I am beginner of Android studio. I got issue in layout at android:id with multiple implementation. I searched but it's showing links with- Include same layout multiple times- and Can I use the same id in different layout-Android Multiple Implementations of one element of the same Layout etc.,...

I tried to search on web too but I didn't find related information .The problem is in a layout I have used. The Button id is android:id="@+id/button_actionpage" and also I have used the Button id below in DatePicker Button with android:layout_below="@+id/button_actionpage". So I got a issue in Activity.java with an error                                                                              "java.lang.NullPointerException" due multiple implementation android:id in layout

I can't get a solution about android:id with multiple implementation in layout.

Here is my screen shot

Here is my layout code:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button_store"
        android:text="Store information"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show Information"
        android:id="@+id/button_show"
        android:layout_alignParentTop="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Date:"
        android:id="@+id/date_reg"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ActionPage"
        android:id="@+id/button_actionpage"
        android:layout_marginTop="116dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <DatePicker
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/datePicker"
        android:layout_below="@+id/button_actionpage"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

</RelativeLayout>

Logcat:

07-30 15:58:14.041 29642-29642/com.raj.androidapplication
  E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.raj.androidapplication, PID: 29642
                                                                                java.lang.RuntimeException: Unable to start activity
  ComponentInfo{com.raj.androidapplication/com.raj.androidapplication.LoginPrefActivity}:
  android.view.InflateException: Binary XML file line #25: Error
  inflating class java.lang.reflect.Constructor
                                                                                at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2335)
                                                                                at
  android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2397)
                                                                                at android.app.ActivityThread.access$800(ActivityThread.java:151)
                                                                                at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1310)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:135)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5268)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:902)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:697)
                                                                                Caused by: android.view.InflateException: Binary XML file line #25:
  Error inflating class java.lang.reflect.Constructor
                                                                                at
  android.preference.GenericInflater.createItem(GenericInflater.java:397)
                                                                                at
  android.preference.GenericInflater.onCreateItem(GenericInflater.java:417)
                                                                                at
  android.preference.GenericInflater.createItemFromTag(GenericInflater.java:428)
                                                                                at
  android.preference.GenericInflater.rInflate(GenericInflater.java:481)
                                                                                at
  android.preference.GenericInflater.rInflate(GenericInflater.java:493)
                                                                                at
  android.preference.GenericInflater.inflate(GenericInflater.java:326)
                                                                                at
  android.preference.GenericInflater.inflate(GenericInflater.java:263)
                                                                                at
  android.preference.PreferenceManager.inflateFromResource(PreferenceManager.java:272)
                                                                                at
  android.preference.PreferenceActivity.addPreferencesFromResource(PreferenceActivity.java:1513)
                                                                                at
  com.raj.androidapplication.LoginPrefActivity.onCreate(LoginPrefActivity.java:13)
                                                                                at android.app.Activity.performCreate(Activity.java:6033)
                                                                                at
  android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
                                                                                at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2288)
                                                                                at
  android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2397)
                                                                                at android.app.ActivityThread.access$800(ActivityThread.java:151)
                                                                                at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1310)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:135)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5268)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:902)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:697)
                                                                                Caused by: java.lang.reflect.InvocationTargetException
                                                                                at java.lang.reflect.Constructor.newInstance(Native Method)
                                                                                at java.lang.reflect.Constructor.newInstance(Constructor.java:288)
                                                                                at
  android.preference.GenericInflater.createItem(GenericInflater.java:383)
                                                                                at
  android.preference.GenericInflater.onCreateItem(GenericInflater.java:417)
                                                                                at
  android.preference.GenericInflater.createItemFromTag(GenericInflater.java:428)
                                                                                at
  android.preference.GenericInflater.rInflate(GenericInflater.java:481)
                                                                                at
  android.preference.GenericInflater.rInflate(GenericInflater.java:493)
                                                                                at
  android.preference.GenericInflater.inflate(GenericInflater.java:326)
                                                                                at
  android.preference.GenericInflater.inflate(GenericInflater.java:263)
                                                                                at
  android.preference.PreferenceManager.inflateFromResource(PreferenceManager.java:272)
                                                                                at
  android.preference.PreferenceActivity.addPreferencesFromResource(PreferenceActivity.java:1513)
                                                                                at
  com.raj.androidapplication.LoginPrefActivity.onCreate(LoginPrefActivity.java:13)
                                                                                at android.app.Activity.performCreate(Activity.java:6033)
                                                                                at
  android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
                                                                                at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2288)
                                                                                at
  android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2397)
                                                                                at android.app.ActivityThread.access$800(ActivityThread.java:151)
                                                                                at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1310)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:135)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5268)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:902)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:697)
                                                                                Caused by: java.lang.NullPointerException: Attempt to get length of
  null array
                                                                                at
  android.content.res.AssetManager.getResourceTextArray(AssetManager.java:226)
                                                                                at android.content.res.Resources.getTextArray(Resources.java:518)
                                                                                at android.content.res.TypedArray.getTextArray(TypedArray.java:771)
                                                                                at android.preference.ListPreference.(ListPreference.java:51)
                                                                                at android.preference.ListPreference.(ListPreference.java:65)
                                                                                at android.preference.ListPreference.(ListPreference.java:69)
                                                                                at java.lang.reflect.Constructor.newInstance(Native Method)
                                                                                at java.lang.reflect.Constructor.newInstance(Constructor.java:288)
                                                                                at
  android.preference.GenericInflater.createItem(GenericInflater.java:383)
                                                                                at
  android.preference.GenericInflater.onCreateItem(GenericInflater.java:417)
                                                                                at
  android.preference.GenericInflater.createItemFromTag(GenericInflater.java:428)
                                                                                at
  android.preference.GenericInflater.rInflate(GenericInflater.java:481)
                                                                                at
  android.preference.GenericInflater.rInflate(GenericInflater.java:493)
                                                                                at
  android.preference.GenericInflater.inflate(GenericInflater.java:326)
                                                                                at
  android.preference.GenericInflater.inflate(GenericInflater.java:263)
                                                                                at
  android.preference.PreferenceManager.inflateFromResource(PreferenceManager.java:272)
                                                                                at
  android.preference.PreferenceActivity.addPreferencesFromResource(PreferenceActivity.java:1513)
                                                                                at
  com.raj.androidapplication.LoginPrefActivity.onCreate(LoginPrefActivity.java:13)
                                                                                at android.app.Activity.performCreate(Activity.java:6033)
                                                                                at
  android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
                                                                                at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2288)
                                                                                at
  android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2397)
                                                                                at android.app.ActivityThread.access$800(ActivityThread.java:151)
                                                                                at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1310)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:135)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5268)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:902)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:697)


问:
Need help centering div inside bootstrap columns
I need your help
I'm trying to make a page with a 4 equal width bootstrap columns and a content (let's say a rectangle) inside each of the columns. However, I can't seem to find a way to position each rectangle centrally inside the columns. I need your help to find a way to position the rectangles centrally without ruining the responsive layout of the page.</p>

```<code>    <div class="container-fluid">

    <div class="border row">

    <div class="border col-md-3"><div  class="rectangles"></div></div>

    <div class="border col-md-3"><div  class="rectangles"></div></div>

    <div class="border col-md-3"><div  class="rectangles"></div></div>

    <div class="border col-md-3"><div  class="rectangles"></div></div>

    </div>
    </div>
</code>```

答:
was this what you were looking for? look in full page.

.rectangles1 {
  width: 100px;
  height: 100px;
  background: purple;
  text-align: center;
  margin: auto;
}

.rectangles2 {
  width: 100px;
  height: 100px;
  background: blue;
  text-align: center;
  margin: auto;
}

.rectangles3 {
  width: 100px;
  height: 100px;
  background: green;
  text-align: center;
  margin: auto;
}

.rectangles4 {
  width: 100px;
  height: 100px;
  background: gray;
  text-align: center;
  margin: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="container-fluid">

  <div class="border row">

    <div class="border col-sm-3">
      <div class="rectangles1"></div>
    </div>

    <div class="border col-sm-3">
      <div class="rectangles2"></div>
    </div>

    <div class="border col-sm-3">
      <div class="rectangles3"></div>
    </div>

    <div class="border col-sm-3">
      <div class="rectangles4"></div>
    </div>

  </div>
</div></code>```

Body:
was this what you were looking for? look in full page.

.rectangles1 {
  width: 100px;
  height: 100px;
  background: purple;
  text-align: center;
  margin: auto;
}

.rectangles2 {
  width: 100px;
  height: 100px;
  background: blue;
  text-align: center;
  margin: auto;
}

.rectangles3 {
  width: 100px;
  height: 100px;
  background: green;
  text-align: center;
  margin: auto;
}

.rectangles4 {
  width: 100px;
  height: 100px;
  background: gray;
  text-align: center;
  margin: auto;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="container-fluid">

  <div class="border row">

    <div class="border col-sm-3">
      <div class="rectangles1"></div>
    </div>

    <div class="border col-sm-3">
      <div class="rectangles2"></div>
    </div>

    <div class="border col-sm-3">
      <div class="rectangles3"></div>
    </div>

    <div class="border col-sm-3">
      <div class="rectangles4"></div>
    </div>

  </div>
</div>


问:
navigation bar doesn't show inside popup
I'm using the PopupDialog library and have a button inside it. when user click on this button, I want to open a view controller that has a navigation bar.

my function inside PopupDialog controller :

```<code>func cliclOnContent(tapGestureRecognizer: UITapGestureRecognizer)
{

    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let controller = storyboard.instantiateViewController(withIdentifier: "ContentAJobViewController") as! ContentAJobViewController
    controller.job_id = self.gh.id
    self.present(controller, animated: true, completion: nil)

}
</code>```

but when my controller shows view (ContentAJobViewController), my navigation bar is hide:

my library link:
https://github.com/Orderella/PopupDialog

答: in order to keep the current navigation controller you must use self.show(controller, sender: self). But I don't understand where you are using the PopupDialog in this case.

Body:
I'm using the PopupDialog library and have a button inside it. when user click on this button, I want to open a view controller that has a navigation bar.

my function inside PopupDialog controller :

func cliclOnContent(tapGestureRecognizer: UITapGestureRecognizer)
{

    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let controller = storyboard.instantiateViewController(withIdentifier: "ContentAJobViewController") as! ContentAJobViewController
    controller.job_id = self.gh.id
    self.present(controller, animated: true, completion: nil)

}

but when my controller shows view (ContentAJobViewController), my navigation bar is hide:

my library link:
https://github.com/Orderella/PopupDialog


问:
How to solve "multiple definition of `__vector_32'" error?
I am working on an Arduino Mega 2560 project involving infrared signal processing and controlling servos. But the following simple sketch produces an error, saying that some field is multiple times defined.

Libraries involved: Servo and IRremote.

Code for reproducing the error:

```<code>#include <Servo.h>
#include <IRremote.h>

void setup() { }

void loop() { }
</code>```

Error description:

```<code>libraries\IRremote\IRremote.cpp.o (symbol from plugin): In function `MATCH(int, int)':

(.text+0x0): multiple definition of `__vector_32'

libraries\Servo\avr\Servo.cpp.o (symbol from plugin):(.text+0x0): first defined here

c:/arduino/hardware/tools/avr/bin/../lib/gcc/avr/4.9.2/../../../../avr/bin/ld.exe: Disabling relaxation: it will not work with multiple definitions

collect2.exe: error: ld returned 1 exit status

exit status 1
Error compiling for board Arduino/Genuino Mega or Mega 2560.
</code>```

How do I solve this issue?

UPDATE/SOLUTION:

The servo library has the following definition in ServoTimers.h:

```<code>typedef enum { _timer5, _timer1, _timer3, _timer4, _Nbr_16timers } timer16_Sequence_t;
</code>```

Basically, the first 12 servos are controlled by timer 5. If you need more servos, timer 1 is also consulted for servo 13-24, etc. Up to 48 servos can be controlled by the standard servo library on a Arduino Mega 2560 (12 per timer).

The IRremote library uses timer 2 for receiving IR signals. This basically does not conflict with the Servo library. But I already altered the IRremoteInt.h to use timer 3 instead of timer 2, since I also use ultrasonic sensors which are interrupt driven (on timer 2). That's the reason why I ran into the issue described above.

Since I am not using more than 12 servos for my project, I simply disabled the timers 1, 3, 4 in the Servo library, resulting in the following line (cp. to the original line above):

```<code>typedef enum { _timer5, _Nbr_16timers } timer16_Sequence_t;
</code>```

This results in some more errors, since the enum is not complete anymore... If you want do the same, just comment out the lines of code that pop up as error when you try to compile the sketch. Then re-compile and everything should be fine.

Now everything working fine, ultrasonic sensors, servos and IR reception. Thanks.

答: Servo.h and IRremote.h are both trying to use Timer1.  They can't both have it, hence the error.  You could try the ServoTimer2 library to run the servos off timer 2 but be sure you read the documentation for it as it doesn't work exactly like Servo.  </p>

Body:
I am working on an Arduino Mega 2560 project involving infrared signal processing and controlling servos. But the following simple sketch produces an error, saying that some field is multiple times defined.

Libraries involved: Servo and IRremote.

Code for reproducing the error:

#include <Servo.h>
#include <IRremote.h>

void setup() { }

void loop() { }

Error description:

libraries\IRremote\IRremote.cpp.o (symbol from plugin): In function `MATCH(int, int)':

(.text+0x0): multiple definition of `__vector_32'

libraries\Servo\avr\Servo.cpp.o (symbol from plugin):(.text+0x0): first defined here

c:/arduino/hardware/tools/avr/bin/../lib/gcc/avr/4.9.2/../../../../avr/bin/ld.exe: Disabling relaxation: it will not work with multiple definitions

collect2.exe: error: ld returned 1 exit status

exit status 1
Error compiling for board Arduino/Genuino Mega or Mega 2560.

How do I solve this issue?

UPDATE/SOLUTION:

The servo library has the following definition in ServoTimers.h:

typedef enum { _timer5, _timer1, _timer3, _timer4, _Nbr_16timers } timer16_Sequence_t;

Basically, the first 12 servos are controlled by timer 5. If you need more servos, timer 1 is also consulted for servo 13-24, etc. Up to 48 servos can be controlled by the standard servo library on a Arduino Mega 2560 (12 per timer).

The IRremote library uses timer 2 for receiving IR signals. This basically does not conflict with the Servo library. But I already altered the IRremoteInt.h to use timer 3 instead of timer 2, since I also use ultrasonic sensors which are interrupt driven (on timer 2). That's the reason why I ran into the issue described above.

Since I am not using more than 12 servos for my project, I simply disabled the timers 1, 3, 4 in the Servo library, resulting in the following line (cp. to the original line above):

typedef enum { _timer5, _Nbr_16timers } timer16_Sequence_t;

This results in some more errors, since the enum is not complete anymore... If you want do the same, just comment out the lines of code that pop up as error when you try to compile the sketch. Then re-compile and everything should be fine.

Now everything working fine, ultrasonic sensors, servos and IR reception. Thanks.


问:
Ruby on Rails: split string into hash and insert it to a json
I have a model that looks something like:

```<code>  :created_at => Tue, 06 Jun 2017 15:34:32 UTC +00:00,
  :updated_at => Tue, 06 Jun 2017 15:34:35 UTC +00:00,
     :metrics => {
                "metric_a" => 10756,
                "metric_b" => "",
                "metric_c" => 6.67267607666759
},
  :status => "working"
</code>```

With the  metrics field as a json.

And I want to split a string such as:

```<code>"Home/Personal Finance=37.00%=55,Computers/Internet/Web Design and Development=13.77%=48,News=8.64%=45,Arts/Television=5.23%=42,Arts/Music=2.99%=39,News/Current Events=2.66%=38,Society/Issues=2.47%=38,Computers/Internet/On the Web=2.46%=38,Business/Investing=1.76%=36,Society=1.70%=36"
</code>```

To be named categories under the metrics field so that each category will hold two numbers, the percentage and the number that follows it.
So in the example above it would look like:

```<code>  :created_at => Tue, 06 Jun 2017 15:34:32 UTC +00:00,
  :updated_at => Tue, 06 Jun 2017 15:34:35 UTC +00:00,
     :metrics => {
                "metric_a" => 10756,
                "metric_b" => "",
                "metric_c" => 6.67267607666759
                "categories" => {
            "Home/Personal Finance": [37.00,55],
            "Computers/Internet/Web Design and Development": [13.77,48],
            ...
            }

},
  :status => "working"
</code>```

Basically I want to save the two numbers for each category (maybe there's a better way to store them by the way?).

Either way can split the string with .split(",") but what next?

答:
You could use regex for this, or something like this:

str="Home/Personal Finance=37.00%=55,Computers/Internet/Web Design and Development=13.77%=48,News=8.64%=45,Arts/Television=5.23%=42,Arts/Music=2.99%=39,News/Current Events=2.66%=38,Society/Issues=2.47%=38,Computers/Internet/On the Web=2.46%=38,Business/Investing=1.76%=36,Society=1.70%=36"

categories = {}

str = str.split(',').each do |category|

    parts = category.split('=')

    # Parts:
    #   0: Home/Personal Finance
    #   1: 37.00%
    #   2: 55

    key = parts[0]
    first_number = Float(parts[1].gsub('%', ''))
    last_number = parts[2].to_i

    categories[key] = [first_number, last_number]

end
```

Body:
I have a model that looks something like:

  :created_at => Tue, 06 Jun 2017 15:34:32 UTC +00:00,
  :updated_at => Tue, 06 Jun 2017 15:34:35 UTC +00:00,
     :metrics => {
                "metric_a" => 10756,
                "metric_b" => "",
                "metric_c" => 6.67267607666759
},
  :status => "working"

With the  metrics field as a json.

And I want to split a string such as:

"Home/Personal Finance=37.00%=55,Computers/Internet/Web Design and Development=13.77%=48,News=8.64%=45,Arts/Television=5.23%=42,Arts/Music=2.99%=39,News/Current Events=2.66%=38,Society/Issues=2.47%=38,Computers/Internet/On the Web=2.46%=38,Business/Investing=1.76%=36,Society=1.70%=36"

To be named categories under the metrics field so that each category will hold two numbers, the percentage and the number that follows it.
So in the example above it would look like:

  :created_at => Tue, 06 Jun 2017 15:34:32 UTC +00:00,
  :updated_at => Tue, 06 Jun 2017 15:34:35 UTC +00:00,
     :metrics => {
                "metric_a" => 10756,
                "metric_b" => "",
                "metric_c" => 6.67267607666759
                "categories" => {
            "Home/Personal Finance": [37.00,55],
            "Computers/Internet/Web Design and Development": [13.77,48],
            ...
            }

},
  :status => "working"

Basically I want to save the two numbers for each category (maybe there's a better way to store them by the way?).

Either way can split the string with .split(",") but what next?


问:
I am having problems with "error ';' expected"
Im having problem with this code. The console shows this error to me and I cannot figure it out. "file.java on line 7: error: ';' expected"

```<code>int adjacentElementsProduct(int[] inputArray) {
    int numberofElements = inputArray.length();
    int [] products = new int [numberofElements];
    for (int firstNumber = 0; numberofElements > firstNumber; firstNumber++) {
         products [firstNumber] = product (inputArray [firstNumber], inputArray [1+firstNumber]);
    };
    int maxValue () {
        int x = products [0];
        for (int i = 1; i < products.length; i++) {
            if (products [i] > x){
                x = products [i];
            }
        }
        return x;
    }
    return maxValue;
}
</code>```

If anyone could help me with this, I would really appreciate.
Thank you.

答:
To put everyone's comments into words.  Arrays use a data field to access length, because it is not a method you don't use ().

```<code>array.length
</code>```

Next thing is your for loop has a semicolon at the end of the last bracket which prevents it from even happening.  So take that out.

Next you can't declare a method inside of another method.  Write the second method outside this method and then call it inside the other one.

Next you cant call the method nextValue like you did.  Even though you can't put it there to call it you have to call it like so:

What you did:

```<code>return maxValue;
</code>```

What you should do:

```<code>/*something*/.nextValue();
</code>```

Fix these things and you should get rid of the errors.

Body:
Im having problem with this code. The console shows this error to me and I cannot figure it out. "file.java on line 7: error: ';' expected"

int adjacentElementsProduct(int[] inputArray) {
    int numberofElements = inputArray.length();
    int [] products = new int [numberofElements];
    for (int firstNumber = 0; numberofElements > firstNumber; firstNumber++) {
         products [firstNumber] = product (inputArray [firstNumber], inputArray [1+firstNumber]);
    };
    int maxValue () {
        int x = products [0];
        for (int i = 1; i < products.length; i++) {
            if (products [i] > x){
                x = products [i];
            }
        }
        return x;
    }
    return maxValue;
}

If anyone could help me with this, I would really appreciate.
Thank you.

Body:
To put everyone's comments into words.  Arrays use a data field to access length, because it is not a method you don't use ().

array.length

Next thing is your for loop has a semicolon at the end of the last bracket which prevents it from even happening.  So take that out.

Next you can't declare a method inside of another method.  Write the second method outside this method and then call it inside the other one.

Next you cant call the method nextValue like you did.  Even though you can't put it there to call it you have to call it like so:

What you did:

return maxValue;

What you should do:

/*something*/.nextValue();

Fix these things and you should get rid of the errors.


问:
Python 2.7.11 in Visual Studio Throws Exception in cElementTree.py
I'm coding Python in Visual Studio 2015 which has worked great for the past few days, however this morning I decided to move the solution and directory to a GitHub-monitored directory on my Windows machine. Ever since I moved the solution and run it in debug mode, it throws this message:

un(shallow)copyable object of type <type 'element'>

I'm completely stumped because there's no class named cElementTree.py in my project; it's actually here:

```<code>C:\Program Files (x86)\Python\2_7_11\Lib\xml\etree
</code>```

I can run the code in the original location just fine, so something was messed up in transit. I've copied it multiple times and it keeps throwing that exception. How can I resolve that error?

答: Try the "continue" option in the menu bar. It should run just fine, even if the location of the file has been changed.</p>

Body:
I'm coding Python in Visual Studio 2015 which has worked great for the past few days, however this morning I decided to move the solution and directory to a GitHub-monitored directory on my Windows machine. Ever since I moved the solution and run it in debug mode, it throws this message:

un(shallow)copyable object of type <type 'element'>

I'm completely stumped because there's no class named cElementTree.py in my project; it's actually here:

C:\Program Files (x86)\Python\2_7_11\Lib\xml\etree

I can run the code in the original location just fine, so something was messed up in transit. I've copied it multiple times and it keeps throwing that exception. How can I resolve that error?


答: You'll probably need to change the form and/or create template manually to contain a password_confirmation field. Look more closely at the has_secure_password docs maybe?

Title: has_secure_password, wont create attributes

Body:
I am trying to use has_secure_password and bcrypt (3.1.11) on my Rails app.

Here is my setup on Ubuntu:

I installed bcrypt with no issues and have it in my gem file

I have a password_digest:string for my users migrated in the database

I added has_secure_password to my user model

I am getting no errors, however when I go to create a user, it is asking me for a password_digest attribute instead of password and password_confirmation.

why is this? Shouldn't the has_secure_password automatically change the user to need a password and password_confirmation instead of password_digest?


问:
How tf.nn.dynamic_rnn works with different lengths of inputs sepcially when working with seq2seq?
Here I am asking how the dynamic behavior work.
This is the tensorflow documentation for above dynamic_rnn function. What is the maximum length of RNN input blocks that this function create? Will it pad all shorter ones according to the largest input?</p>

答:
It is your responsibility to pad the sequences, and then supply the sequences lengths.

For example:

```<code># Create input data
X = np.random.randn(2, 10, 8)

# The second example is of length 6
X[1,6:] = 0
X_lengths = [10, 6]

cell = tf.nn.rnn_cell.LSTMCell(num_units=64, state_is_tuple=True)

outputs, last_states = tf.nn.dynamic_rnn(
    cell=cell,
    dtype=tf.float64,
    sequence_length=X_lengths,
    inputs=X)
</code>```

Here you can see, we pad the sequences ourselves  X[1,6:] = 0 will assign 0 to all of the values after the 6th element, that means this sequence is of length 6 and we state so by giving X_lengths 2nd value the value 6

Body:
It is your responsibility to pad the sequences, and then supply the sequences lengths.

For example:

# Create input data
X = np.random.randn(2, 10, 8)

# The second example is of length 6
X[1,6:] = 0
X_lengths = [10, 6]

cell = tf.nn.rnn_cell.LSTMCell(num_units=64, state_is_tuple=True)

outputs, last_states = tf.nn.dynamic_rnn(
    cell=cell,
    dtype=tf.float64,
    sequence_length=X_lengths,
    inputs=X)

Here you can see, we pad the sequences ourselves  X[1,6:] = 0 will assign 0 to all of the values after the 6th element, that means this sequence is of length 6 and we state so by giving X_lengths 2nd value the value 6


问:
I need a language dictionary
I need to add dictionary facilities to an Asp.net MVC app. Does anyone know a library that I could use? Where can I get word definitions from?

Any help is appreciated.

答:
If its still relevant for you, It's not a 'library' but on Dicts.info site you can find raw dictionary files you could use inside your application.

You can also find bilingual dictionaries for various languages or even categorized vocabulary, and even more...

Watch out to respect their respective licences.

ContentLicense: CC BY-SA 2.5

Title: I need a language dictionary


问:
how to wait for a specific command to finish in selenium
I'm trying to get some info from pages that look like this link to the site

I need to scroll all the way down, I wrote a function for that.

```<code>def Scroll():
    startPos = driver.execute_script("return window.pageYOffset;")
    while 1:
        driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") #need to wait
        time.sleep(0.1)
        newPos = driver.execute_script("return window.pageYOffset;")
        if newPos == startPos:
            break
        startPos = newPos
return
</code>```

I would like to change time.sleep(0.1) with some conditional wait until the line before that one is executed, is there a way to do this? There is no special element loaded after every scroll or at the end of the page.

Solution:

```<code>...
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
while 1:
    if driver.execute_script("return jQuery.active == 0"):
        break
    else:
        time.sleep(0.05)
        continue
...
</code>```

答:
Instead of thread.sleep, you can use following code which waits for Ajax calls to complete because every scroll, there will be a Ajax call in the background.

```<code>WebDriverWait wait=new WebDriverWait(driver, 120);
</code>```

Wait.until(ExpectedConditions.jsReturnValue("return jQuery.active == 0"));

Body:
I'm trying to get some info from pages that look like this link to the site

I need to scroll all the way down, I wrote a function for that.

def Scroll():
    startPos = driver.execute_script("return window.pageYOffset;")
    while 1:
        driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") #need to wait
        time.sleep(0.1)
        newPos = driver.execute_script("return window.pageYOffset;")
        if newPos == startPos:
            break
        startPos = newPos
return

I would like to change time.sleep(0.1) with some conditional wait until the line before that one is executed, is there a way to do this? There is no special element loaded after every scroll or at the end of the page.

Solution:

...
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
while 1:
    if driver.execute_script("return jQuery.active == 0"):
        break
    else:
        time.sleep(0.05)
        continue
...

Body:
Instead of thread.sleep, you can use following code which waits for Ajax calls to complete because every scroll, there will be a Ajax call in the background.

WebDriverWait wait=new WebDriverWait(driver, 120);

Wait.until(ExpectedConditions.jsReturnValue("return jQuery.active == 0"));


问:
Can I check for numeric input only in javascript?
I am checking if a input field is empty but would like to check if it is numeric since it is a street address. I only want numeric to be allowed, no alpha even though an address might be like 123a or something else.

I want to keep the same format cause I'm checking other fields in the same function and want it to be the same. Below is what I have for empty field. What is the easiest way to change it to check for numeric only. I was trying if( !isNumeric (numbr.value)) but it isn't working.

```<code>var numbr = document.getElementById( "numbr" );
if( numbr.value == "")  {
    error = "Address number must be entered. Numeric only.";
    document.getElementById( "error_para" ).innerHTML = error;
    return false;
    }
</code>```

答:
You could also use parseInt and check if it is NotANumber:

window.onload=function(){

    document.getElementById("numbr").addEventListener("input",function(){
    document.getElementById( "error_para" ).innerHTML = (isNaN(parseInt(this.value,10)))?"Address number must be entered. Numeric only.":"";
    });

  };```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="numbr">
<div id="error_para"></div></code>```

Body:
I am checking if a input field is empty but would like to check if it is numeric since it is a street address. I only want numeric to be allowed, no alpha even though an address might be like 123a or something else.

I want to keep the same format cause I'm checking other fields in the same function and want it to be the same. Below is what I have for empty field. What is the easiest way to change it to check for numeric only. I was trying if( !isNumeric (numbr.value)) but it isn't working.

var numbr = document.getElementById( "numbr" );
if( numbr.value == "")  {
    error = "Address number must be entered. Numeric only.";
    document.getElementById( "error_para" ).innerHTML = error;
    return false;
    }

Body:
You could also use parseInt and check if it is NotANumber:

window.onload=function(){

    document.getElementById("numbr").addEventListener("input",function(){
    document.getElementById( "error_para" ).innerHTML = (isNaN(parseInt(this.value,10)))?"Address number must be entered. Numeric only.":"";
    });

  };

<input id="numbr">
<div id="error_para"></div>


问:
Searching for something in Database (2) - SELECT - Need to search in 2 tables

As you can see in the print screen above, I am wondering, if it is possible to check if there is one thing in two tables at once WITH gaining whole one row if found (logical 1). Without making 2 queries. I need to look, if "fajne-to-jest" is in table1 or table2, and then take data row. I'm doing it in 2 queries... but question is, is it possible to check this information using one query? Mabye something else? Most efficent way? The best way?

@Gordon Linoff gave me this:

```<code>select (exists (select 1 from table1 where url = 'fajne-to-jest')) as in_table1,
       (exists (select 1 from table2 where url = 'fajne-to-jest')) as in_table2;
</code>```

But this produces:

And I want query to produce this + data from this row, like this:

答:
Here's a quick stab at this, haven't tested it at all:

```<code>select
    IF(table1.id IS NULL, 0, 1) as table1,
    IF(table2.id IS NULL, 0, 1) as table2,
    COALESCE(table1.id, table2.id, "NONE") as id,
    `master`.url
from
(select 'fajne-to-jest' as url)  `master`
left join table1 on table1.url = `master`.url
left join table2 on table2.url = `master`.url
;
</code>```

Should always give a single row, whether it's found in 0,1, or both tables.  You said url is unique so shouldn't need to worry about repeats, but if IDs don't match then this favors table1 (and prints "NONE" if not in either table).

Body:
As you can see in the print screen above, I am wondering, if it is possible to check if there is one thing in two tables at once WITH gaining whole one row if found (logical 1). Without making 2 queries. I need to look, if "fajne-to-jest" is in table1 or table2, and then take data row. I'm doing it in 2 queries... but question is, is it possible to check this information using one query? Mabye something else? Most efficent way? The best way?

@Gordon Linoff gave me this:

select (exists (select 1 from table1 where url = 'fajne-to-jest')) as in_table1,
       (exists (select 1 from table2 where url = 'fajne-to-jest')) as in_table2;

But this produces:

And I want query to produce this + data from this row, like this:

Body:
Here's a quick stab at this, haven't tested it at all:

select
    IF(table1.id IS NULL, 0, 1) as table1,
    IF(table2.id IS NULL, 0, 1) as table2,
    COALESCE(table1.id, table2.id, "NONE") as id,
    `master`.url
from
(select 'fajne-to-jest' as url)  `master`
left join table1 on table1.url = `master`.url
left join table2 on table2.url = `master`.url
;

Should always give a single row, whether it's found in 0,1, or both tables.  You said url is unique so shouldn't need to worry about repeats, but if IDs don't match then this favors table1 (and prints "NONE" if not in either table).


问:
help, stored procedures and cursors
i have to write a stored procedure, where you give the month, and a credit card number, and it calulates 1%  for each transaction made in the first 10 days of the month, 2% for transactions between 10 and 20, and 3% for transactions above 20.
And i must use cursors.

i wrote this code, but i get some errors when i try to run the precedure

```<code>   create procedure cardP
   /* month ex 1,3,5 etc*/
   @minas int,
   @cardNo bigint

as
/* creating the cursor*/
DECLARE sinallages CURSOR
FOR SELECT cc_number,day([DateTime]),charged_amount FROM transactions
where cc_number=@cardNo and month([DateTime])=@minas

/* declaring local variables*/
declare @poso int,@karta bigint,@mera int,@pos float,@pos2 float,@pos3 float,
@count int,@counter int

open sinallages

set @count=(select count(cc_number) from transactions where cc_number=@cardNo and month([DateTime])=@minas )
/* get 1st row*/
fetch sinallages into @karta,@mera,@poso
while (/*@@sqlstatus != 2*/@counter<@count)
  begin
    if day(@mera)<=10
    set @pos =@poso+ @poso * 0.01
    else
    if day(@mera)>10 and day(@mera)<=20
    set @pos2 =@poso+ @poso * 0.02
    else
    if day(@mera) > 20
    set @pos3 =@poso+ @poso * 0.03
    fetch sinallages into @karta,@mera,@poso
  set @counter=@counter+1
  end

close sinallages

return
</code>```

when i call the procedure i get

EXEC cardP @minas = 5, @cardNo =4929569752542450

```<code>Msg 16915, Level 16, State 1, Procedure cardP, Line 20
A cursor with the name 'sinallages' already exists.
Msg 16922, Level 16, State 1, Procedure cardP, Line 31
</code>```

Cursor Fetch: Implicit conversion from data type datetime to int is not allowed.

thank you :) i now deallocate the cursor at the end of the stored procedure and removed the day(). Now i want to print the pos+pos2+pos3. I use print  pos+pos2+pos3  but it doesnt print anything. why is that ??

```<code>    ................
      set @counter=@counter+1
  end
print @pos+@pos2+@pos3
close sinallages

return
DEALLOCATE sinallages;
</code>```

it seems like hte variables po,pos2,pos3 are left null??

答:
you have to dealocate the cursor after closing it:

```<code>DEALLOCATE sinallages
</code>```

http://msdn.microsoft.com/en-us/library/ms188782.aspx

Title: help, stored procedures and cursors

Body:
i have to write a stored procedure, where you give the month, and a credit card number, and it calulates 1%  for each transaction made in the first 10 days of the month, 2% for transactions between 10 and 20, and 3% for transactions above 20.
And i must use cursors.

i wrote this code, but i get some errors when i try to run the precedure

   create procedure cardP
   /* month ex 1,3,5 etc*/
   @minas int,
   @cardNo bigint

as
/* creating the cursor*/
DECLARE sinallages CURSOR
FOR SELECT cc_number,day([DateTime]),charged_amount FROM transactions
where cc_number=@cardNo and month([DateTime])=@minas

/* declaring local variables*/
declare @poso int,@karta bigint,@mera int,@pos float,@pos2 float,@pos3 float,
@count int,@counter int

open sinallages

set @count=(select count(cc_number) from transactions where cc_number=@cardNo and month([DateTime])=@minas )
/* get 1st row*/
fetch sinallages into @karta,@mera,@poso
while (/*@@sqlstatus != 2*/@counter<@count)
  begin
    if day(@mera)<=10
    set @pos =@poso+ @poso * 0.01
    else
    if day(@mera)>10 and day(@mera)<=20
    set @pos2 =@poso+ @poso * 0.02
    else
    if day(@mera) > 20
    set @pos3 =@poso+ @poso * 0.03
    fetch sinallages into @karta,@mera,@poso
  set @counter=@counter+1
  end

close sinallages

return

when i call the procedure i get

EXEC cardP @minas = 5, @cardNo =4929569752542450

Msg 16915, Level 16, State 1, Procedure cardP, Line 20
A cursor with the name 'sinallages' already exists.
Msg 16922, Level 16, State 1, Procedure cardP, Line 31

Cursor Fetch: Implicit conversion from data type datetime to int is not allowed.

thank you :) i now deallocate the cursor at the end of the stored procedure and removed the day(). Now i want to print the pos+pos2+pos3. I use print  pos+pos2+pos3  but it doesnt print anything. why is that ??

    ................
      set @counter=@counter+1
  end
print @pos+@pos2+@pos3
close sinallages

return
DEALLOCATE sinallages;

it seems like hte variables po,pos2,pos3 are left null??

Body:
you have to dealocate the cursor after closing it:

DEALLOCATE sinallages

http://msdn.microsoft.com/en-us/library/ms188782.aspx