问:
c remove new line char help
Im fairly new to c sorry if this is a stupid question!

i have this:

```<code>  fgets(question,200,stdin);
  char *memq = malloc(sizeof(strlen(question)));
  memq= question;
</code>```

however the question variable always has a new line on the end of it !
how do i remove this / prevent it happening?

i have tried this:

```<code>  fgets(question,200,stdin);
  char *memq = malloc(sizeof(strlen(question))-sizeof(char));
  memq= question;
</code>```

there was no effect!

答:
This code is badly broken.

You need to allocate strlen+1 bytes into memq if you plan to copy the data there (why are you doing sizeof?  that will allocate 4 bytes since sizeof(strlen()) is sizeof(int)).

You cannot just assign question to memq and expect the data to be copied in.  All this does is overwrite the pointer you just malloc-ed into memq, leaking it.  You have to do

```<code>strcpy(memq, question);
</code>```

That's why you need the extra byte in memq, since this includes a null terminator. At this point you are in position to remove the newline from memq as noted elsewhere.

Title: c remove new line char help

Body:
Im fairly new to c sorry if this is a stupid question!

i have this:

  fgets(question,200,stdin);
  char *memq = malloc(sizeof(strlen(question)));
  memq= question;

however the question variable always has a new line on the end of it !
how do i remove this / prevent it happening?

i have tried this:

  fgets(question,200,stdin);
  char *memq = malloc(sizeof(strlen(question))-sizeof(char));
  memq= question;

there was no effect!

Body:
This code is badly broken.

You need to allocate strlen+1 bytes into memq if you plan to copy the data there (why are you doing sizeof?  that will allocate 4 bytes since sizeof(strlen()) is sizeof(int)).

You cannot just assign question to memq and expect the data to be copied in.  All this does is overwrite the pointer you just malloc-ed into memq, leaking it.  You have to do

strcpy(memq, question);

That's why you need the extra byte in memq, since this includes a null terminator. At this point you are in position to remove the newline from memq as noted elsewhere.


来源: stackexchange

问:
Spring Data JPA Relationship Annotations
I'm learning Spring Data JPA and having some trouble establishing the relationship between these two tables:

product table with columns id, name, product_type_id

product_type table with columns id, name

A product can have only one type.  A type can be associated with many products.

Where would I use the @OnetoMany and @ManytoOne annotations in my entity classes?

答:
Entity Product should have field ProductType with annotation @ManyToOne.
Entity ProductType should have field Set with annotation @OneToMany(mappedBy = 'productType')</p>

ContentLicense: CC BY-SA 3.0


问:
Multiple OR in SQL string Variable, VBA
I am using a bit a code to Adjust form length and an SQL variable to modify the names that show up in a Combobox. I want to make sure that the names in the Comboboxes above the one that is being worked on, do not show any names.
So if Combo1 has 40 names then Combo2 will only have 39 and so on.
My problem seems to be when I use multiple "OR" within the WHERE Clause of the SQL String. Can anyone advice?

```<code>Private Sub Worker3_Change()
Dim Worker4STR As String

'Shows Worker 4

Me.Worker4.RowSource = ""
Worker4STR = "SELECT T1Workers.NonUserID, T1Workers.[FirstName] & "" "" & [LastName] AS FullName FROM T1Workers WHERE T1Workers.NonUserID <>" & _
              Me.Worker1.Value & " OR " & Me.Worker2.Value & " Or " & Me.Worker3.Value
Me.Worker4.RowSource = Worker4STR

Me.Worker4.AllowValueListEdits = False
Me.Worker4.ColumnCount = 2
Me.Worker4.ColumnWidths = "0, "

Me.Worker4.Visible = True
Me.Activity4.Visible = True
Me.w4a1s.Visible = True
Me.w4a1d.Visible = True
Me.w4a1o.Visible = True
Me.w4a2s.Visible = True
Me.w4a2o.Visible = True
Me.w4a2d.Visible = True
Me.w4a3s.Visible = True
Me.w4a3o.Visible = True
Me.w4a3d.Visible = True
Me.w4a4s.Visible = True
Me.w4a4o.Visible = True
Me.w4a4d.Visible = True
Me.w4a5s.Visible = True
Me.w4a5o.Visible = True
Me.w4a5d.Visible = True
Me.InsideHeight = 1440 * 4.6

End Sub
</code>```

Thank you in Advance.
-Matt

答:
Your clause:

```<code>X <> A OR B OR C
</code>```

Is not valid SQL.  You can use NOT IN instead:

```<code>"WHERE T1Workers.NonUserID NOT IN (" & _
              Me.Worker1.Value & " , " & _
              Me.Worker2.Value & " , " & _
              Me.Worker3.Value & " ) "
</code>```

Note that if the values are strings they at a minimum need to be enclosed in quotes.  A much better solution is to use SQL parameters instead, but I do not know if that's possible with whatever Worker4 is.

Title: Multiple OR in SQL string Variable, VBA

Body:
I am using a bit a code to Adjust form length and an SQL variable to modify the names that show up in a Combobox. I want to make sure that the names in the Comboboxes above the one that is being worked on, do not show any names.
So if Combo1 has 40 names then Combo2 will only have 39 and so on.
My problem seems to be when I use multiple "OR" within the WHERE Clause of the SQL String. Can anyone advice?

Private Sub Worker3_Change()
Dim Worker4STR As String

'Shows Worker 4

Me.Worker4.RowSource = ""
Worker4STR = "SELECT T1Workers.NonUserID, T1Workers.[FirstName] & "" "" & [LastName] AS FullName FROM T1Workers WHERE T1Workers.NonUserID <>" & _
              Me.Worker1.Value & " OR " & Me.Worker2.Value & " Or " & Me.Worker3.Value
Me.Worker4.RowSource = Worker4STR

Me.Worker4.AllowValueListEdits = False
Me.Worker4.ColumnCount = 2
Me.Worker4.ColumnWidths = "0, "

Me.Worker4.Visible = True
Me.Activity4.Visible = True
Me.w4a1s.Visible = True
Me.w4a1d.Visible = True
Me.w4a1o.Visible = True
Me.w4a2s.Visible = True
Me.w4a2o.Visible = True
Me.w4a2d.Visible = True
Me.w4a3s.Visible = True
Me.w4a3o.Visible = True
Me.w4a3d.Visible = True
Me.w4a4s.Visible = True
Me.w4a4o.Visible = True
Me.w4a4d.Visible = True
Me.w4a5s.Visible = True
Me.w4a5o.Visible = True
Me.w4a5d.Visible = True
Me.InsideHeight = 1440 * 4.6

End Sub

Thank you in Advance.
-Matt

Body:
Your clause:

X <> A OR B OR C

Is not valid SQL.  You can use NOT IN instead:

"WHERE T1Workers.NonUserID NOT IN (" & _
              Me.Worker1.Value & " , " & _
              Me.Worker2.Value & " , " & _
              Me.Worker3.Value & " ) "

Note that if the values are strings they at a minimum need to be enclosed in quotes.  A much better solution is to use SQL parameters instead, but I do not know if that's possible with whatever Worker4 is.


问:
How to filter objects by price range in Django?
I have a model Item with field price.

```<code>class Item(models.Model):
    title = models.CharField(max_length=200, blank='true')
    price = models.IntegerField(default=0)
</code>```

My query may contain min_price & max_price values. So, my request may be like this: http://example.com/api/items?min_price=50&max_price=500. Can anybody tell me, how can I query items between min & max values? Can I solve it using Django ORM?

Thanks!

答:
Check api reference for range. Like it states

You can use range anywhere you can use BETWEEN in SQL — for dates,
  numbers and even characters.

So, in your case:

```<code>Item.objects.filter(price__range=(min_price, max_price))
</code>```

Body:
I have a model Item with field price.

class Item(models.Model):
    title = models.CharField(max_length=200, blank='true')
    price = models.IntegerField(default=0)

My query may contain min_price & max_price values. So, my request may be like this: http://example.com/api/items?min_price=50&max_price=500. Can anybody tell me, how can I query items between min & max values? Can I solve it using Django ORM?

Thanks!

Body:
Check api reference for range. Like it states

You can use range anywhere you can use BETWEEN in SQL — for dates,
  numbers and even characters.

So, in your case:

Item.objects.filter(price__range=(min_price, max_price))


问:
Launch Mailchimp evil popup onclick
Styling

```<code><link href="//cdn-images.mailchimp.com/embedcode/classic-081711.css" rel="stylesheet" type="text/css">
<style type="text/css">
    #mc_embed_signup{position:absolute; top:0; left:0; width:100%; height:100%; background-color:rgba(0,0,0,.8);display:none;z-index:10000; }
    #mc_embed_signup form{position:fixed; top:10%; left:50%; width:50%; margin-left:-25%; font:normal 100% Helvetica,Arial,sans-serif; font-size:14px; border-radius:4px; border:none; padding:10px 20px; background-color:#fff; color:#000; text-align:left;max-height:400px;overflow-y:auto;overflow-x:hidden;}
    #mc_embed_signup a.mc_embed_close{background:transparent url(http://downloads.mailchimp.com/img/closebox.png) no-repeat; display:block; height:30px; width:30px; text-indent:-999em; position:absolute; top:-10px; right:-10px; display:none; }
    /* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
       We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
</style>
</code>```

HTML

```<code><div id="mc_embed_signup">
<form action="http://zehava.us3.list-manage2.com/subscribe/post?u=fc807e12a60c9cbaaf5f5616e&id=0707dfe742" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
    <h2>We want to share with you the newest ZEHAVA creations! Leave us your email address! With this occasion, ZEHAVA offers you a gift: a free recondition of your favorite jewelry.</h2>
<div class="indicates-required"><span class="asterisk">*</span> indicates required</div>
<div class="mc-field-group">
    <label for="mce-EMAIL">Email Address  <span class="asterisk">*</span>
</label>
    <input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL">
</div>
<div class="mc-field-group">
    <label for="mce-FNAME">First Name  <span class="asterisk">*</span>
</label>
    <input type="text" value="" name="FNAME" class="required" id="mce-FNAME">
</div>
<div class="mc-field-group">
    <label for="mce-LNAME">Last Name </label>
    <input type="text" value="" name="LNAME" class="" id="mce-LNAME">
</div>
<a href="#" id="mc_embed_close" class="mc_embed_close">Close</a>    <div id="mce-responses" class="clear">
        <div class="response" id="mce-error-response" style="display:none"></div>
        <div class="response" id="mce-success-response" style="display:none"></div>
    </div>  <div class="clear"><input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
</form>
</div>
</code>```

Javascript

```<code><script type="text/javascript">
var fnames = new Array();var ftypes = new Array();fnames[0]='EMAIL';ftypes[0]='email';fnames[1]='FNAME';ftypes[1]='text';fnames[2]='LNAME';ftypes[2]='text';
try {
    var jqueryLoaded=jQuery;
    jqueryLoaded=true;
} catch(err) {
    var jqueryLoaded=false;
}
var head= document.getElementsByTagName('head')[0];
if (!jqueryLoaded) {
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = '//ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js';
    head.appendChild(script);
    if (script.readyState && script.onload!==null){
        script.onreadystatechange= function () {
              if (this.readyState == 'complete') mce_preload_check();
        }
    }
}

var err_style = '';
try{
    err_style = mc_custom_error_style;
} catch(e){
    err_style = '#mc_embed_signup input.mce_inline_error{border-color:#6B0505;} #mc_embed_signup div.mce_inline_error{margin: 0 0 1em 0; padding: 5px 10px; background-color:#6B0505; font-weight: bold; z-index: 1; color:#fff;}';
}
var head= document.getElementsByTagName('head')[0];
var style= document.createElement('style');
style.type= 'text/css';
if (style.styleSheet) {
  style.styleSheet.cssText = err_style;
} else {
  style.appendChild(document.createTextNode(err_style));
}
head.appendChild(style);
setTimeout('mce_preload_check();', 250);

var mce_preload_checks = 0;
function mce_preload_check(){
    if (mce_preload_checks>40) return;
    mce_preload_checks++;
    try {
        var jqueryLoaded=jQuery;
    } catch(err) {
        setTimeout('mce_preload_check();', 250);
        return;
    }
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = 'http://downloads.mailchimp.com/js/jquery.form-n-validate.js';
    head.appendChild(script);
    try {
        var validatorLoaded=jQuery("#fake-form").validate({});
    } catch(err) {
        setTimeout('mce_preload_check();', 250);
        return;
    }
    mce_init_form();
}
function mce_init_form(){
    jQuery(document).ready( function($) {
      var options = { errorClass: 'mce_inline_error', errorElement: 'div', onkeyup: function(){}, onfocusout:function(){}, onblur:function(){}  };
      var mce_validator = $("#mc-embedded-subscribe-form").validate(options);
      $("#mc-embedded-subscribe-form").unbind('submit');//remove the validator so we can get into beforeSubmit on the ajaxform, which then calls the validator
      options = { url: 'http://mysite.us3.list-manage1.com/subscribe/post-json?u=fcsfse12a6sfsdfsfaf5f5616e&id=0707dfe742&c=?', type: 'GET', dataType: 'json', contentType: "application/json; charset=utf-8",
                    beforeSubmit: function(){
                        $('#mce_tmp_error_msg').remove();
                        $('.datefield','#mc_embed_signup').each(
                            function(){
                                var txt = 'filled';
                                var fields = new Array();
                                var i = 0;
                                $(':text', this).each(
                                    function(){
                                        fields[i] = this;
                                        i++;
                                    });
                                $(':hidden', this).each(
                                    function(){
                                        var bday = false;
                                        if (fields.length == 2){
                                            bday = true;
                                            fields[2] = {'value':1970};//trick birthdays into having years
                                        }
                                        if ( fields[0].value=='MM' && fields[1].value=='DD' && (fields[2].value=='YYYY' || (bday && fields[2].value==1970) ) ){
                                            this.value = '';
                                        } else if ( fields[0].value=='' && fields[1].value=='' && (fields[2].value=='' || (bday && fields[2].value==1970) ) ){
                                            this.value = '';
                                        } else {
                                            if (/\[day\]/.test(fields[0].name)){
                                                this.value = fields[1].value+'/'+fields[0].value+'/'+fields[2].value;
                                            } else {
                                                this.value = fields[0].value+'/'+fields[1].value+'/'+fields[2].value;
                                            }
                                        }
                                    });
                            });
                        $('.phonefield-us','#mc_embed_signup').each(
                            function(){
                                var fields = new Array();
                                var i = 0;
                                $(':text', this).each(
                                    function(){
                                        fields[i] = this;
                                        i++;
                                    });
                                $(':hidden', this).each(
                                    function(){
                                        if ( fields[0].value.length != 3 || fields[1].value.length!=3 || fields[2].value.length!=4 ){
                                            this.value = '';
                                        } else {
                                            this.value = 'filled';
                                        }
                                    });
                            });
                        return mce_validator.form();
                    },
                    success: mce_success_cb
                };
      $('#mc-embedded-subscribe-form').ajaxForm(options);

              $('#mc_embed_signup').hide();
        cks = document.cookie.split( ';' );
        var show=true;
        for(i=0;i<cks.length;i++){
            parts = cks[i].split('=');
            if( parts[0].indexOf('MCEvilPopupClosed')!= -1 ) show = false;
        }
        if (show){
            $('#mc_embed_signup a.mc_embed_close').show();
            setTimeout( function(){ $('#mc_embed_signup').fadeIn();} , 2000);
            $('#mc_embed_signup a.mc_embed_close').click(function(){ mcEvilPopupClose();});
        }

        $(document).keydown(function(e){
            if (e == null) {
              keycode = event.keyCode;
            } else {
              keycode = e.which;
            }
            if(keycode == 27){
                mcEvilPopupClose();
            }
        });

        function mcEvilPopupClose(){
            $('#mc_embed_signup').hide();
            var now = new Date();
            var expires_date = new Date( now.getTime() + 31536000000 );
            document.cookie = 'MCEvilPopupClosed=yes;expires=' + expires_date.toGMTString()+';path=/';
        }

    });
}
function mce_success_cb(resp){
    $('#mce-success-response').hide();
    $('#mce-error-response').hide();
    if (resp.result=="success"){
        $('#mce-'+resp.result+'-response').show();
        $('#mce-'+resp.result+'-response').html(resp.msg);
        $('#mc-embedded-subscribe-form').each(function(){
            this.reset();
        });
    } else {
        var index = -1;
        var msg;
        try {
            var parts = resp.msg.split(' - ',2);
            if (parts[1]==undefined){
                msg = resp.msg;
            } else {
                i = parseInt(parts[0]);
                if (i.toString() == parts[0]){
                    index = parts[0];
                    msg = parts[1];
                } else {
                    index = -1;
                    msg = resp.msg;
                }
            }
        } catch(e){
            index = -1;
            msg = resp.msg;
        }
        try{
            if (index== -1){
                $('#mce-'+resp.result+'-response').show();
                $('#mce-'+resp.result+'-response').html(msg);
            } else {
                err_id = 'mce_tmp_error_msg';
                html = '<div id="'+err_id+'" style="'+err_style+'"> '+msg+'</div>';

                var input_id = '#mc_embed_signup';
                var f = $(input_id);
                if (ftypes[index]=='address'){
                    input_id = '#mce-'+fnames[index]+'-addr1';
                    f = $(input_id).parent().parent().get(0);
                } else if (ftypes[index]=='date'){
                    input_id = '#mce-'+fnames[index]+'-month';
                    f = $(input_id).parent().parent().get(0);
                } else {
                    input_id = '#mce-'+fnames[index];
                    f = $().parent(input_id).get(0);
                }
                if (f){
                    $(f).append(html);
                    $(input_id).focus();
                } else {
                    $('#mce-'+resp.result+'-response').show();
                    $('#mce-'+resp.result+'-response').html(msg);
                }
            }
        } catch(e){
            $('#mce-'+resp.result+'-response').show();
            $('#mce-'+resp.result+'-response').html(msg);
        }
    }
}

</script>
</code>```

The popup is set to launch automatically and the user can exit. I want to also put a link on the site to make the popup show on command.
I have tried:

```<code><a onclick="$('#mc_embed_signup, #mc_embed_signup a.mc_embed_close').css('display', 'block');" href="#">Newsletter</a>
</code>```

and the popup is shown but doesn't seem to work properly.

What is the correct form to launch this so called evil popup when I click on a link?

答:
Make sure to expire cookie (adding path was required for it to work on all pages):</p>

```<code>document.cookie = "MCEvilPopupClosed=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/";
</code>```

Title: Launch Mailchimp evil popup onclick

Body:
Styling

<link href="//cdn-images.mailchimp.com/embedcode/classic-081711.css" rel="stylesheet" type="text/css">

HTML

<form action="http://zehava.us3.list-manage2.com/subscribe/post?u=fc807e12a60c9cbaaf5f5616e&id=0707dfe742" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>

We want to share with you the newest ZEHAVA creations! Leave us your email address! With this occasion, ZEHAVA offers you a gift: a free recondition of your favorite jewelry.

* indicates required

    Email Address  *

    <input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL">

    First Name  *

    <input type="text" value="" name="FNAME" class="required" id="mce-FNAME">

    Last Name
    <input type="text" value="" name="LNAME" class="" id="mce-LNAME">

Close

<input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button">

</form>

Javascript

The popup is set to launch automatically and the user can exit. I want to also put a link on the site to make the popup show on command.
I have tried:

Newsletter

and the popup is shown but doesn't seem to work properly.

What is the correct form to launch this so called evil popup when I click on a link?

Body:
Make sure to expire cookie (adding path was required for it to work on all pages):

document.cookie = "MCEvilPopupClosed=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/";


问:
Why do some built-in constructors begin with a lower case letter?
Why do some constructors like int(), list(), set() and many others starts with a lower case letter instead of upper case? Shouldn't this be written Int(), List(), Set() and so on?

答:
Despite the historical reason for most of these, builtin names that abide to Pythons' naming conventions don't use CapWords. This is specified in PEP 8:

Note that there is a separate convention for builtin names: most builtin names are single words (or two words run together), with the CapWords convention used only for exception names and builtin constants.


问:
how to get the value after the second instance of a character in SQL Server?
I have these strings:

XXXXX - XXXX - XXX - XXXX

XXXX - XXX - XXXXXXX

I need to grab the value AFTER the second instance of '-'

so in the scenario above, I would get:

XXX - XXXX

XXXXXXX

how do I do this in SQL?

答:
This is a XML/XQuery based solution:

```<code>SELECT *, y.ColB.query('root/i[position() gt 2]').value('.', 'NVARCHAR(100)') AS SomethingVeryImportant
FROM (
    SELECT 'XXXXX - XXXX - XXX - XXXX'
    UNION ALL
    SELECT 'XXXX - XXX - XXXXXXX'
) AS x(ColA)
CROSS APPLY ( SELECT CONVERT(XML, N'<root><i>' + REPLACE(x.ColA, N'-', N'-</i><i>') + N'</i></root>') ) AS y(ColB)
</code>```

Demo

Body:
This is a XML/XQuery based solution:

SELECT *, y.ColB.query('root/i[position() gt 2]').value('.', 'NVARCHAR(100)') AS SomethingVeryImportant
FROM (
    SELECT 'XXXXX - XXXX - XXX - XXXX'
    UNION ALL
    SELECT 'XXXX - XXX - XXXXXXX'
) AS x(ColA)
CROSS APPLY ( SELECT CONVERT(XML, N'<root><i>' + REPLACE(x.ColA, N'-', N'-</i><i>') + N'</i></root>') ) AS y(ColB)

Demo


问:
"'init' is deprecated" warning after Swift4 convert
In Swift3, I previously converted a Bool to an Int using the following method

```<code>let _ = Int(NSNumber(value: false))
</code>```

After converting to Swift4, I'm getting a "'init' is deprecated" warning. How else should this be done?

答:
With Swift 4.2 and Swift 5, you can choose one of the 5 following solutions in order to solve your problem.

#1. Using NSNumber's intValue property

```<code>import Foundation

let integer = NSNumber(value: false).intValue
print(integer) // prints 0
</code>```

#2. Using type casting

```<code>import Foundation

let integer = NSNumber(value: false) as? Int
print(String(describing: integer)) // prints Optional(0)
</code>```

#3. Using Int's init(exactly:) initializer

```<code>import Foundation

let integer = Int(exactly: NSNumber(value: false))
print(String(describing: integer)) // prints Optional(0)
</code>```

As an alternative to the previous code, you can use the more concise code below.

```<code>import Foundation

let integer = Int(exactly: false)
print(String(describing: integer)) // prints Optional(0)
</code>```

#4. Using Int's init(truncating:) initializer

```<code>import Foundation

let integer = Int(truncating: false)
print(integer) // prints 0
</code>```

#5. Using control flow

Note that the following sample codes do not require to import Foundation.

Usage #1 (if statement):

```<code>let integer: Int
let bool = false

if bool {
    integer = 1
} else {
    integer = 0
}
print(integer) // prints 0
</code>```

Usage #2 (ternary operator):

```<code>let integer = false ? 1 : 0
print(integer) // prints 0
</code>```

Body:
In Swift3, I previously converted a Bool to an Int using the following method

let _ = Int(NSNumber(value: false))

After converting to Swift4, I'm getting a "'init' is deprecated" warning. How else should this be done?

Body:
With Swift 4.2 and Swift 5, you can choose one of the 5 following solutions in order to solve your problem.

#1. Using NSNumber's intValue property

import Foundation

let integer = NSNumber(value: false).intValue
print(integer) // prints 0

#2. Using type casting

import Foundation

let integer = NSNumber(value: false) as? Int
print(String(describing: integer)) // prints Optional(0)

#3. Using Int's init(exactly:) initializer

import Foundation

let integer = Int(exactly: NSNumber(value: false))
print(String(describing: integer)) // prints Optional(0)

As an alternative to the previous code, you can use the more concise code below.

import Foundation

let integer = Int(exactly: false)
print(String(describing: integer)) // prints Optional(0)

#4. Using Int's init(truncating:) initializer

import Foundation

let integer = Int(truncating: false)
print(integer) // prints 0

#5. Using control flow

Note that the following sample codes do not require to import Foundation.

Usage #1 (if statement):

let integer: Int
let bool = false

if bool {
    integer = 1
} else {
    integer = 0
}
print(integer) // prints 0

Usage #2 (ternary operator):

let integer = false ? 1 : 0
print(integer) // prints 0

ContentLicense: CC BY-SA 4.0


问:
Similar C strings have varying sizes
I have a function which takes an argument of type const unsigned char * as one of its inputs.

Function (mentioned below)

someType *doSomething (someStruct *, const unsigned char *);
or judyData *getFromJudy (judyConfig *, const unsigned char *).

I also have an array of strings , char* i[10].

Suppose, i[2] = "foo". Now, I get different results when I run

doSomething(struct_instance, i[2]) and doSomething(struct_instance, "foo").

Can anyone help me out with when do such situations arise?
Is there a way to type cast the value this pointer points to such that it behaves like a normal string literal?

EDIT:

Sharing code samples.

The function:

```<code>// get an entry from the index, return it or null
judyData *getFromJudy (judyConfig *cnf, const unsigned char *key) {
  judyData *data;
  JudySlot *cell;
  int current;
      cell = judy_slot((Judy *) cnf->idx, (unsigned char *) key, (size_t) strlen((const char *) key));

  if (cell) {
    data = (judyData *) *cell;
    // doesn't enter this if "foo" is not used and i[2] is used.
    if (data->count == 0) {
      return NULL;
    }

    return data;
  }
  return NULL;
}
</code>```

with char * i[10]. It is called as

data = getFromJudy (obj, "foo")

答: sizeof(i[2]) returns the size of a pointer on your machine, which is eight bytes, since it is of type char *; sizeof("foo") returns the length of the string "foo" plus the null terminator, which is four bytes.

Title: Similar C strings have varying sizes

Body:
I have a function which takes an argument of type const unsigned char * as one of its inputs.

Function (mentioned below)

someType *doSomething (someStruct *, const unsigned char *);
or judyData *getFromJudy (judyConfig *, const unsigned char *).

I also have an array of strings , char* i[10].

Suppose, i[2] = "foo". Now, I get different results when I run

doSomething(struct_instance, i[2]) and doSomething(struct_instance, "foo").

Can anyone help me out with when do such situations arise?
Is there a way to type cast the value this pointer points to such that it behaves like a normal string literal?

EDIT:

Sharing code samples.

The function:

// get an entry from the index, return it or null
judyData *getFromJudy (judyConfig *cnf, const unsigned char *key) {
  judyData *data;
  JudySlot *cell;
  int current;
      cell = judy_slot((Judy *) cnf->idx, (unsigned char *) key, (size_t) strlen((const char *) key));

  if (cell) {
    data = (judyData *) *cell;
    // doesn't enter this if "foo" is not used and i[2] is used.
    if (data->count == 0) {
      return NULL;
    }

    return data;
  }
  return NULL;
}

with char * i[10]. It is called as

data = getFromJudy (obj, "foo")


问:
Repeating an Array Looping in jQuery
I am trying to get a jQuery snippet to loop around and keep displaying the messages in the array. This is what I have so far and it works, it just won't loop round after once even though I used setTimeout function.

What am I doing wrong? What would be best practice and why?

Thanks in advance

```<code>    var obj = $("div");
    var arr = $.makeArray(obj);
    var len = arr.length;
    var i = 0;

    function printloop() {
        arr[i].style.display = "block";
        i++;
        if (i < len) {
            setTimeout(printloop, 2000);
        } else {
            setTimeout(function() {
                    $("div").css("display", "none");
            },1000);
        };
    }
    printloop();

    setInterval(prinloop, 20000);
</code>```

答:
If I understand correctly, after you've made it through all the divs, you want to hide them all again and restart the process.

If so, try this:

```<code>// ...
setTimeout(function() {
    $("div").css("display", "none");
    i = 0; // start back at the first div
    printloop();
}, 1000);
</code>```

Note that your setInterval call misspells printloop (prinloop), but I don't think you want that line at all anyway. I'd suggest deleting it.

Full working example:

var arr = $.makeArray($('div'));
var i = 0;

function printloop() {
    arr[i].style.display = "block";
    i++;
    if (i < arr.length) {
        setTimeout(printloop, 2000);
    } else {
        setTimeout(function() {
            $("div").css("display", "none");
            i = 0;
            printloop();
        }, 1000);
    }
}
printloop();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div style="display:none">Div 1</div>
<div style="display:none">Div 2</div>
<div style="display:none">Div 3</div></code>```

Title: Repeating an Array Looping in jQuery

Body:
I am trying to get a jQuery snippet to loop around and keep displaying the messages in the array. This is what I have so far and it works, it just won't loop round after once even though I used setTimeout function.

What am I doing wrong? What would be best practice and why?

Thanks in advance

    var obj = $("div");
    var arr = $.makeArray(obj);
    var len = arr.length;
    var i = 0;

    function printloop() {
        arr[i].style.display = "block";
        i++;
        if (i < len) {
            setTimeout(printloop, 2000);
        } else {
            setTimeout(function() {
                    $("div").css("display", "none");
            },1000);
        };
    }
    printloop();

    setInterval(prinloop, 20000);

Body:
If I understand correctly, after you've made it through all the divs, you want to hide them all again and restart the process.

If so, try this:

// ...
setTimeout(function() {
    $("div").css("display", "none");
    i = 0; // start back at the first div
    printloop();
}, 1000);

Note that your setInterval call misspells printloop (prinloop), but I don't think you want that line at all anyway. I'd suggest deleting it.

Full working example:

var arr = $.makeArray($('div'));
var i = 0;

function printloop() {
    arr[i].style.display = "block";
    i++;
    if (i < arr.length) {
        setTimeout(printloop, 2000);
    } else {
        setTimeout(function() {
            $("div").css("display", "none");
            i = 0;
            printloop();
        }, 1000);
    }
}
printloop();

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div style="display:none">Div 1</div>
<div style="display:none">Div 2</div>
<div style="display:none">Div 3</div>


问:
bash: [: too many arguments after rvm get stable
As the title says, after running the rvm get stable code in bash, I started getting an error, -bash: [: too many arguments.  This error pops up when I do any command, but executes the command properly.  ls and cd for instance will execute as expected, but then print out the error.

I'm running macOS Sierra.  Any help is greatly appreciated!

答:
For anyone who runs into this issue, I was able to stop the error message from showing up by removing the following line of code from ~/.profile and ~/.bash_profile:

[[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm" # Load RVM into a shell session *as a function*

This was added by updating rvm, which is still working after these lines being removed.

UPDATE: This stopped the error, but popped my ruby version backwards from 2.2 back to 2.0


问:
Call a function in a CustomEditor script from another script
I want to use GetComponent. This script is not attached to any Gameobject:

```<code>namespace CBX.Unity.Editors.Editor
{
    using System;
    using CBX.TileMapping.Unity;
    using UnityEditor;
    using UnityEngine;

    /// <summary>
    /// Provides a editor for the <see cref="TileMap"/> component
    /// </summary>
    [CustomEditor(typeof(TileMap))]
    public class TileMapEditor : Editor
    {
        /// <summary>
        /// Holds the location of the mouse hit location
        /// </summary>
        private Vector3 mouseHitPos;

        /// <summary>
        /// Lets the Editor handle an event in the scene view.
        /// </summary>
        ///

        private void OnSceneGUI()
        {
            // if UpdateHitPosition return true we should update the scene views so that the marker will update in real time
            if (this.UpdateHitPosition())
            {
                SceneView.RepaintAll();
            }

            // Calculate the location of the marker based on the location of the mouse
            this.RecalculateMarkerPosition();

            // get a reference to the current event
            Event current = Event.current;

            // if the mouse is positioned over the layer allow drawing actions to occur
            if (this.IsMouseOnLayer())
            {
                // if mouse down or mouse drag event occurred
                if (current.type == EventType.MouseDown || current.type == EventType.MouseDrag)
                {
                    if (current.button == 1)
                    {
                        // if right mouse button is pressed then we erase blocks
                        this.Erase();
                        current.Use();
                    }
                    else if (current.button == 0)
                    {
                        // if left mouse button is pressed then we draw blocks
                        this.Draw();
                        current.Use();
                    }
                }
            }

            // draw a UI tip in scene view informing user how to draw & erase tiles
            Handles.BeginGUI();
            GUI.Label(new Rect(10, Screen.height - 90, 100, 100), "LMB: Draw");
            GUI.Label(new Rect(10, Screen.height - 105, 100, 100), "RMB: Erase");
            Handles.EndGUI();
        }

        /// <summary>
        /// When the <see cref="GameObject"/> is selected set the current tool to the view tool.
        /// </summary>
        private void OnEnable()
        {
            Tools.current = Tool.View;
            Tools.viewTool = ViewTool.FPS;
        }

        /// <summary>
        /// Draws a block at the pre-calculated mouse hit position
        /// </summary>
        private void Draw()
        {
            // get reference to the TileMap component
            var map = (TileMap)this.target;

            // Calculate the position of the mouse over the tile layer
            var tilePos = this.GetTilePositionFromMouseLocation();

            // Given the tile position check to see if a tile has already been created at that location
            var cube = GameObject.Find(string.Format("Tile_{0}_{1}", tilePos.x, tilePos.y));

            // if there is already a tile present and it is not a child of the game object we can just exit.
            if (cube != null && cube.transform.parent != map.transform)
            {
                return;
            }

            // if no game object was found we will create a cube
            if (cube == null)
            {
                cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
            }

            // set the cubes position on the tile map
            var tilePositionInLocalSpace = new Vector3((tilePos.x * map.TileWidth) + (map.TileWidth / 2), (tilePos.y * map.TileHeight) + (map.TileHeight / 2));
            cube.transform.position = map.transform.position + tilePositionInLocalSpace;

            // we scale the cube to the tile size defined by the TileMap.TileWidth and TileMap.TileHeight fields
            cube.transform.localScale = new Vector3(map.TileWidth, map.TileHeight, 1);

            // set the cubes parent to the game object for organizational purposes
            cube.transform.parent = map.transform;

            // give the cube a name that represents it's location within the tile map
            cube.name = string.Format("Tile_{0}_{1}", tilePos.x, tilePos.y);

            // give the cube a tag
            cube.tag = "GridObject";

            TerrainObjects(cube);
        }

        public GameObject TerrainObjects(GameObject gameobject)
        {
            return gameobject;
        }

        /// <summary>
        /// Erases a block at the pre-calculated mouse hit position
        /// </summary>
        private void Erase()
        {
            // get reference to the TileMap component
            var map = (TileMap)this.target;

            // Calculate the position of the mouse over the tile layer
            var tilePos = this.GetTilePositionFromMouseLocation();

            // Given the tile position check to see if a tile has already been created at that location
            var cube = GameObject.Find(string.Format("Tile_{0}_{1}", tilePos.x, tilePos.y));
            var terrainObject = GameObject.Find(string.Format("Terrain_{0}_{1}", Terrain.activeTerrain.transform.position.x + tilePos.x, Terrain.activeTerrain.transform.position.z + tilePos.y));

            // if a game object was found with the same name and it is a child we just destroy it immediately
            if (cube != null && cube.transform.parent == map.transform)
            {
                UnityEngine.Object.DestroyImmediate(cube);
            }

            if (terrainObject != null && terrainObject.transform.parent == map.transform)
            {
                DestroyImmediate(terrainObject);
            }
        }

        /// <summary>
        /// Calculates the location in tile coordinates (Column/Row) of the mouse position
        /// </summary>
        /// <returns>Returns a <see cref="Vector2"/> type representing the Column and Row where the mouse of positioned over.</returns>
        private Vector2 GetTilePositionFromMouseLocation()
        {
            // get reference to the tile map component
            var map = (TileMap)this.target;

            // calculate column and row location from mouse hit location
            var pos = new Vector3(this.mouseHitPos.x / map.TileWidth, this.mouseHitPos.y / map.TileHeight, map.transform.position.z);

            // round the numbers to the nearest whole number using 5 decimal place precision
            pos = new Vector3((int)Math.Round(pos.x, 5, MidpointRounding.ToEven), (int)Math.Round(pos.y, 5, MidpointRounding.ToEven), 0);

            // do a check to ensure that the row and column are with the bounds of the tile map
            var col = (int)pos.x;
            var row = (int)pos.y;
            if (row < 0)
            {
                row = 0;
            }

            if (row > map.Rows - 1)
            {
                row = map.Rows - 1;
            }

            if (col < 0)
            {
                col = 0;
            }

            if (col > map.Columns - 1)
            {
                col = map.Columns - 1;
            }

            // return the column and row values
            return new Vector2(col, row);
        }

        /// <summary>
        /// Returns true or false depending if the mouse is positioned over the tile map.
        /// </summary>
        /// <returns>Will return true if the mouse is positioned over the tile map.</returns>
        private bool IsMouseOnLayer()
        {
            // get reference to the tile map component
            var map = (TileMap)this.target;

            // return true or false depending if the mouse is positioned over the map
            return this.mouseHitPos.x > 0 && this.mouseHitPos.x < (map.Columns * map.TileWidth) &&
                   this.mouseHitPos.y > 0 && this.mouseHitPos.y < (map.Rows * map.TileHeight);
        }

        /// <summary>
        /// Recalculates the position of the marker based on the location of the mouse pointer.
        /// </summary>
        private void RecalculateMarkerPosition()
        {
            // get reference to the tile map component
            var map = (TileMap)this.target;

            // store the tile location (Column/Row) based on the current location of the mouse pointer
            var tilepos = this.GetTilePositionFromMouseLocation();

            // store the tile position in world space
            var pos = new Vector3(tilepos.x * map.TileWidth, tilepos.y * map.TileHeight, 0);

            // set the TileMap.MarkerPosition value
            map.MarkerPosition = map.transform.position + new Vector3(pos.x + (map.TileWidth / 2), pos.y + (map.TileHeight / 2), 0);
        }

        /// <summary>
        /// Calculates the position of the mouse over the tile map in local space coordinates.
        /// </summary>
        /// <returns>Returns true if the mouse is over the tile map.</returns>
        private bool UpdateHitPosition()
        {
            // get reference to the tile map component
            var map = (TileMap)this.target;

            // build a plane object that
            var p = new Plane(map.transform.TransformDirection(Vector3.forward), map.transform.position);

            // build a ray type from the current mouse position
            var ray = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition);

            // stores the hit location
            var hit = new Vector3();

            // stores the distance to the hit location
            float dist;

            // cast a ray to determine what location it intersects with the plane
            if (p.Raycast(ray, out dist))
            {
                // the ray hits the plane so we calculate the hit location in world space
                hit = ray.origin + (ray.direction.normalized * dist);
            }

            // convert the hit location from world space to local space
            var value = map.transform.InverseTransformPoint(hit);

            // if the value is different then the current mouse hit location set the
            // new mouse hit location and return true indicating a successful hit test
            if (value != this.mouseHitPos)
            {
                this.mouseHitPos = value;
                return true;
            }

            // return false if the hit test failed
            return false;
        }
    }
}
</code>```

In this script i also added a public method

```<code>public GameObject TerrainObjects(GameObject gameobject)
{
    return gameobject;
}
</code>```

And I want to get access to this method TerrainObjects from another script:

This script is attached to a GameObject:

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TerrainObjects : MonoBehaviour {

    // Use this for initialization
    void Start ()
    {
      GetComponent<tile>
    }

    // Update is called once per frame
    void Update ()
    {

    }
}
</code>```

I'm trying to type tile or TileMap or TileMapEditor but it's not exist.
So i can't make Getcomponent of this script.

In the Start i tried to type:

```<code>GetComponent<tile>
</code>```

But I can't access the TileMapEditor.

Is there any way to get access to it ?
If it's editor type script should i attach to the same gameobject as the TerrainObjects script ?

I don't want that the TileMapEditor will work in game only in scene.

答:
I assume this is an Editor plugin. GetComponent should not work for scripts that inherits from the Editor. You need to use Resources.FindObjectsOfTypeAll to find TileMapEditor then call its function (TerrainObjects).

If there is one instance of TileMap, use index 0 to call the function. If there are many of them then loop through them and call their functions.

```<code>TileMapEditor[] tpEditorInstance = (TileMapEditor[])Resources.FindObjectsOfTypeAll(typeof(TileMapEditor));

//Make sure it is not null
if (tpEditorInstance != null && tpEditorInstance.Length > 0)
{
    tpEditorInstance[0].TerrainObjects(gameObject);
}
else
{
    Debug.Log("TileMapEditor is Null");
}
</code>```

EDIT:

TileMapEditor is not exist in the TerrainObjects script.

Don't really understand that but remember that your TileMapEditor script is in another namespace called "CBX.Unity.Editors.Editor". You have to import that namespace too in any script that will access TileMapEditor.

Just add using CBX.Unity.Editors.Editor; to the top of each script that will access the TileMapEditor script.

Body:
I want to use GetComponent. This script is not attached to any Gameobject:

namespace CBX.Unity.Editors.Editor
{
    using System;
    using CBX.TileMapping.Unity;
    using UnityEditor;
    using UnityEngine;

    ///
    /// Provides a editor for the <see cref="TileMap"/> component
    ///
    [CustomEditor(typeof(TileMap))]
    public class TileMapEditor : Editor
    {
        ///
        /// Holds the location of the mouse hit location
        ///
        private Vector3 mouseHitPos;

        ///
        /// Lets the Editor handle an event in the scene view.
        ///
        ///

        private void OnSceneGUI()
        {
            // if UpdateHitPosition return true we should update the scene views so that the marker will update in real time
            if (this.UpdateHitPosition())
            {
                SceneView.RepaintAll();
            }

            // Calculate the location of the marker based on the location of the mouse
            this.RecalculateMarkerPosition();

            // get a reference to the current event
            Event current = Event.current;

            // if the mouse is positioned over the layer allow drawing actions to occur
            if (this.IsMouseOnLayer())
            {
                // if mouse down or mouse drag event occurred
                if (current.type == EventType.MouseDown || current.type == EventType.MouseDrag)
                {
                    if (current.button == 1)
                    {
                        // if right mouse button is pressed then we erase blocks
                        this.Erase();
                        current.Use();
                    }
                    else if (current.button == 0)
                    {
                        // if left mouse button is pressed then we draw blocks
                        this.Draw();
                        current.Use();
                    }
                }
            }

            // draw a UI tip in scene view informing user how to draw & erase tiles
            Handles.BeginGUI();
            GUI.Label(new Rect(10, Screen.height - 90, 100, 100), "LMB: Draw");
            GUI.Label(new Rect(10, Screen.height - 105, 100, 100), "RMB: Erase");
            Handles.EndGUI();
        }

        ///
        /// When the <see cref="GameObject"/> is selected set the current tool to the view tool.
        ///
        private void OnEnable()
        {
            Tools.current = Tool.View;
            Tools.viewTool = ViewTool.FPS;
        }

        ///
        /// Draws a block at the pre-calculated mouse hit position
        ///
        private void Draw()
        {
            // get reference to the TileMap component
            var map = (TileMap)this.target;

            // Calculate the position of the mouse over the tile layer
            var tilePos = this.GetTilePositionFromMouseLocation();

            // Given the tile position check to see if a tile has already been created at that location
            var cube = GameObject.Find(string.Format("Tile_{0}_{1}", tilePos.x, tilePos.y));

            // if there is already a tile present and it is not a child of the game object we can just exit.
            if (cube != null && cube.transform.parent != map.transform)
            {
                return;
            }

            // if no game object was found we will create a cube
            if (cube == null)
            {
                cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
            }

            // set the cubes position on the tile map
            var tilePositionInLocalSpace = new Vector3((tilePos.x * map.TileWidth) + (map.TileWidth / 2), (tilePos.y * map.TileHeight) + (map.TileHeight / 2));
            cube.transform.position = map.transform.position + tilePositionInLocalSpace;

            // we scale the cube to the tile size defined by the TileMap.TileWidth and TileMap.TileHeight fields
            cube.transform.localScale = new Vector3(map.TileWidth, map.TileHeight, 1);

            // set the cubes parent to the game object for organizational purposes
            cube.transform.parent = map.transform;

            // give the cube a name that represents it's location within the tile map
            cube.name = string.Format("Tile_{0}_{1}", tilePos.x, tilePos.y);

            // give the cube a tag
            cube.tag = "GridObject";

            TerrainObjects(cube);
        }

        public GameObject TerrainObjects(GameObject gameobject)
        {
            return gameobject;
        }

        ///
        /// Erases a block at the pre-calculated mouse hit position
        ///
        private void Erase()
        {
            // get reference to the TileMap component
            var map = (TileMap)this.target;

            // Calculate the position of the mouse over the tile layer
            var tilePos = this.GetTilePositionFromMouseLocation();

            // Given the tile position check to see if a tile has already been created at that location
            var cube = GameObject.Find(string.Format("Tile_{0}_{1}", tilePos.x, tilePos.y));
            var terrainObject = GameObject.Find(string.Format("Terrain_{0}_{1}", Terrain.activeTerrain.transform.position.x + tilePos.x, Terrain.activeTerrain.transform.position.z + tilePos.y));

            // if a game object was found with the same name and it is a child we just destroy it immediately
            if (cube != null && cube.transform.parent == map.transform)
            {
                UnityEngine.Object.DestroyImmediate(cube);
            }

            if (terrainObject != null && terrainObject.transform.parent == map.transform)
            {
                DestroyImmediate(terrainObject);
            }
        }

        ///
        /// Calculates the location in tile coordinates (Column/Row) of the mouse position
        ///
        /// <returns>Returns a <see cref="Vector2"/> type representing the Column and Row where the mouse of positioned over.</returns>
        private Vector2 GetTilePositionFromMouseLocation()
        {
            // get reference to the tile map component
            var map = (TileMap)this.target;

            // calculate column and row location from mouse hit location
            var pos = new Vector3(this.mouseHitPos.x / map.TileWidth, this.mouseHitPos.y / map.TileHeight, map.transform.position.z);

            // round the numbers to the nearest whole number using 5 decimal place precision
            pos = new Vector3((int)Math.Round(pos.x, 5, MidpointRounding.ToEven), (int)Math.Round(pos.y, 5, MidpointRounding.ToEven), 0);

            // do a check to ensure that the row and column are with the bounds of the tile map
            var col = (int)pos.x;
            var row = (int)pos.y;
            if (row < 0)
            {
                row = 0;
            }

            if (row > map.Rows - 1)
            {
                row = map.Rows - 1;
            }

            if (col < 0)
            {
                col = 0;
            }

            if (col > map.Columns - 1)
            {
                col = map.Columns - 1;
            }

            // return the column and row values
            return new Vector2(col, row);
        }

        ///
        /// Returns true or false depending if the mouse is positioned over the tile map.
        ///
        /// <returns>Will return true if the mouse is positioned over the tile map.</returns>
        private bool IsMouseOnLayer()
        {
            // get reference to the tile map component
            var map = (TileMap)this.target;

            // return true or false depending if the mouse is positioned over the map
            return this.mouseHitPos.x > 0 && this.mouseHitPos.x < (map.Columns * map.TileWidth) &&
                   this.mouseHitPos.y > 0 && this.mouseHitPos.y < (map.Rows * map.TileHeight);
        }

        ///
        /// Recalculates the position of the marker based on the location of the mouse pointer.
        ///
        private void RecalculateMarkerPosition()
        {
            // get reference to the tile map component
            var map = (TileMap)this.target;

            // store the tile location (Column/Row) based on the current location of the mouse pointer
            var tilepos = this.GetTilePositionFromMouseLocation();

            // store the tile position in world space
            var pos = new Vector3(tilepos.x * map.TileWidth, tilepos.y * map.TileHeight, 0);

            // set the TileMap.MarkerPosition value
            map.MarkerPosition = map.transform.position + new Vector3(pos.x + (map.TileWidth / 2), pos.y + (map.TileHeight / 2), 0);
        }

        ///
        /// Calculates the position of the mouse over the tile map in local space coordinates.
        ///
        /// <returns>Returns true if the mouse is over the tile map.</returns>
        private bool UpdateHitPosition()
        {
            // get reference to the tile map component
            var map = (TileMap)this.target;

            // build a plane object that
            var p = new Plane(map.transform.TransformDirection(Vector3.forward), map.transform.position);

            // build a ray type from the current mouse position
            var ray = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition);

            // stores the hit location
            var hit = new Vector3();

            // stores the distance to the hit location
            float dist;

            // cast a ray to determine what location it intersects with the plane
            if (p.Raycast(ray, out dist))
            {
                // the ray hits the plane so we calculate the hit location in world space
                hit = ray.origin + (ray.direction.normalized * dist);
            }

            // convert the hit location from world space to local space
            var value = map.transform.InverseTransformPoint(hit);

            // if the value is different then the current mouse hit location set the
            // new mouse hit location and return true indicating a successful hit test
            if (value != this.mouseHitPos)
            {
                this.mouseHitPos = value;
                return true;
            }

            // return false if the hit test failed
            return false;
        }
    }
}

In this script i also added a public method

public GameObject TerrainObjects(GameObject gameobject)
{
    return gameobject;
}

And I want to get access to this method TerrainObjects from another script:

This script is attached to a GameObject:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TerrainObjects : MonoBehaviour {

    // Use this for initialization
    void Start ()
    {
      GetComponent<tile>
    }

    // Update is called once per frame
    void Update ()
    {

    }
}

I'm trying to type tile or TileMap or TileMapEditor but it's not exist.
So i can't make Getcomponent of this script.

In the Start i tried to type:

GetComponent<tile>

But I can't access the TileMapEditor.

Is there any way to get access to it ?
If it's editor type script should i attach to the same gameobject as the TerrainObjects script ?

I don't want that the TileMapEditor will work in game only in scene.

Body:
I assume this is an Editor plugin. GetComponent should not work for scripts that inherits from the Editor. You need to use Resources.FindObjectsOfTypeAll to find TileMapEditor then call its function (TerrainObjects).

If there is one instance of TileMap, use index 0 to call the function. If there are many of them then loop through them and call their functions.

TileMapEditor[] tpEditorInstance = (TileMapEditor[])Resources.FindObjectsOfTypeAll(typeof(TileMapEditor));

//Make sure it is not null
if (tpEditorInstance != null && tpEditorInstance.Length > 0)
{
    tpEditorInstance[0].TerrainObjects(gameObject);
}
else
{
    Debug.Log("TileMapEditor is Null");
}

EDIT:

TileMapEditor is not exist in the TerrainObjects script.

Don't really understand that but remember that your TileMapEditor script is in another namespace called "CBX.Unity.Editors.Editor". You have to import that namespace too in any script that will access TileMapEditor.

Just add using CBX.Unity.Editors.Editor; to the top of each script that will access the TileMapEditor script.


问:
Stroke Dash Interpolation Sample Code Not Working
I am trying to use Mike Bostock’s Block 5649592 as an example to draw stroke-dash interpolation.

I copied his code from index.html example into an html file on my local computer, and it is not presenting anything when I open the html file. Does anyone know what's happening here? Am I missing anything here?

I am copying his code here:

```<code><!DOCTYPE html>
<meta charset="utf-8">
<body>
<style>

path {
  fill: none;
  stroke: #000;
  stroke-width: 3px;
}

</style>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>

var points = [
  [480, 200],
  [580, 400],
  [680, 100],
  [780, 300],
  [180, 300],
  [280, 100],
  [380, 400]
];

var line = d3.svg.line()
    .tension(0) // Catmull–Rom
    .interpolate("cardinal-closed");

var svg = d3.select("body").append("svg")
    .datum(points)
    .attr("width", 960)
    .attr("height", 500);

svg.append("path")
    .style("stroke", "#ddd")
    .style("stroke-dasharray", "4,4")
    .attr("d", line);

svg.append("path")
    .attr("d", line)
    .call(transition);

function transition(path) {
  path.transition()
      .duration(7500)
      .attrTween("stroke-dasharray", tweenDash)
      .each("end", function() { d3.select(this).call(transition); });
}

function tweenDash() {
  var l = this.getTotalLength(),
      i = d3.interpolateString("0," + l, l + "," + l);
  return function(t) { return i(t); };
}

</script>
</code>```

Any help is appreciated! Thanks.

PROBLEM SOLVED

Please see my answer post below. Kudos to BJK!

答:
Thanks to BJK, who helped me from Google D3.js group, I figured out the problem. I was not operating in the development environment. I was using local file system, which does not always work.

Here is the suggestion BJK sent me: "See https://github.com/d3/d3/wiki => section "local development"..."

After switch to the development environment, Mike Bostock (FYI, I remember his name as BossTalk, which is true for he talking data like a boss)'s code works perfectly.

Cheers.

Body:
I am trying to use Mike Bostock’s Block 5649592 as an example to draw stroke-dash interpolation.

I copied his code from index.html example into an html file on my local computer, and it is not presenting anything when I open the html file. Does anyone know what's happening here? Am I missing anything here?

I am copying his code here:

<!DOCTYPE html>
<meta charset="utf-8">

Any help is appreciated! Thanks.

PROBLEM SOLVED

Please see my answer post below. Kudos to BJK!


问:
How to enable CSRF protection in ServiceStack
There is AntiXsrf code in ServiceStack, but it's not clear how to use it or enable it. Looking at network requests using chrome devtools, it doesn't appear to be turned on by default.</p>

答:
In your Razor page you can embed the token in your Form with:

```<code><form action="/antiforgery/test" method="POST">
    @Html.AntiForgeryToken()
    <input name="Field" value="Test"/>
    <input type="submit"/>
</form>
</code>```

Which you can then validate in your Service with:

```<code>[Route("/antiforgery/test")]
public class AntiForgeryTest
{
    public string Field { get; set; }
}

public class AntiForgeryService : Service
{
    public object Any(AntiForgeryTest request)
    {
        AntiForgery.Validate();
       ...
    }
}
</code>```

Body:
In your Razor page you can embed the token in your Form with:

<form action="/antiforgery/test" method="POST">
    @Html.AntiForgeryToken()
    <input name="Field" value="Test"/>
    <input type="submit"/>
</form>

Which you can then validate in your Service with:

[Route("/antiforgery/test")]
public class AntiForgeryTest
{
    public string Field { get; set; }
}

public class AntiForgeryService : Service
{
    public object Any(AntiForgeryTest request)
    {
        AntiForgery.Validate();
       ...
    }
}


问:
Keeping classes loosely coupled and sharing data
I've been working in python on a project where I have a GUI which I split up a bunch of the work between classes. I don't know a lot of the best practices for passing data around between classes, and I've frequently run into the issue, where I have to implement something, or change something for work, and I've resorted to making a lot of the classes objects of another class in order to give it the data I need.

Any ideas or suggests would be greatly appreciated on how to keep my classes independent for later modification and still pass the relevant data around without affecting interfaces too much?

As an example

```<code>class Window():
    def __init__(self, parent=None):
        self.parent = parent
    def doStuff(self):
        #do work here

class ParseMyWork(Window):
    def __init__(self, parent=None):
        self.parent=parent
</code>```

I often find myself doing stuff like the above giving objects to class Window
or simply inheriting everything from them as in ParseMyWork

There must be better and cleaner ways of passing data around without making my classes utterly dependent on eachother, where one little change creates a cascade effect that forces me to make changes in a bunch of other classes.

Any answers to the question don't necessarily have to be in python, but it will be helpful if they are

答:
Classes are super powerful, so it's good you're getting started with em.

Discalimer: Haven't worked in python for a while now, so things might not be exact. The general idea still applies though.

Getting into your question now:

I would say the best way to achieve what you want is to create an instance of the first object where you will extract information from.

Now when creating a class, it's vital that you have attributes within them that you will want to be stored within it that you would like to retrieve once the class is instantiated.

For example, using your Window class example above, let's say that you have an attribute called resolution. It would look something like this:

```<code>    class Window():
      def __init__(self, parent = None):
         self.parent = None
         self.resolution = '40x80'
</code>```

Now the resolution information associated with your Window class is forever part of any Window class instance. Now, the next step would be to create a get method for resolution. This should be done as follow:

```<code>    class Window():
      def __init__(self, parent = None):
         self.parent = None
         self.resolution = '40x80'

      def getResoultion():
         return self.resolution
</code>```

Now, the reason we created this get method is because we can now set a variable to the information that is returned with it.

So let's say that you have everything associated with your Window class in its own file (let's say the file name is called Window.py). In a separate file (let's call it main.py), you can do the following:

```<code>    import Window

    windowInstance = Window()
    windowResolution = windowInstance.getResolution()
</code>```

If you print out the variable windowResolution, you should get that 40x80 printed out.

Now, as a side note, I do believe it is possible to get the information associated with an attribute with an instance of a class by simply doing something like

```<code>     windowResolution = windowInstance.resolution
</code>```

but that is bad practice in general. The reason, in a nutshell, is because you are now exposing attribute names of your class which you do not want to do because it makes it easy for a person outside of your code to learn the name where that information is held and change it. This can then lead to a myriad of other problems when it comes to making an overall program work. That is why it is best practice to use getters and setters. I already showed what getters are. Simply a get method for attributes. Setters, as you can probably assume, allow for one to set the information of an attribute to something else. Now you might say "Gabe, if we can create setter methods, what's the point of it if they just change it". My answer to that is to not give a setter method to all attributes. For attributes you don't mind for a person to change, give it a setter method, but for attributes you do not want any outside users to touch, simply don't create a setter method for it. Same goes with getter methods too. Users don't need to see all of the information of all attributes that makes your program work. Here's a better explanation: https://en.wikipedia.org/wiki/Mutator_method

Now, back to your example. Now let's say you have your ParseMyWork class in its own file like we did with your Window class, and let's say that ParseMyWork needs the resolution info from Window class. You can do the following :

```<code>    import Window
    import ParseMyWork

    windowInstance = Window()
    windowResolution = windowInstance.getResolution()

    parseInstance = ParseMyWork(windowResolution)
</code>```

This will only pass the window resolution information associated with your Window class. Hope this helps.

Body:
I've been working in python on a project where I have a GUI which I split up a bunch of the work between classes. I don't know a lot of the best practices for passing data around between classes, and I've frequently run into the issue, where I have to implement something, or change something for work, and I've resorted to making a lot of the classes objects of another class in order to give it the data I need.

Any ideas or suggests would be greatly appreciated on how to keep my classes independent for later modification and still pass the relevant data around without affecting interfaces too much?

As an example

class Window():
    def __init__(self, parent=None):
        self.parent = parent
    def doStuff(self):
        #do work here

class ParseMyWork(Window):
    def __init__(self, parent=None):
        self.parent=parent

I often find myself doing stuff like the above giving objects to class Window
or simply inheriting everything from them as in ParseMyWork

There must be better and cleaner ways of passing data around without making my classes utterly dependent on eachother, where one little change creates a cascade effect that forces me to make changes in a bunch of other classes.

Any answers to the question don't necessarily have to be in python, but it will be helpful if they are

Body:
Classes are super powerful, so it's good you're getting started with em.

Discalimer: Haven't worked in python for a while now, so things might not be exact. The general idea still applies though.

Getting into your question now:

I would say the best way to achieve what you want is to create an instance of the first object where you will extract information from.

Now when creating a class, it's vital that you have attributes within them that you will want to be stored within it that you would like to retrieve once the class is instantiated.

For example, using your Window class example above, let's say that you have an attribute called resolution. It would look something like this:

    class Window():
      def __init__(self, parent = None):
         self.parent = None
         self.resolution = '40x80'

Now the resolution information associated with your Window class is forever part of any Window class instance. Now, the next step would be to create a get method for resolution. This should be done as follow:

    class Window():
      def __init__(self, parent = None):
         self.parent = None
         self.resolution = '40x80'

      def getResoultion():
         return self.resolution

Now, the reason we created this get method is because we can now set a variable to the information that is returned with it.

So let's say that you have everything associated with your Window class in its own file (let's say the file name is called Window.py). In a separate file (let's call it main.py), you can do the following:

    import Window

    windowInstance = Window()
    windowResolution = windowInstance.getResolution()

If you print out the variable windowResolution, you should get that 40x80 printed out.

Now, as a side note, I do believe it is possible to get the information associated with an attribute with an instance of a class by simply doing something like

     windowResolution = windowInstance.resolution

but that is bad practice in general. The reason, in a nutshell, is because you are now exposing attribute names of your class which you do not want to do because it makes it easy for a person outside of your code to learn the name where that information is held and change it. This can then lead to a myriad of other problems when it comes to making an overall program work. That is why it is best practice to use getters and setters. I already showed what getters are. Simply a get method for attributes. Setters, as you can probably assume, allow for one to set the information of an attribute to something else. Now you might say "Gabe, if we can create setter methods, what's the point of it if they just change it". My answer to that is to not give a setter method to all attributes. For attributes you don't mind for a person to change, give it a setter method, but for attributes you do not want any outside users to touch, simply don't create a setter method for it. Same goes with getter methods too. Users don't need to see all of the information of all attributes that makes your program work. Here's a better explanation: https://en.wikipedia.org/wiki/Mutator_method

Now, back to your example. Now let's say you have your ParseMyWork class in its own file like we did with your Window class, and let's say that ParseMyWork needs the resolution info from Window class. You can do the following :

    import Window
    import ParseMyWork

    windowInstance = Window()
    windowResolution = windowInstance.getResolution()

    parseInstance = ParseMyWork(windowResolution)

This will only pass the window resolution information associated with your Window class. Hope this helps.


问:
Have Magento respond to several domains with the same store
I would like to have my magento install respond to two different domains, e.g.
  a.mydomain.com and
  b.anotherdomain.com

I need magento to respond with the same store, showing the same customers, the same catalog, same prices, etc.

The difference, of course, is that when the store is accessed through a.mydomain.com all the links and urls should use this domain as baseurl, and when it is accessed through b.anotherdomain.com all links and urls should use b.anotherdomain.com as baseurl.

Is there any way to do so? All the documentation I've found so far deal with having different stores on the same magento instance, while what I need here is to have the same store respond to two different URLs.

Thank you!

答:
Everything I know of Magento says it was designed to prevent exactly this from happening so as not to be penalised by search engines for duplicate content.

You can, however, have multiple stores that share customers and catalog and products and prices and so on, but represent a separate domain each. In System > Manage Stores add several Stores for a single website and use the same root category for them all. Then in System > Configuration > Web assign the various domains.

ContentLicense: CC BY-SA 2.5


问:
Using MDC Components in my Angular CLI Application
I have cloned and angular-cli quickstart.I am trying to use material design web components in it.I just want the MDCCheckbox so i have run the following command npm install --save @material/checkbox which installed the checkbox without any errors.Then i placed checkbox template in my app.component.html

```<code><div class="mdc-form-field">
 <div class="mdc-checkbox">
  <input type="checkbox"
       id="my-checkbox"
       class="mdc-checkbox__native-control"/>
<div class="mdc-checkbox__background">
  <svg class="mdc-checkbox__checkmark"
       viewBox="0 0 24 24">
    <path class="mdc-checkbox__checkmark__path"
          fill="none"
          stroke="white"
          d="M1.73,12.91 8.1,19.28 22.79,4.59"/>
  </svg>
  <div class="mdc-checkbox__mixedmark"></div>
</div>
</div>
<label for="my-checkbox">My Checkbox Label</label>
</div>
</code>```

I have imported MDCCheckbox, MDCCheckboxFoundation from @material/checkbox in my app.module.ts and added them in my imports list.
But I dont find the material styles applied.Is there something wrong which i'm doing? Can Somebody please help me out

答:
Seems like you're missing importing the @material/checkbox styles into your application.

```<code>const MDC_CHECKBOX_STYLES = require('@material/checkbox/dist/mdc.checkbox.css');

@Component({
   styles: [String(MDC_CHECKBOX_STYLES), /* ... */],
})
class CheckboxComponent {
  // Use MDCCheckbox within this component's template
};
</code>```

We have an example of how to do this for angular2 in our framework-examples/angular2 folder: https://github.com/material-components/material-components-web/blob/master/framework-examples/angular2/src/app/components/checkbox/checkbox.ts#L38

The example in our repo uses angular2-seed, not angular CLI, and loads our Sass, but using CSS instead should be relatively straightforward. I couldn't really find any official docs on how to include CSS for third-party libs within the angular-cli repo but I did find this issue comment that seems to explain how to do so.

Body:
I have cloned and angular-cli quickstart.I am trying to use material design web components in it.I just want the MDCCheckbox so i have run the following command npm install --save @material/checkbox which installed the checkbox without any errors.Then i placed checkbox template in my app.component.html

  <input type="checkbox"
       id="my-checkbox"
       class="mdc-checkbox__native-control"/>

  <svg class="mdc-checkbox__checkmark"
       viewBox="0 0 24 24">
    <path class="mdc-checkbox__checkmark__path"
          fill="none"
          stroke="white"
          d="M1.73,12.91 8.1,19.28 22.79,4.59"/>
  </svg>

My Checkbox Label

I have imported MDCCheckbox, MDCCheckboxFoundation from @material/checkbox in my app.module.ts and added them in my imports list.
But I dont find the material styles applied.Is there something wrong which i'm doing? Can Somebody please help me out

Body:
Seems like you're missing importing the @material/checkbox styles into your application.

const MDC_CHECKBOX_STYLES = require('@material/checkbox/dist/mdc.checkbox.css');

@Component({
   styles: [String(MDC_CHECKBOX_STYLES), /* ... */],
})
class CheckboxComponent {
  // Use MDCCheckbox within this component's template
};

We have an example of how to do this for angular2 in our framework-examples/angular2 folder: https://github.com/material-components/material-components-web/blob/master/framework-examples/angular2/src/app/components/checkbox/checkbox.ts#L38

The example in our repo uses angular2-seed, not angular CLI, and loads our Sass, but using CSS instead should be relatively straightforward. I couldn't really find any official docs on how to include CSS for third-party libs within the angular-cli repo but I did find this issue comment that seems to explain how to do so.


问:
SQL - 1 Column Twice in the SELECT Statement for different values
I have created a database of "trips" with the following

TripParent

Id

DrivingCompany

Client

TripDetails

Id

Destination

PlannedArrivalDate

StatusLog

Id

CatStatusId (Comes from another table just with the names)

DateTimeModified

Let me explain the tables, first of all I hid another fields to keep it simple, the "Parent" table has MANY TripDetails, so it is just a summary for the many "Details" it has. The TripDetails table its 1 row for 1 destination, let's say the Trip is going from A to C, then we have a Row for each "stop" (A, B, C).
And then we got the StatusLog table that has MANY Rows for each "TripDetails".

The problem is, I need a stored procedure that returns the DrivingCompany, Client, PlannedArrivalDate, RealArrivalDate and RealDepartureDate.

The "Real Dates" come from the StatusLog table. Status 1 means that the truck has arrived Destination (A/B/C) and the status 2 means that it has left said location.

So far I got the following

```<code>SELECT
    TP.DrivingCompany, TP.Client, TD.PlannedArrivalDate,
    'Real Arrival Date' = CASE SL.CatStatusId
                             WHEN 1 THEN SL.DateTimeModified
                             ELSE NULL
                          END,
   'Real Departure Date' = CASE SL.CatStatusId
                              WHEN 2 THEN SL.DateTimeModified
                              ELSE NULL
                           END
FROM
    TripParent TP
JOIN
    TripDetails TD ON TD.TripParentId = TE.Id
JOIN
    StatusLog SL ON SL.TripDetailsId = TD.Id
GROUP BY
    TP.Id
ORDER BY
    TD.Id
</code>```

Is using the CASE the correct way to show the same column twice in the SELECT statement? I think I'm on the right track but I can't group by TP.Id and I also need to show ALL the rows, going by this query, It doesn't show the "TripDetails" that don't have a "StatusLog" row because they haven't arrived.

Any help is appreciated

答:
Try this:

```<code>SELECT TP.Id,
       TP.DrivingCompany,
       TP.Client,
       TD.PlannedArrivalDate,
       'Real Arrival Date' = CASE SL.CatStatusId
                              WHEN 1 THEN SL.DateTimeModified
                              ELSE NULL
                             END,
       'Real Departure Date' = CASE SL.CatStatusId
                                WHEN 2 THEN SL.DateTimeModified
                                ELSE NULL
                               END
  FROM      TripParent TP
       JOIN TripDetails TD ON TD.TripParentId = TE.Id
  LEFT JOIN StatusLog SL ON SL.TripDetailsId = TD.Id
 GROUP BY TP.Id,
          TP.DrivingCompany,
          TP.Client,
          TD.PlannedArrivalDate
 ORDER BY TD.Id
</code>```

They way you use CASE if perfectly fine, yes. Columns you want to group by must be contained in the SELECT. Using a LEFT JOIN for the log entries ensures that you get also rows without corresponding log.

When grouping, each column you display must be either contained in the GROUP BY clause or in an aggregate function in the SELECT. So you have to think about why you are grouping, do you want to create a sum, count, ... ? >> Change the two CASE columns accordingly.

Body:
I have created a database of "trips" with the following

TripParent

Id

DrivingCompany

Client

TripDetails

Id

Destination

PlannedArrivalDate

StatusLog

Id

CatStatusId (Comes from another table just with the names)

DateTimeModified

Let me explain the tables, first of all I hid another fields to keep it simple, the "Parent" table has MANY TripDetails, so it is just a summary for the many "Details" it has. The TripDetails table its 1 row for 1 destination, let's say the Trip is going from A to C, then we have a Row for each "stop" (A, B, C).
And then we got the StatusLog table that has MANY Rows for each "TripDetails".

The problem is, I need a stored procedure that returns the DrivingCompany, Client, PlannedArrivalDate, RealArrivalDate and RealDepartureDate.

The "Real Dates" come from the StatusLog table. Status 1 means that the truck has arrived Destination (A/B/C) and the status 2 means that it has left said location.

So far I got the following

SELECT
    TP.DrivingCompany, TP.Client, TD.PlannedArrivalDate,
    'Real Arrival Date' = CASE SL.CatStatusId
                             WHEN 1 THEN SL.DateTimeModified
                             ELSE NULL
                          END,
   'Real Departure Date' = CASE SL.CatStatusId
                              WHEN 2 THEN SL.DateTimeModified
                              ELSE NULL
                           END
FROM
    TripParent TP
JOIN
    TripDetails TD ON TD.TripParentId = TE.Id
JOIN
    StatusLog SL ON SL.TripDetailsId = TD.Id
GROUP BY
    TP.Id
ORDER BY
    TD.Id

Is using the CASE the correct way to show the same column twice in the SELECT statement? I think I'm on the right track but I can't group by TP.Id and I also need to show ALL the rows, going by this query, It doesn't show the "TripDetails" that don't have a "StatusLog" row because they haven't arrived.

Any help is appreciated

Body:
Try this:

SELECT TP.Id,
       TP.DrivingCompany,
       TP.Client,
       TD.PlannedArrivalDate,
       'Real Arrival Date' = CASE SL.CatStatusId
                              WHEN 1 THEN SL.DateTimeModified
                              ELSE NULL
                             END,
       'Real Departure Date' = CASE SL.CatStatusId
                                WHEN 2 THEN SL.DateTimeModified
                                ELSE NULL
                               END
  FROM      TripParent TP
       JOIN TripDetails TD ON TD.TripParentId = TE.Id
  LEFT JOIN StatusLog SL ON SL.TripDetailsId = TD.Id
 GROUP BY TP.Id,
          TP.DrivingCompany,
          TP.Client,
          TD.PlannedArrivalDate
 ORDER BY TD.Id

They way you use CASE if perfectly fine, yes. Columns you want to group by must be contained in the SELECT. Using a LEFT JOIN for the log entries ensures that you get also rows without corresponding log.

When grouping, each column you display must be either contained in the GROUP BY clause or in an aggregate function in the SELECT. So you have to think about why you are grouping, do you want to create a sum, count, ... ? >> Change the two CASE columns accordingly.


问:
MVC Controller Create New Record
I am using c# MVC I am trying to create 2 new records in 2 tables - employee and address table.
I have the following so far:

```<code>    db.employee.AddObject(empmodel.employee);
    db.address.AddObject(empmodel.address);
    db.SaveChanges();
</code>```

When an employee record is created, it creates an EmpID record which is autogenerated. I need to get that EmpID and create a new record in the address table with that EmpID as as there is a primary foreign key relationship between the 2 tables.

I am not sure how to get the EmpID from employee table and then create a new record for the address table. I thought I could get it after AddObject but it did not create an employee record.

答:
This works for me:

```<code>db.Employees.Add(emp);
db.Savechanges();
</code>```

Go to this link for a complete tutorial:
https://www.youtube.com/watch?v=qOiwjbPmxSk

Title: MVC Controller Create New Record

Body:
I am using c# MVC I am trying to create 2 new records in 2 tables - employee and address table.
I have the following so far:

    db.employee.AddObject(empmodel.employee);
    db.address.AddObject(empmodel.address);
    db.SaveChanges();

When an employee record is created, it creates an EmpID record which is autogenerated. I need to get that EmpID and create a new record in the address table with that EmpID as as there is a primary foreign key relationship between the 2 tables.

I am not sure how to get the EmpID from employee table and then create a new record for the address table. I thought I could get it after AddObject but it did not create an employee record.

Body:
This works for me:

db.Employees.Add(emp);
db.Savechanges();

Go to this link for a complete tutorial:
https://www.youtube.com/watch?v=qOiwjbPmxSk


问:
HTML css margin pading content border
What is my problem? I cannot find a solution to make it look like this
Hello World box I'm not very good at coding but I'm trying to understand what I did wrong. Can someone help me please and fix my code?

.mano-modelis .content {
  content: "Hello World!";
  width: 300px;
  font-size: 1em;
  color: white;
  display: block;
  text-align: center;
  line-height: 300px;
  background-color: green;
}

.mano-modelis .padding {
  color: black;
  padding: 15px;
  width: 300px;
  height: 300px;
  position: relative;
  background: black;
}

.mano-modelis .border {
  padding: 15px;
  width: 300px;
  height: 300px;
  position: relative;
}

.mano-modelis .margin {
  background: blue;
  padding: 15px;
  width: 300px;
  height: 300px;
  position: relative;
  border: 2px;
  transition: all;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="mano-modelis">
  <div class="margin">
    <div class="border">
      <div class="padding">
        <div class="content">Hello world!</div>
      </div>
    </div>
  </div>
</div></code>```

答:
The issue stems from an outer DIV having padding and an inner DIV sharing the same width with an inner DIV. The inner DIV will start inside the padding and therefor overflows the outer DIV.

Here's a couple simplified solutions if you don't need all those extra elements.

One Element Using outline for Outer Border

body {
  margin: 0;
}

.mano-modelis {
  width: 300px;
  height: 300px;
  margin: 15px; /* provides buffer for outline below as outlines don't take up space. */
  padding: 15px;
  color: white;
  text-align: center;
  line-height: 300px;
  outline: 15px solid blue;
  border: 15px solid black;
  background-color: green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="mano-modelis">Hello world!</div></code>```

One Element Using ::before Pseudo Element for Outer Border

body {
  margin: 0;
}

.mano-modelis {
  position: relative;
  width: 300px;
  height: 300px;
  margin: 15px; /* Buffer space for pseudo element */
  padding: 15px;
  color: white;
  text-align: center;
  line-height: 300px;
  border: 15px solid black;
  background-color: green;
}

.mano-modelis::before {
  content: '';
  display: block;
  z-index: -1;
  position: absolute;
  top: -30px;
  right: -30px;
  bottom: -30px;
  left: -30px;
  background-color: blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="mano-modelis">Hello world!</div></code>```

There's additional solutions out there that I'm sure others will cover.

Title: HTML css margin pading content border

Body:
What is my problem? I cannot find a solution to make it look like this
Hello World box I'm not very good at coding but I'm trying to understand what I did wrong. Can someone help me please and fix my code?

.mano-modelis .content {
  content: "Hello World!";
  width: 300px;
  font-size: 1em;
  color: white;
  display: block;
  text-align: center;
  line-height: 300px;
  background-color: green;
}

.mano-modelis .padding {
  color: black;
  padding: 15px;
  width: 300px;
  height: 300px;
  position: relative;
  background: black;
}

.mano-modelis .border {
  padding: 15px;
  width: 300px;
  height: 300px;
  position: relative;
}

.mano-modelis .margin {
  background: blue;
  padding: 15px;
  width: 300px;
  height: 300px;
  position: relative;
  border: 2px;
  transition: all;
}

Hello world!

Body:
The issue stems from an outer DIV having padding and an inner DIV sharing the same width with an inner DIV. The inner DIV will start inside the padding and therefor overflows the outer DIV.

Here's a couple simplified solutions if you don't need all those extra elements.

One Element Using outline for Outer Border

body {
  margin: 0;
}

.mano-modelis {
  width: 300px;
  height: 300px;
  margin: 15px; /* provides buffer for outline below as outlines don't take up space. */
  padding: 15px;
  color: white;
  text-align: center;
  line-height: 300px;
  outline: 15px solid blue;
  border: 15px solid black;
  background-color: green;
}

<div class="mano-modelis">Hello world!</div>

One Element Using ::before Pseudo Element for Outer Border

body {
  margin: 0;
}

.mano-modelis {
  position: relative;
  width: 300px;
  height: 300px;
  margin: 15px; /* Buffer space for pseudo element */
  padding: 15px;
  color: white;
  text-align: center;
  line-height: 300px;
  border: 15px solid black;
  background-color: green;
}

.mano-modelis::before {
  content: '';
  display: block;
  z-index: -1;
  position: absolute;
  top: -30px;
  right: -30px;
  bottom: -30px;
  left: -30px;
  background-color: blue;
}

<div class="mano-modelis">Hello world!</div>

There's additional solutions out there that I'm sure others will cover.


问:
Javascript error, help please
I cant figure out why this is happening.

```<code>http://www.freemoviedb.com/watch/5749/28_weeks_later.html
</code>```

Click the thumb up / thumb down, it doesn't do anything but load.

In firebug, all it says is:

```<code>invalid 'in' operand a
http://static.freemoviedb.com/thumbsup/init.min.js.php
Line 1
</code>```

/

```<code>invalid 'in' operand a
error(Object { name="a"})init.min.js.php (line 1)
b()jquery.min.js (line 124)
abort(Object { name="q"})
</code>```

答:
The reason it breaks is the response, because of it being another domain, is null (thanks to the same origin policy), so this part:

```<code>success: function (a) {
  if ('error' in a) { //here's your error
</code>```

...fails, because the data from the response (a) will be null on a cross-domain request, and ("anything" in null) will throw the error you're seeing.

Title: Javascript error, help please

Body:
I cant figure out why this is happening.

http://www.freemoviedb.com/watch/5749/28_weeks_later.html

Click the thumb up / thumb down, it doesn't do anything but load.

In firebug, all it says is:

invalid 'in' operand a
http://static.freemoviedb.com/thumbsup/init.min.js.php
Line 1

/

invalid 'in' operand a
error(Object { name="a"})init.min.js.php (line 1)
b()jquery.min.js (line 124)
abort(Object { name="q"})

Body:
The reason it breaks is the response, because of it being another domain, is null (thanks to the same origin policy), so this part:

success: function (a) {
  if ('error' in a) { //here's your error

...fails, because the data from the response (a) will be null on a cross-domain request, and ("anything" in null) will throw the error you're seeing.


问:
i need an image to slide left and show another image underneath then slide back into place after a few seconds
I am trying to click on an image and have it slide away showing another image underneath. after a few second delay I need the first image to slide back over the other image. I'm not sure my html has correct id's.

CSS

```<code>.dr {
align-content: center;
}

.container {
width: 960px;
margin: 20px auto;
}

.contentl {
float: left;
width: 480px;
margin: 10px;
padding: 10px;
}

.contentr {
float: left;
width: 480px;
margin: 10px;
padding: 10px;
}
</code>```

(JS for one requirement that works, however I need the second image not to show until the first image is clicked on. )

```<code> <script>
$(document).ready(function(){

    $('img').load(function() {
        $(this).data('height', this.height);
    }).bind('mouseenter mouseleave', function(e) {
        $(this).stop().animate({
            height: $(this).data('height') * (e.type === 'mouseenter' ? 1.5
: 1)
        });
    });

});
</script>

<body>

<h1>Guessing Game</h1>

<div id="container">

<div id="contentl">
<p id="dr" align="center">
<img id="i1"
</code>```

src="file:///C:/Users/billi/Google%20Drive/School/INMD215/assignments/week%206/Media/gg%20media/door1.jpg" alt="Door One"/>

```<code><div id="contentr">
<p id="dr" align="center">
<img id="i1" src="file:///C:/Users/billi/Google%20Drive/School/INMD215/assignments/week%206/Media/gg%20media/door2.jpg" alt="Door Two"/>
<img id="i2" src="file:///C:/Users/billi/Google%20Drive/School/INMD215/assignments/week%206/Media/gg%20media/pog.png" alt="pot of gold"/>
    </p>
    </div>

</div>

</body>
</code>```

答:
Run this bad boy…

$(function(){
  $('.top_image').click(function(event){
    var $top_image = $(this);
    var $bottom_image = $('.bottom_image');

    $top_image.animate({
      left: '-150px'
    },function(){
      window.setTimeout(function(){
        $top_image.animate({left: '0px'});
      },2500); // wait 2.5 seconds before sliding back
    });

    $bottom_image.animate({opacity: 1}, 1000);
});
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.image_container{position:relative; width:150px; height:100px;margin:auto}
img{display:block; position:absolute}
.top_image{cursor:pointer}
.bottom_image{opacity:0}</code>```

<!DOCTYPE html>

```

Body:
I am trying to click on an image and have it slide away showing another image underneath. after a few second delay I need the first image to slide back over the other image. I'm not sure my html has correct id's.

CSS

.dr {
align-content: center;
}

.container {
width: 960px;
margin: 20px auto;
}

.contentl {
float: left;
width: 480px;
margin: 10px;
padding: 10px;
}

.contentr {
float: left;
width: 480px;
margin: 10px;
padding: 10px;
}

(JS for one requirement that works, however I need the second image not to show until the first image is clicked on. )

Guessing Game

<img id="i1"

src="file:///C:/Users/billi/Google%20Drive/School/INMD215/assignments/week%206/Media/gg%20media/door1.jpg" alt="Door One"/>

Body:
Run this bad boy…

$(function(){
  $('.top_image').click(function(event){
    var $top_image = $(this);
    var $bottom_image = $('.bottom_image');

    $top_image.animate({
      left: '-150px'
    },function(){
      window.setTimeout(function(){
        $top_image.animate({left: '0px'});
      },2500); // wait 2.5 seconds before sliding back
    });

    $bottom_image.animate({opacity: 1}, 1000);
});
});

.image_container{position:relative; width:150px; height:100px;margin:auto}
img{display:block; position:absolute}
.top_image{cursor:pointer}
.bottom_image{opacity:0}

<!DOCTYPE html>
<body>
<div class='image_container'>
  <img class='bottom_image' src='http://68.media.tumblr.com/a203e3d842f73161fbf13318a08d69ad/tumblr_nrxh7u6nwX1ts2l6wo1_250.jpg' width='150'/>
  <img class='top_image' src='https://www.pets4homes.co.uk/images/classifieds/2016/09/26/1403628/large/smooth-haired-miniature-dapple-dachshund-57ea690ac071a.jpg' width='150' />
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</body>
</html>


答:
I'm guessing you're aiming to get something like this...

.margin,
.border,
.padding,
.content {
  box-sizing: border-box;
}

.margin {
  padding: 15px;
  width: 300px;
  height: 300px;
  position: relative;
  background: blue;
}

.border {
  padding: 15px;
  width: 100%;
  height: 100%;
  position: relative;
}

.padding {
  padding: 15px;
  width: 100%;
  height: 100%;
  position: relative;
  background: black;
}

.content {
  text-align: center;
  line-height: 180px;
  margin: auto;
  color: white;
  padding: 10px;
  width: 100%;
  height: 100%;
  position: relative;
  background: green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="mano-modelis">
  <div class="margin">
    <div class="border">
      <div class="padding">
        <div class="content">Hello world!</div>
      </div>
    </div>
  </div>
</div></code>```

Title: HTML css margin pading content border

Body:
I'm guessing you're aiming to get something like this...

.margin,
.border,
.padding,
.content {
  box-sizing: border-box;
}

.margin {
  padding: 15px;
  width: 300px;
  height: 300px;
  position: relative;
  background: blue;
}

.border {
  padding: 15px;
  width: 100%;
  height: 100%;
  position: relative;
}

.padding {
  padding: 15px;
  width: 100%;
  height: 100%;
  position: relative;
  background: black;
}

.content {
  text-align: center;
  line-height: 180px;
  margin: auto;
  color: white;
  padding: 10px;
  width: 100%;
  height: 100%;
  position: relative;
  background: green;
}

<div class="mano-modelis">
  <div class="margin">
    <div class="border">
      <div class="padding">
        <div class="content">Hello world!</div>
      </div>
    </div>
  </div>
</div>