问:
I/O intensive serial port application: Porting from Threading, Queue based design to Asynchronous (ala Twisted)
So, I've been working on an application for a client that communicates with wireless devices via a Serial (RS-232) "Master". I've currently written the core of the app using threading (below). I've been noticing on #python that the consensus seems to be to NOT use threads and to use Twisted's asynchronous communication abilities.

I haven't been able to find any good examples of using twisted for serial port async I/O communication. However, I have found Dave Peticolas' 'Twisted Introduction' (thanks nosklo) that I'm currently working through, but, it uses sockets instead of serial communication (but the async concept is definitely very well explained).

How would I go about porting this app over to Twisted from using Threading, Queues? Are there any advantages/disadvantages (I have noticed that, on occasion, if a thread hangs it will BSOD the system)?

The Code (msg_poller.py)

```<code>from livedatafeed import LiveDataFeed
from msg_build import build_message_to_send
from utils import get_item_from_queue
from protocol_wrapper import ProtocolWrapper, ProtocolStatus
from crc16 import *
import time
import Queue
import threading
import serial
import gc

gc.enable()
PROTOCOL_HEADER = '\x01'
PROTOCOL_FOOTER = '\x0D\x0A'
PROTOCOL_DLE = '\x90'

INITIAL_MODBUS = 0xFFFF

class Poller:
    """
    Connects to the serial port and polls nodes for data.
    Reads response from node(s) and loads that data into queue.
    Parses qdata and writes that data to database.
    """

    def __init__(self,
            port,
            baudrate,
            parity,
            rtscts,
            xonxoff,
            echo=False):
        try:
            self.serial = serial.serial_for_url(port,
                    baudrate,
                    parity=parity,
                    rtscts=rtscts,
                    xonxoff=xonxoff,
                    timeout=.01)
        except AttributeError:
            self.serial = serial.Serial(port,
                    baudrate,
                    parity=parity,
                    rtscts=rtscts,
                    xonxoff=xonxoff,
                    timeout=.01)
            self.com_data_q = None
        self.com_error_q = None
        self.livefeed = LiveDataFeed()
        self.timer = time.time()
        self.dtr_state = True
        self.rts_state = True
        self.break_state = False

    def start(self):
        self.data_q = Queue.Queue()
        self.error_q = Queue.Queue()
        com_error = get_item_from_queue(self.error_q)
        if com_error is not None:
            print 'Error %s' % (com_error)
        self.timer = time.time()
        self.alive = True

        # start monitor thread
        #
        self.mon_thread = threading.Thread(target=self.reader)
        self.mon_thread.setDaemon(1)
        self.mon_thread.start()

        # start sending thread
        #
        self.trans_thread = threading.Thread(target=self.writer)
        self.trans_thread.setDaemon(1)
        self.trans_thread.start()

    def stop(self):
        try:
            self.alive = False
            self.serial.close()
        except (KeyboardInterrupt, SystemExit):
            self.alive = False

    def reader(self):
        """
        Reads data from the serial port using self.mon_thread.
        Displays that data on the screen.
        """
        from rmsg_format import message_crc, message_format
        while self.alive:
            try:
                while self.serial.inWaiting() != 0:

                # Read node data from the serial port. Data should be 96B.

                    data = self.serial.read(96)
                    data += self.serial.read(self.serial.inWaiting())

                    if len(data) > 0:

                        # Put data in to the data_q object
                        self.data_q.put(data)
                        if len(data) == 96:
                            msg = self.data_q.get()

                            pw = ProtocolWrapper(
                                        header=PROTOCOL_HEADER,
                                        footer=PROTOCOL_FOOTER,
                                        dle=PROTOCOL_DLE)
                            status = map(pw.input, msg)

                            if status[-1] == ProtocolStatus.IN_MSG:
                                # Feed all the bytes of 'msg' sequentially into pw.input

                                # Parse the received CRC into a 16-bit integer
                                rec_crc = message_crc.parse(msg[-4:]).crc

                                # Compute the CRC on the message
                                calc_crc = calcString(msg[:-4], INITIAL_MODBUS)
                                from datetime import datetime
                                ts = datetime.now().strftime('%Y/%m/%d %H:%M:%S')
                                if rec_crc != calc_crc:
                                    print ts
                                    print 'ERROR: CRC Mismatch'
                                    print msg.encode('hex')
                                else:
                                    #msg = message_format.parse(msg[1:])
                                    #print msg.encode('hex') + "\r\n"
                                    msg = message_format.parse(msg[1:])
                                    print msg
                                    #return msg
                                    gc.collect()
                    time.sleep(.2)
            except (KeyboardInterrupt, SystemExit, Exception, TypeError):
                self.alive = False
                self.serial.close()
                raise

    def writer(self):
        """
        Builds the packet to poll each node for data.
        Writes that data to the serial port using self.trans_thread
        """
        import time
        try:
            while self.alive:
                try:
                    dest_module_code = ['DRILLRIG',
                            'POWERPLANT',
                            'GENSET',
                            'MUDPUMP']
                    dest_ser_no = lambda x: x + 1
                    for code in dest_module_code:
                        if code != 'POWERPLANT':
                            msg = build_message_to_send(
                                    data_len=0x10,
                                    dest_module_code='%s' % (code),
                                    dest_ser_no=dest_ser_no(0),
                                    dest_customer_code='*****',
                                    ret_ser_no=0x01,
                                    ret_module_code='DOGHOUSE',
                                    ret_customer_code='*****',
                                    command='POLL_NODE',
                                    data=[])
                            self.serial.write(msg)
                            time.sleep(.2)
                            gc.collect()
                        elif code == 'POWERPLANT':
                            msg = build_message_to_send(
                                    data_len=0x10,
                                    dest_module_code='POWERPLANT',
                                    dest_ser_no=dest_ser_no(0),
                                    dest_customer_code='*****',
                                    ret_ser_no=0x01,
                                    ret_module_code='DOGHOUSE',
                                    ret_customer_code='*****',
                                    command='POLL_NODE',
                                    data=[])
                            self.serial.write(msg)
                            time.sleep(.2)
                            gc.collect()
                            msg = build_message_to_send(
                                    data_len=0x10,
                                    dest_module_code='POWERPLANT',
                                    dest_ser_no=dest_ser_no(1),
                                    dest_customer_code='*****',
                                    ret_ser_no=0x01,
                                    ret_module_code='DOGHOUSE',
                                    ret_customer_code='*****',
                                    command='POLL_NODE',
                                    data=[])
                            self.serial.write(msg)
                            time.sleep(.2)
                            gc.collect()
                except (KeyboardInterrupt, SystemExit):
                    self.alive = False
                    self.serial.close()
                    raise
        except (KeyboardInterrupt, SystemExit):
            self.alive = False
            self.serial.close()
            raise

def main():
    poller = Poller(
            port='COM4',
            baudrate=115200,
            parity=serial.PARITY_NONE,
            rtscts=0,
            xonxoff=0,
            )
    poller.start()
    poller.reader()
    poller.writer()
    poller.stop()
if __name__ == '__main__':
    main()
</code>```

答:
It is very difficult (if not impossible) to write a direct one-to-one mapping program between threading/queue approach and one that uses twisted.

I would suggest that, get a hang of twisted and its reactor way it's use of Protocol and the protocol specific methods. Think about it as as all the asynchronous things that you had been explicitly coding using threads and queues are given to you for free when you are using deferred using twisted.

twisted does seem to support SerialPort over it's reactor using SerialPort transport class and the basic structure seems to be somewhat like this.

```<code>from twisted.internet import reactor
from twisted.internet.serialport import SerialPort

SerialPort(YourProtocolClass(), Port, reactor, baudrate=baudrate))
reactor.run()
</code>```

In YourProtocolClass() would you handle the various events that are specific to your Serial Port Communication requirements.  The doc/core/examples directory contains examples such as gpsfix.py and mouse.py.

Body:
So, I've been working on an application for a client that communicates with wireless devices via a Serial (RS-232) "Master". I've currently written the core of the app using threading (below). I've been noticing on #python that the consensus seems to be to NOT use threads and to use Twisted's asynchronous communication abilities.

I haven't been able to find any good examples of using twisted for serial port async I/O communication. However, I have found Dave Peticolas' 'Twisted Introduction' (thanks nosklo) that I'm currently working through, but, it uses sockets instead of serial communication (but the async concept is definitely very well explained).

How would I go about porting this app over to Twisted from using Threading, Queues? Are there any advantages/disadvantages (I have noticed that, on occasion, if a thread hangs it will BSOD the system)?

The Code (msg_poller.py)

from livedatafeed import LiveDataFeed
from msg_build import build_message_to_send
from utils import get_item_from_queue
from protocol_wrapper import ProtocolWrapper, ProtocolStatus
from crc16 import *
import time
import Queue
import threading
import serial
import gc

gc.enable()
PROTOCOL_HEADER = '\x01'
PROTOCOL_FOOTER = '\x0D\x0A'
PROTOCOL_DLE = '\x90'

INITIAL_MODBUS = 0xFFFF

class Poller:
    """
    Connects to the serial port and polls nodes for data.
    Reads response from node(s) and loads that data into queue.
    Parses qdata and writes that data to database.
    """

    def __init__(self,
            port,
            baudrate,
            parity,
            rtscts,
            xonxoff,
            echo=False):
        try:
            self.serial = serial.serial_for_url(port,
                    baudrate,
                    parity=parity,
                    rtscts=rtscts,
                    xonxoff=xonxoff,
                    timeout=.01)
        except AttributeError:
            self.serial = serial.Serial(port,
                    baudrate,
                    parity=parity,
                    rtscts=rtscts,
                    xonxoff=xonxoff,
                    timeout=.01)
            self.com_data_q = None
        self.com_error_q = None
        self.livefeed = LiveDataFeed()
        self.timer = time.time()
        self.dtr_state = True
        self.rts_state = True
        self.break_state = False

    def start(self):
        self.data_q = Queue.Queue()
        self.error_q = Queue.Queue()
        com_error = get_item_from_queue(self.error_q)
        if com_error is not None:
            print 'Error %s' % (com_error)
        self.timer = time.time()
        self.alive = True

        # start monitor thread
        #
        self.mon_thread = threading.Thread(target=self.reader)
        self.mon_thread.setDaemon(1)
        self.mon_thread.start()

        # start sending thread
        #
        self.trans_thread = threading.Thread(target=self.writer)
        self.trans_thread.setDaemon(1)
        self.trans_thread.start()

    def stop(self):
        try:
            self.alive = False
            self.serial.close()
        except (KeyboardInterrupt, SystemExit):
            self.alive = False

    def reader(self):
        """
        Reads data from the serial port using self.mon_thread.
        Displays that data on the screen.
        """
        from rmsg_format import message_crc, message_format
        while self.alive:
            try:
                while self.serial.inWaiting() != 0:

                # Read node data from the serial port. Data should be 96B.

                    data = self.serial.read(96)
                    data += self.serial.read(self.serial.inWaiting())

                    if len(data) > 0:

                        # Put data in to the data_q object
                        self.data_q.put(data)
                        if len(data) == 96:
                            msg = self.data_q.get()

                            pw = ProtocolWrapper(
                                        header=PROTOCOL_HEADER,
                                        footer=PROTOCOL_FOOTER,
                                        dle=PROTOCOL_DLE)
                            status = map(pw.input, msg)

                            if status[-1] == ProtocolStatus.IN_MSG:
                                # Feed all the bytes of 'msg' sequentially into pw.input

                                # Parse the received CRC into a 16-bit integer
                                rec_crc = message_crc.parse(msg[-4:]).crc

                                # Compute the CRC on the message
                                calc_crc = calcString(msg[:-4], INITIAL_MODBUS)
                                from datetime import datetime
                                ts = datetime.now().strftime('%Y/%m/%d %H:%M:%S')
                                if rec_crc != calc_crc:
                                    print ts
                                    print 'ERROR: CRC Mismatch'
                                    print msg.encode('hex')
                                else:
                                    #msg = message_format.parse(msg[1:])
                                    #print msg.encode('hex') + "\r\n"
                                    msg = message_format.parse(msg[1:])
                                    print msg
                                    #return msg
                                    gc.collect()
                    time.sleep(.2)
            except (KeyboardInterrupt, SystemExit, Exception, TypeError):
                self.alive = False
                self.serial.close()
                raise

    def writer(self):
        """
        Builds the packet to poll each node for data.
        Writes that data to the serial port using self.trans_thread
        """
        import time
        try:
            while self.alive:
                try:
                    dest_module_code = ['DRILLRIG',
                            'POWERPLANT',
                            'GENSET',
                            'MUDPUMP']
                    dest_ser_no = lambda x: x + 1
                    for code in dest_module_code:
                        if code != 'POWERPLANT':
                            msg = build_message_to_send(
                                    data_len=0x10,
                                    dest_module_code='%s' % (code),
                                    dest_ser_no=dest_ser_no(0),
                                    dest_customer_code='*****',
                                    ret_ser_no=0x01,
                                    ret_module_code='DOGHOUSE',
                                    ret_customer_code='*****',
                                    command='POLL_NODE',
                                    data=[])
                            self.serial.write(msg)
                            time.sleep(.2)
                            gc.collect()
                        elif code == 'POWERPLANT':
                            msg = build_message_to_send(
                                    data_len=0x10,
                                    dest_module_code='POWERPLANT',
                                    dest_ser_no=dest_ser_no(0),
                                    dest_customer_code='*****',
                                    ret_ser_no=0x01,
                                    ret_module_code='DOGHOUSE',
                                    ret_customer_code='*****',
                                    command='POLL_NODE',
                                    data=[])
                            self.serial.write(msg)
                            time.sleep(.2)
                            gc.collect()
                            msg = build_message_to_send(
                                    data_len=0x10,
                                    dest_module_code='POWERPLANT',
                                    dest_ser_no=dest_ser_no(1),
                                    dest_customer_code='*****',
                                    ret_ser_no=0x01,
                                    ret_module_code='DOGHOUSE',
                                    ret_customer_code='*****',
                                    command='POLL_NODE',
                                    data=[])
                            self.serial.write(msg)
                            time.sleep(.2)
                            gc.collect()
                except (KeyboardInterrupt, SystemExit):
                    self.alive = False
                    self.serial.close()
                    raise
        except (KeyboardInterrupt, SystemExit):
            self.alive = False
            self.serial.close()
            raise

def main():
    poller = Poller(
            port='COM4',
            baudrate=115200,
            parity=serial.PARITY_NONE,
            rtscts=0,
            xonxoff=0,
            )
    poller.start()
    poller.reader()
    poller.writer()
    poller.stop()
if __name__ == '__main__':
    main()

Body:
It is very difficult (if not impossible) to write a direct one-to-one mapping program between threading/queue approach and one that uses twisted.

I would suggest that, get a hang of twisted and its reactor way it's use of Protocol and the protocol specific methods. Think about it as as all the asynchronous things that you had been explicitly coding using threads and queues are given to you for free when you are using deferred using twisted.

twisted does seem to support SerialPort over it's reactor using SerialPort transport class and the basic structure seems to be somewhat like this.

from twisted.internet import reactor
from twisted.internet.serialport import SerialPort

SerialPort(YourProtocolClass(), Port, reactor, baudrate=baudrate))
reactor.run()

In YourProtocolClass() would you handle the various events that are specific to your Serial Port Communication requirements.  The doc/core/examples directory contains examples such as gpsfix.py and mouse.py.


来源: stackexchange

问:
HTTP 404 error when debugging in Asp.net MVC5
I am new to MVC. I am trying to create a simple user registration process

When I try to run the application I have the error  HTTP 404.
The resource cannot be found.
Requested URL: /Mvc_Web_Project/Views/CreateNewUser/AddUser.cshtml

Solution i found online did not solve the issue

RouteConfig.cs

```<code>public static void RegisterRoutes(RouteCollection routes)
    {

      routes.MapRoute(
      name: "Default",
      url: "{controller}/{action}/{id}",
      defaults: new { controller = "CreateNewUser", action = "AddUser", id = UrlParameter.Optional }
        );
    }
</code>```

Controller.cs

```<code>using System.Web.Mvc;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
using Mvc_Web_Project.Models;

 namespace Mvc_Web_Project.Controllers
 {
   public class CreateNewUserController : Controller
   {
    private SqlConnection con;
    private void connection()
    {
        string constr = ConfigurationManager.ConnectionStrings["Molecular"].ToString();
        con = new SqlConnection(constr);
    }

    // GET: CreateNewUser
    public ActionResult AddUser(AddUserModel CreateNewUser)
    {
        //To Prevent firing validation error on first page Load

        if (ModelState.IsValid)
        {
            connection();
            SqlCommand com = new SqlCommand("AddUser", con);
            com.CommandType = CommandType.StoredProcedure;
            com.Parameters.AddWithValue("@Email", CreateNewUser.Email);
            com.Parameters.AddWithValue("@Password", CreateNewUser.Password);
            com.Parameters.AddWithValue("@Type", CreateNewUser.Type);
            con.Open();
            int i = com.ExecuteNonQuery();
            con.Close();
            if (i >= 1)
            {
                ViewBag.Message = "New User Added Successfully";
            }
        }
        ModelState.Clear();
        return View();
    }
   }
  }
</code>```

cshtml

```<code>   @model Mvc_Web_Project.Models.AddUserModel
@{
ViewBag.Title = "Create New User";
Layout = "~/Views/Shared/_Layout.cshtml";
  }

<h2>AddUser</h2>

  @using (Html.BeginForm())
  {
    @Html.ValidationSummary(true)

<fieldset>
    <legend> AddUserModel</legend>

    <div class="editor-label">
        @Html.LabelFor(model => model.Email)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Email)
        @Html.ValidationMessageFor(model => model.Email)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.Password)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Password)
        @Html.ValidationMessageFor(model => model.Password)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.Type)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Type)
        @Html.ValidationMessageFor(model => model.Type)
    </div>

    <p>
        <input type="submit" value="Save details" />
    </p>

</fieldset>
 }
</code>```

答:
It looks like the Start Action for your ASP.NET Web Application is set to Current Page, which, in your case, is causing Visual Studio to launch a browser that navigates to the /Mvc_Web_Project/Views/CreateNewUser/AddUser.cshtml path.

To change this, one option is to go to the Project Properties window and change from Current Page to Specific Page and use an empty value, which will cause the browser to always navigate to the root of the application:

Here's a link to the docs that explains the options in more detail.

ContentLicense: CC BY-SA 3.0

Body:
I am new to MVC. I am trying to create a simple user registration process

When I try to run the application I have the error  HTTP 404.
The resource cannot be found.
Requested URL: /Mvc_Web_Project/Views/CreateNewUser/AddUser.cshtml

Solution i found online did not solve the issue

RouteConfig.cs

public static void RegisterRoutes(RouteCollection routes)
    {

      routes.MapRoute(
      name: "Default",
      url: "{controller}/{action}/{id}",
      defaults: new { controller = "CreateNewUser", action = "AddUser", id = UrlParameter.Optional }
        );
    }

Controller.cs

using System.Web.Mvc;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
using Mvc_Web_Project.Models;

 namespace Mvc_Web_Project.Controllers
 {
   public class CreateNewUserController : Controller
   {
    private SqlConnection con;
    private void connection()
    {
        string constr = ConfigurationManager.ConnectionStrings["Molecular"].ToString();
        con = new SqlConnection(constr);
    }

    // GET: CreateNewUser
    public ActionResult AddUser(AddUserModel CreateNewUser)
    {
        //To Prevent firing validation error on first page Load

        if (ModelState.IsValid)
        {
            connection();
            SqlCommand com = new SqlCommand("AddUser", con);
            com.CommandType = CommandType.StoredProcedure;
            com.Parameters.AddWithValue("@Email", CreateNewUser.Email);
            com.Parameters.AddWithValue("@Password", CreateNewUser.Password);
            com.Parameters.AddWithValue("@Type", CreateNewUser.Type);
            con.Open();
            int i = com.ExecuteNonQuery();
            con.Close();
            if (i >= 1)
            {
                ViewBag.Message = "New User Added Successfully";
            }
        }
        ModelState.Clear();
        return View();
    }
   }
  }

cshtml

   @model Mvc_Web_Project.Models.AddUserModel
@{
ViewBag.Title = "Create New User";
Layout = "~/Views/Shared/_Layout.cshtml";
  }

AddUser

  @using (Html.BeginForm())
  {
    @Html.ValidationSummary(true)

<fieldset>
    <legend> AddUserModel</legend>

        @Html.LabelFor(model => model.Email)

        @Html.EditorFor(model => model.Email)
        @Html.ValidationMessageFor(model => model.Email)

        @Html.LabelFor(model => model.Password)

        @Html.EditorFor(model => model.Password)
        @Html.ValidationMessageFor(model => model.Password)

        @Html.LabelFor(model => model.Type)

        @Html.EditorFor(model => model.Type)
        @Html.ValidationMessageFor(model => model.Type)

        <input type="submit" value="Save details" />

</fieldset>
 }

ContentLicense: CC BY-SA 4.0


问:
How to combine post table and image table using sql left join and union
How do i combine 3 tables user table, post table and image table to display post with image and post without image
using sql inner join, left join and union.

Table Users

```<code>userid | uname |  pagename
-------|-------|-----
801    | peter |  a1
2      | john  |
</code>```

Table Post

```<code>postid | postuserid | message
-------|------------|--------------
10     |  801       | This is post without image
101    |  801       | This is post with 2 images
102    |  801       | This is post with 1 image
</code>```

Table Images

```<code>img | imgpostid | url
----|-----------|------------
1   | 101       | image1.png
2   | 101       | image2.png
3   | 102       | image01.png
</code>```

My SQL Query

```<code>SELECT * FROM Post pt
INNER JOIN Users us
ON pt.postuserid = us.userid
LEFT JOIN Images im
ON pt.postid = im.imgpostid
WHERE us.pagename = 'a1'
AND us.userid = 801
</code>```

Expected result

```<code>This is post without image
This is post with 2 images [IMAGE1.PNG],[IMAGE2.PNG]
This is post with 1 image [IMAGE01.PNG]
</code>```

The result i get

```<code>This is post without image
This is post with 2 images [IMAGE2.PNG]
This is post with 2 images [IMAGE2.PNG]
This is post with 1 image [IMAGE01.PNG]
</code>```

答:
Try this and see if it works:

```<code>SELECT * FROM users
LEFT JOIN posts
ON users.userid = posts.postuserid
LEFT JOIN images
ON posts.postid = images.imgpostid
WHERE users.pagename = 'a1'
AND users.userid = 801
</code>```

P.S: The query is not tested due I don't know your exact db schema

Body:
How do i combine 3 tables user table, post table and image table to display post with image and post without image
using sql inner join, left join and union.

Table Users

userid | uname |  pagename
-------|-------|-----
801    | peter |  a1
2      | john  |

Table Post

postid | postuserid | message
-------|------------|--------------
10     |  801       | This is post without image
101    |  801       | This is post with 2 images
102    |  801       | This is post with 1 image

Table Images

img | imgpostid | url
----|-----------|------------
1   | 101       | image1.png
2   | 101       | image2.png
3   | 102       | image01.png

My SQL Query

SELECT * FROM Post pt
INNER JOIN Users us
ON pt.postuserid = us.userid
LEFT JOIN Images im
ON pt.postid = im.imgpostid
WHERE us.pagename = 'a1'
AND us.userid = 801

Expected result

This is post without image
This is post with 2 images [IMAGE1.PNG],[IMAGE2.PNG]
This is post with 1 image [IMAGE01.PNG]

The result i get

This is post without image
This is post with 2 images [IMAGE2.PNG]
This is post with 2 images [IMAGE2.PNG]
This is post with 1 image [IMAGE01.PNG]

Body:
Try this and see if it works:

SELECT * FROM users
LEFT JOIN posts
ON users.userid = posts.postuserid
LEFT JOIN images
ON posts.postid = images.imgpostid
WHERE users.pagename = 'a1'
AND users.userid = 801

P.S: The query is not tested due I don't know your exact db schema


问:
How to add Custom Thumbnail in Home Page in blogger?
I want to add a custom thumbnail to my home page. Like when i share my website to social networking sites, I want my custom thumbnail to be previewed. What should I do to achieve this? Please help me.

My site is http://www.technocombo.com on which if i share it to social networking sites, shows my favicon as thumbnail. PLEASE HELP!

答:
you have to use Open Graph to do it.

```<code><meta name="twitter:card" content="summary">
<meta name="twitter:site" content="...">
<meta property="og:url" content="...">
<meta property="og:title" content="...">
<meta property="og:description"...">
<meta name="description" content="...">
<meta property="og:image" content="...">
<meta property="og:image:type" content="image/jpg">
<meta property="og:image:alt" content="...">
</code>```

and then look at the result

https://cards-dev.twitter.com/validator

https://developers.facebook.com/tools/debug/

Body:
you have to use Open Graph to do it.

<meta name="twitter:card" content="summary">
<meta name="twitter:site" content="...">
<meta property="og:url" content="...">
<meta property="og:title" content="...">
<meta property="og:description"...">
<meta name="description" content="...">
<meta property="og:image" content="...">
<meta property="og:image:type" content="image/jpg">
<meta property="og:image:alt" content="...">

and then look at the result

https://cards-dev.twitter.com/validator

https://developers.facebook.com/tools/debug/


问:
EditText changes background color after focus
I have an EditText inside CardView which changes its background color after gaining focus, like writing text in it. I want it to be like the second picture.

Before focus:

After focus:

Code:

```<code><android.support.v7.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="56dp"
    android:clickable="true"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:foreground="?android:attr/selectableItemBackground">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/transparent"
        android:drawableLeft="@drawable/ic_search"
        android:drawablePadding="16dp"
        android:drawableStart="@drawable/ic_search"
        android:hint="@string/search_library"
        android:imeOptions="actionSearch"
        android:inputType="textCapSentences"
        android:padding="16dp"
        android:textSize="16sp"/>
</android.support.v7.widget.CardView>
</code>```

答:
Use selector for changing back ground when edittext focused.

```<code><selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_focused="true" android:drawable="@drawable/edittext_focused" />
    <item android:state_focused="false" android:drawable="@drawable/edittext_notfocused" />
</selector>
</code>```

then add your preferences in edittext_focused.xml file.

Body:
I have an EditText inside CardView which changes its background color after gaining focus, like writing text in it. I want it to be like the second picture.

Before focus:

After focus:

Code:

<android.support.v7.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="56dp"
    android:clickable="true"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:foreground="?android:attr/selectableItemBackground">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/transparent"
        android:drawableLeft="@drawable/ic_search"
        android:drawablePadding="16dp"
        android:drawableStart="@drawable/ic_search"
        android:hint="@string/search_library"
        android:imeOptions="actionSearch"
        android:inputType="textCapSentences"
        android:padding="16dp"
        android:textSize="16sp"/>
</android.support.v7.widget.CardView>

Body:
Use selector for changing back ground when edittext focused.

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_focused="true" android:drawable="@drawable/edittext_focused" />
    <item android:state_focused="false" android:drawable="@drawable/edittext_notfocused" />
</selector>

then add your preferences in edittext_focused.xml file.


问:
I'm trying to send the states to the parents components. But do not get it
How do I send the stats from FMoStep1.js to the wizard in the formSaves array? I tried to pass the stats to the wizard with the method handleFormSubmit but it does not work.

Then, there is also a problem with step changing, it does not change from FMoStep1 to FMoStep2.

Wizard.js

```<code>import React, { Component } from 'react';

import FMoStep1 from './FMoStep1';
import FMoStep2 from './FMoStep2';
import FMoStep3 from './FMoStep3';

import { states } from './States'
import { StateMachine } from './StateMachine.js';

class Wizard extends Component {
    constructor(props) {
        super(props);

        this.state = {
            currentState: states.FMoStep1,
            formSaves: []
        }

        this.saveForm = this.saveForm.bind(this);
        this.nextStep = this.nextStep.bind(this);
        this.backStep = this.backStep.bind(this);
        this.stateMachine = new StateMachine();
    }

    nextStep(desiredState) {
        let currentState = this.state.currentState;
        let nextState = this.stateMachine.transitionTo(currentState, desiredState);
        this.setState({
            currentState: nextState
        });
    }

    backStep(desiredState) {
        let currentState = this.state.currentState;
        this.setState({
            currentState: this.stateMachine.transitionFrom(currentState, desiredState)
        });
    }

    saveForm(formSave) {
        let formSaves = this.state.formSaves.concat();
        formSaves.push(formSave);
        this.setState({
            formSaves: formSaves
        });
    }

    //Switch Case Methode um den CurrentStep zu bestimmen
    currentStep() {
        switch (this.state.currentState) {
            case states.FMoStep1:
            return (
                <FMoStep1
                    saveForm={this.saveForm}
                    back={this.backStep}
                    next={this.nextStep} />
            );
            case states.FMoStep2:
            return (
                <FMoStep2
                    saveForm={this.saveForm}
                    back={this.backStep}
                    next={this.nextStep} />
                );
            case states.FMoStep3:
            return (
                <FMoStep3
                    saveForm={this.saveForm}
                    back={this.backStep}
                    next={this.nextStep} />
                );
            default:
            break;
        }
    }

    render() {
        return (
            <div>{ this.currentStep() }</div>
        );
    }
}
export default Wizard;
</code>```

FMoStep1

```<code>import React, { Component } from 'react';

import SingleInput from './SingleInput';
import TextArea from './TextArea';

class FMoStep1 extends Component {
    constructor(props) {
        super(props);

        this.state = {
            modultitel: '',
            startdate: '',
            enddate: '',
            modulkuerzel: '',
            modulDescription: ''
        };

        this.handleModultitel = this.handleModultitel.bind(this);
        this.handleStartdate = this.handleStartdate.bind(this);
        this.handleEnddate = this.handleEnddate.bind(this);
        this.handleModulkuerzel = this.handleModulkuerzel.bind(this);
        this.handlemodulDescriptionChange = this.handlemodulDescriptionChange.bind(this);
        this.handleClearForm = this.handleClearForm.bind(this);
        this.handleFormSubmit = this.handleFormSubmit.bind(this);
    }

    handleModultitel(e) {
        this.setState(
            { modultitel: e.target.value },
            () => console.log('modultitel:', this.state.modultitel)
        );
    }

    handleStartdate(e) {
        this.setState(
            { startdate: e.target.value },
            () => console.log('startdate:', this.state.startdate)
        );
    }

    handleEnddate(e) {
        this.setState(
            { enddate: e.target.value },
            () => console.log('enddate:', this.state.enddate)
        );
    }

    handleModulkuerzel(e) {
        this.setState(
            { modulkuerzel: e.target.value },
            () => console.log('modulkuerzel', this.state.modulkuerzel)
        );
    }

    handlemodulDescriptionChange(e) {
        this.setState(
            { modulDescription: e.target.value },
            () => console.log('modulDescription', this.state.modulDescription)
        );
    }

    handleClearForm(e) {
        e.preventDefault();
        this.setState({
            modultitel: '',
            startdate: '',
            enddate: '',
            modulkuerzel: '',
            modulDescription: ''
        });
    }

    handleFormSubmit(e) {
        e.preventDefault();

        const formPayload = {
            modultitel: this.state.modultitel,
            startdate: this.state.startdate,
            enddate: this.state.enddate,
            modulkuerzel: this.state.modulkuerzel,
            modulDescription: this.state.modulDescription
        };
        console.log('send befor', formPayload)
        this.props.next(this.props.nextState);

        console.log('Send this in a Post request:', this.state);
        //States übertragen in die Session
        this.props.saveForm(formPayload);

        this.handleClearForm(e);
    }

    render() {
        return (
            <form>
                <h5>Modul anlegen (Schritt 1 von x)</h5>
                <SingleInput
                    inputType={'text'}
                    title={'Modultitel: '}
                    name={'name'}
                    controlFunc={this.handleModultitel}
                    content={this.state.modultitel}
                    placeholder={'Modultitel'} />
                <SingleInput
                    inputType={'text'}
                    title={'Gültig ab: '}
                    name={'Startdate'}
                    controlFunc={this.handleStartdate}
                    content={this.state.startdate}
                    placeholder={'Startdatum'} />
                <SingleInput
                    inputType={'text'}
                    title={'Gültig bis: '}
                    name={'Enddate'}
                    controlFunc={this.handleEnddate}
                    content={this.state.enddate}
                    placeholder={'Enddatum'} />
                <SingleInput
                    inputType={'text'}
                    title={'Modulkürzel'}
                    name={'Modulkürzel'}
                    controlFunc={this.handleModulkuerzel}
                    content={this.state.modulkuerzel}
                    placeholder={'Modulkützel'} />
                <TextArea
                    title={'Kurzbeschreibung'}
                    rows={5}
                    name={'Kurzbeschreibung'}
                    resize={false}
                    content={this.state.modulDescription}
                    controlFunc={this.handlemodulDescriptionChange}
                    placeholder={'Kurzbeschreibung zu Modulen'} />
                <button
                    onClick={this.handleFormSubmit}>Weiter</button>
                <button
                    onClick={this.handleClearForm}>Clear form</button>
            </form>
        );
    }
}

export default FMoStep1;
</code>```

Thank you!

答:
You are relying on the nextState prop to navigate to the nextState in the the FMoStep1 component which you aren't supplying. Pass then and it should work

```<code>  switch (this.state.currentState) {
        case states.FMoStep1:
            return <FMoStep1
                saveForm={this.saveForm}
                nextState={states.FMoStep2}
                back={this.backStep}
                next={this.nextStep}
                />;
        case states.FMoStep2:
            return (<FMoStep2
                saveForm={this.saveForm}
                nextState={states.FMoStep3}
                back={this.backStep}
                next={this.nextStep}
            />);
        case states.FMoStep3:
            return (<FMoStep3
                saveForm={this.saveForm}
                back={this.backStep}
                next={this.nextStep}
            />);

        default:
            break;
    }
</code>```

P.S. However I would suggest you to restructure your code and maybe use routes instead of conditional rendering of the components

Body:
How do I send the stats from FMoStep1.js to the wizard in the formSaves array? I tried to pass the stats to the wizard with the method handleFormSubmit but it does not work.

Then, there is also a problem with step changing, it does not change from FMoStep1 to FMoStep2.

Wizard.js

import React, { Component } from 'react';

import FMoStep1 from './FMoStep1';
import FMoStep2 from './FMoStep2';
import FMoStep3 from './FMoStep3';

import { states } from './States'
import { StateMachine } from './StateMachine.js';

class Wizard extends Component {
    constructor(props) {
        super(props);

        this.state = {
            currentState: states.FMoStep1,
            formSaves: []
        }

        this.saveForm = this.saveForm.bind(this);
        this.nextStep = this.nextStep.bind(this);
        this.backStep = this.backStep.bind(this);
        this.stateMachine = new StateMachine();
    }

    nextStep(desiredState) {
        let currentState = this.state.currentState;
        let nextState = this.stateMachine.transitionTo(currentState, desiredState);
        this.setState({
            currentState: nextState
        });
    }

    backStep(desiredState) {
        let currentState = this.state.currentState;
        this.setState({
            currentState: this.stateMachine.transitionFrom(currentState, desiredState)
        });
    }

    saveForm(formSave) {
        let formSaves = this.state.formSaves.concat();
        formSaves.push(formSave);
        this.setState({
            formSaves: formSaves
        });
    }

    //Switch Case Methode um den CurrentStep zu bestimmen
    currentStep() {
        switch (this.state.currentState) {
            case states.FMoStep1:
            return (
                <FMoStep1
                    saveForm={this.saveForm}
                    back={this.backStep}
                    next={this.nextStep} />
            );
            case states.FMoStep2:
            return (
                <FMoStep2
                    saveForm={this.saveForm}
                    back={this.backStep}
                    next={this.nextStep} />
                );
            case states.FMoStep3:
            return (
                <FMoStep3
                    saveForm={this.saveForm}
                    back={this.backStep}
                    next={this.nextStep} />
                );
            default:
            break;
        }
    }

    render() {
        return (

{ this.currentStep() }

        );
    }
}
export default Wizard;

FMoStep1

import React, { Component } from 'react';

import SingleInput from './SingleInput';
import TextArea from './TextArea';

class FMoStep1 extends Component {
    constructor(props) {
        super(props);

        this.state = {
            modultitel: '',
            startdate: '',
            enddate: '',
            modulkuerzel: '',
            modulDescription: ''
        };

        this.handleModultitel = this.handleModultitel.bind(this);
        this.handleStartdate = this.handleStartdate.bind(this);
        this.handleEnddate = this.handleEnddate.bind(this);
        this.handleModulkuerzel = this.handleModulkuerzel.bind(this);
        this.handlemodulDescriptionChange = this.handlemodulDescriptionChange.bind(this);
        this.handleClearForm = this.handleClearForm.bind(this);
        this.handleFormSubmit = this.handleFormSubmit.bind(this);
    }

    handleModultitel(e) {
        this.setState(
            { modultitel: e.target.value },
            () => console.log('modultitel:', this.state.modultitel)
        );
    }

    handleStartdate(e) {
        this.setState(
            { startdate: e.target.value },
            () => console.log('startdate:', this.state.startdate)
        );
    }

    handleEnddate(e) {
        this.setState(
            { enddate: e.target.value },
            () => console.log('enddate:', this.state.enddate)
        );
    }

    handleModulkuerzel(e) {
        this.setState(
            { modulkuerzel: e.target.value },
            () => console.log('modulkuerzel', this.state.modulkuerzel)
        );
    }

    handlemodulDescriptionChange(e) {
        this.setState(
            { modulDescription: e.target.value },
            () => console.log('modulDescription', this.state.modulDescription)
        );
    }

    handleClearForm(e) {
        e.preventDefault();
        this.setState({
            modultitel: '',
            startdate: '',
            enddate: '',
            modulkuerzel: '',
            modulDescription: ''
        });
    }

    handleFormSubmit(e) {
        e.preventDefault();

        const formPayload = {
            modultitel: this.state.modultitel,
            startdate: this.state.startdate,
            enddate: this.state.enddate,
            modulkuerzel: this.state.modulkuerzel,
            modulDescription: this.state.modulDescription
        };
        console.log('send befor', formPayload)
        this.props.next(this.props.nextState);

        console.log('Send this in a Post request:', this.state);
        //States übertragen in die Session
        this.props.saveForm(formPayload);

        this.handleClearForm(e);
    }

    render() {
        return (
            <form>

Modul anlegen (Schritt 1 von x)

                <SingleInput
                    inputType={'text'}
                    title={'Modultitel: '}
                    name={'name'}
                    controlFunc={this.handleModultitel}
                    content={this.state.modultitel}
                    placeholder={'Modultitel'} />
                <SingleInput
                    inputType={'text'}
                    title={'Gültig ab: '}
                    name={'Startdate'}
                    controlFunc={this.handleStartdate}
                    content={this.state.startdate}
                    placeholder={'Startdatum'} />
                <SingleInput
                    inputType={'text'}
                    title={'Gültig bis: '}
                    name={'Enddate'}
                    controlFunc={this.handleEnddate}
                    content={this.state.enddate}
                    placeholder={'Enddatum'} />
                <SingleInput
                    inputType={'text'}
                    title={'Modulkürzel'}
                    name={'Modulkürzel'}
                    controlFunc={this.handleModulkuerzel}
                    content={this.state.modulkuerzel}
                    placeholder={'Modulkützel'} />
                <TextArea
                    title={'Kurzbeschreibung'}
                    rows={5}
                    name={'Kurzbeschreibung'}
                    resize={false}
                    content={this.state.modulDescription}
                    controlFunc={this.handlemodulDescriptionChange}
                    placeholder={'Kurzbeschreibung zu Modulen'} />
                <button
                    onClick={this.handleFormSubmit}>Weiter</button>
                <button
                    onClick={this.handleClearForm}>Clear form</button>
            </form>
        );
    }
}

export default FMoStep1;

Thank you!

Body:
You are relying on the nextState prop to navigate to the nextState in the the FMoStep1 component which you aren't supplying. Pass then and it should work

  switch (this.state.currentState) {
        case states.FMoStep1:
            return <FMoStep1
                saveForm={this.saveForm}
                nextState={states.FMoStep2}
                back={this.backStep}
                next={this.nextStep}
                />;
        case states.FMoStep2:
            return (<FMoStep2
                saveForm={this.saveForm}
                nextState={states.FMoStep3}
                back={this.backStep}
                next={this.nextStep}
            />);
        case states.FMoStep3:
            return (<FMoStep3
                saveForm={this.saveForm}
                back={this.backStep}
                next={this.nextStep}
            />);

        default:
            break;
    }

P.S. However I would suggest you to restructure your code and maybe use routes instead of conditional rendering of the components


问:
typedef Using a typename
So I had some code that I asked a question about which I realized was confusing and later edited out:

```<code>template <typename T>
struct foo {
    typedef typename pair<T, T> PointType;
private:
    PointType point;
};
</code>```

I'm not certain what the function of the typename in PointType's definition is. It this keyword just omitted? I notice that it's frequently used in the using definitions to add the *_t extensions in type support. Perhaps that's what was intended here?

答: It is necessary because pair<T, T> is a dependent name, meaning that it changes depending on how foo was initialized.

Title: typedef Using a typename

Body:
So I had some code that I asked a question about which I realized was confusing and later edited out:

template <typename T>
struct foo {
    typedef typename pair<T, T> PointType;
private:
    PointType point;
};

I'm not certain what the function of the typename in PointType's definition is. It this keyword just omitted? I notice that it's frequently used in the using definitions to add the *_t extensions in type support. Perhaps that's what was intended here?


答:
You are using the second type of typename use, according to cppreference: http://en.cppreference.com/w/cpp/keyword/typename

Basically, you are giving a hint to the compiler: T is a template dependent type in
pair<T, T>

Title: typedef Using a typename


问:
Why are there holes in the Unicode table?
Given this area of the Unicode table, for instance:

```<code>  ...
    U+1D44E Dec:119886       MATHEMATICAL ITALIC SMALL A 𝑎
    U+1D44F Dec:119887       MATHEMATICAL ITALIC SMALL B 𝑏
    U+1D450 Dec:119888       MATHEMATICAL ITALIC SMALL C 𝑐
    U+1D451 Dec:119889       MATHEMATICAL ITALIC SMALL D 𝑑
    U+1D452 Dec:119890       MATHEMATICAL ITALIC SMALL E 𝑒
    U+1D453 Dec:119891       MATHEMATICAL ITALIC SMALL F 𝑓
    U+1D454 Dec:119892       MATHEMATICAL ITALIC SMALL G 𝑔
    U+1D456 Dec:119894       MATHEMATICAL ITALIC SMALL I 𝑖 # what?!
    U+1D457 Dec:119895       MATHEMATICAL ITALIC SMALL J 𝑗
    U+1D458 Dec:119896       MATHEMATICAL ITALIC SMALL K 𝑘
    U+1D459 Dec:119897       MATHEMATICAL ITALIC SMALL L 𝑙
    U+1D45A Dec:119898       MATHEMATICAL ITALIC SMALL M 𝑚
    U+1D45B Dec:119899       MATHEMATICAL ITALIC SMALL N 𝑛
    U+1D45C Dec:119900       MATHEMATICAL ITALIC SMALL O 𝑜
  ...
</code>```

I would naturally expect u+1d455 to be MATHEMATICAL ITALIC SMALL H. But it seems not defined on any table I look around.

Why are there holes in Unicode table? (also U+1d49d, u+1d53a, etc.)

Is there any way I can fill them?

[EDIT]: These links do state:

The "holes" in the alphabetic ranges are filled by previously defined characters in the Letter like Symbols block shown below.

and

The Unicode Consortium adds new codepoints to the standard all the time. Visit their website to find out about pending codepoints and whether this one is in the pipe. The following table shows typical representations of how the codepoint would look, if it existed. This may help you when debugging, but is not of real use otherwise.

But I just... don't understand what they mean :\

答:
From the comments (cheers guys), I have learnt that these holes are due to some characters being already assigned in Unicode when the whole alphabet had been added.

For instance: before U+1D4* MATHEMATICAL ITALIC SMALL * identifiers were defined, ℎ was already known in the table as

```<code>ℎ    U+210E Dec:008462        PLANCK CONSTANT ℎ # here it is
</code>```

So in order to keep consistency in numbering but NOT to duplicate ℎ id, a hole has been inserted at U+1D455 position.

Similarly, ℬ is known as U+212C SCRIPT CAPITAL B rather than U+1D49D - - - reserved in the MATHEMATICAL SCRIPT CAPITAL letters family.

Similarly, ℂ from MATHEMATICAL DOUBLE-STRUCK CAPITAL letters family is not U+1D53A because it was already known as U+2102 DOUBLE-STRUCK CAPITAL C.

This was a difficult choice, having to deal with retro-compatibility, consistency and reliability altogether :)

Body:
Given this area of the Unicode table, for instance:

  ...
    U+1D44E Dec:119886       MATHEMATICAL ITALIC SMALL A 𝑎
    U+1D44F Dec:119887       MATHEMATICAL ITALIC SMALL B 𝑏
    U+1D450 Dec:119888       MATHEMATICAL ITALIC SMALL C 𝑐
    U+1D451 Dec:119889       MATHEMATICAL ITALIC SMALL D 𝑑
    U+1D452 Dec:119890       MATHEMATICAL ITALIC SMALL E 𝑒
    U+1D453 Dec:119891       MATHEMATICAL ITALIC SMALL F 𝑓
    U+1D454 Dec:119892       MATHEMATICAL ITALIC SMALL G 𝑔
    U+1D456 Dec:119894       MATHEMATICAL ITALIC SMALL I 𝑖 # what?!
    U+1D457 Dec:119895       MATHEMATICAL ITALIC SMALL J 𝑗
    U+1D458 Dec:119896       MATHEMATICAL ITALIC SMALL K 𝑘
    U+1D459 Dec:119897       MATHEMATICAL ITALIC SMALL L 𝑙
    U+1D45A Dec:119898       MATHEMATICAL ITALIC SMALL M 𝑚
    U+1D45B Dec:119899       MATHEMATICAL ITALIC SMALL N 𝑛
    U+1D45C Dec:119900       MATHEMATICAL ITALIC SMALL O 𝑜
  ...

I would naturally expect u+1d455 to be MATHEMATICAL ITALIC SMALL H. But it seems not defined on any table I look around.

Why are there holes in Unicode table? (also U+1d49d, u+1d53a, etc.)

Is there any way I can fill them?

[EDIT]: These links do state:

The "holes" in the alphabetic ranges are filled by previously defined characters in the Letter like Symbols block shown below.

and

The Unicode Consortium adds new codepoints to the standard all the time. Visit their website to find out about pending codepoints and whether this one is in the pipe. The following table shows typical representations of how the codepoint would look, if it existed. This may help you when debugging, but is not of real use otherwise.

But I just... don't understand what they mean :\

Body:
From the comments (cheers guys), I have learnt that these holes are due to some characters being already assigned in Unicode when the whole alphabet had been added.

For instance: before U+1D4* MATHEMATICAL ITALIC SMALL * identifiers were defined, ℎ was already known in the table as

ℎ    U+210E Dec:008462        PLANCK CONSTANT &planckh; # here it is

So in order to keep consistency in numbering but NOT to duplicate ℎ id, a hole has been inserted at U+1D455 position.

Similarly, ℬ is known as U+212C SCRIPT CAPITAL B rather than U+1D49D - - - reserved in the MATHEMATICAL SCRIPT CAPITAL letters family.

Similarly, ℂ from MATHEMATICAL DOUBLE-STRUCK CAPITAL letters family is not U+1D53A because it was already known as U+2102 DOUBLE-STRUCK CAPITAL C.

This was a difficult choice, having to deal with retro-compatibility, consistency and reliability altogether :)


问:
Printing from array with button
I´m trying to print from an array with a button. The users are supposed to press the button and a text box is showing up. But nothing happens when I press the button. Does anyone see the problem?

The button is made in html.

```<code>(function () {
  "use strict";

  //HTML objects
  let lenkerBtn;
  let mainContent;

  //bildeliste
  let tekst = ["Her kan du lese om lenker. Bare vent et øyeblikk :)"];

  let init = function () {

    let setHTMLObjects = function () {
      lenkerBtn = document.getElementById("lenkerBtn");
      mainContent = document.getElementById("main-content");
    }(); //end setEvents

    let setEvents = function(){
      lenkerBtn.onclick = vislenker;
    }(); //end setEvents

  }(); //end init

  function visLenker () {
    let antallTekst = tekst.length;
    for (var i = 0; i < tekst; i++) {
      document.getElementById("tekstOmLenker").innerHTML += ("<li>" + tekst[i] + "</li>");
    }
  }
}());
</code>```

答:
This line of code seems to be wrong

```<code> for (var i = 0; i < tekst; i++) {
</code>```

Since tekst is an array not a number

Title: Printing from array with button

Body:
I´m trying to print from an array with a button. The users are supposed to press the button and a text box is showing up. But nothing happens when I press the button. Does anyone see the problem?

The button is made in html.

(function () {
  "use strict";

  //HTML objects
  let lenkerBtn;
  let mainContent;

  //bildeliste
  let tekst = ["Her kan du lese om lenker. Bare vent et øyeblikk :)"];

  let init = function () {

    let setHTMLObjects = function () {
      lenkerBtn = document.getElementById("lenkerBtn");
      mainContent = document.getElementById("main-content");
    }(); //end setEvents

    let setEvents = function(){
      lenkerBtn.onclick = vislenker;
    }(); //end setEvents

  }(); //end init

  function visLenker () {
    let antallTekst = tekst.length;
    for (var i = 0; i < tekst; i++) {
      document.getElementById("tekstOmLenker").innerHTML += ("
" + tekst[i] + "
");
    }
  }
}());

Body:
This line of code seems to be wrong

 for (var i = 0; i < tekst; i++) {

Since tekst is an array not a number


问:
multiple int[][] array to single[] String array in java
So, I'm new to programming and I have this exercise where I have to read an int[][] array with the age and a handicap level of people trying to start a membership in a Club, with two categories, Senior and Open.
My job is to read the array for example [[45, 12],[55,21],[19, -2]] where the first int is the age and the second the handicap level. If the age is at least 55 and the handicap level is higher than 7 then the person gets a Senior membership if not he gets an Open one. My idea was to see the int[][] as a matrix and add both numbers (age and level) and if the number is higher than 62 I would classify it as a Senior otherwise as open.
My method looks like this:

```<code>public class montecarlo {
    static String[] openOrSenior(int[][] a) {
        int i, j, sum;
        String[] abo = new String[a[0].length];
        for (i = 0; i < a.length; i++)
            for (j = 0; j < a[0].length; j++ ) {
                sum = 0;
                int x = a[i][j];
                sum = sum + x;
                if (sum > 62)
                   abo[i] = "Senior";
                else
                   abo[i] = "Open"; //this would be line 12
            }
        return abo;
}

    public static void main(String[] args) {
        int [][] a = {{42, 12},{55, 21},{19,-2}};
        String[] x = openOrSenior(a);    //this would be line 20
        Out.print(x);    //here was to see what i'd get if i let it run

    }
}
</code>```

This is the error i get:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
     at montecarlo.openOrSenior(montecarlo.java:12)      at
  montecarlo.main(montecarlo.java:20)

I would really appreciate some help.

答:
```<code>import java.util. * ;
import java.lang. * ;
import java.io. * ;

class montecarlo {
    static String[] openOrSenior(int[][] a) {
        int i,
        j,
        sum,
        x;
        /*Declare x here, otherwise in your code it will create a new variable everytime in your for loop*/
        String[] abo = new String[a.length];
        /* a.length not a[0].length */

        for (i = 0; i < a.length; i++) {
            sum = 0;
            /* sum should initialised to zero here every time outside the inner for loop*/

            for (j = 0; j < a[0].length; j++) {

                x = a[i][j];
                sum = sum + x;

            }
            /* check outside for loop whether the total sum is greater than 62 */

            if (sum > 62) {
                abo[i] = "Senior";

            }
            else {
                abo[i] = "Open";

            }

        }
        return abo;

    }

    public static void main(String[] args) {
        int[][] a = {
            {
                42,
                12
            },
            {
                55,
                21
            },
            {
                19,
                -2
            },
            {
                72,
                74
            }
        };
        String[] x = openOrSenior(a);
        System.out.print(x);

    }

}
</code>```

Here is the working demo of what you wanted.
I have pointed out your mistakes in comments.
You have done several mistakes, Please watch the code carefully and understand what you did wrong.

Also there is a flaw in your logic which you should fix yourself.
for example age=60, handicap  level=3
total=60+3=63, which is greater than 62 and hence should be "Senior" according to your logic but it is wrong since the handicap level is below 7.

Body:
So, I'm new to programming and I have this exercise where I have to read an int[][] array with the age and a handicap level of people trying to start a membership in a Club, with two categories, Senior and Open.
My job is to read the array for example [[45, 12],[55,21],[19, -2]] where the first int is the age and the second the handicap level. If the age is at least 55 and the handicap level is higher than 7 then the person gets a Senior membership if not he gets an Open one. My idea was to see the int[][] as a matrix and add both numbers (age and level) and if the number is higher than 62 I would classify it as a Senior otherwise as open.
My method looks like this:

public class montecarlo {
    static String[] openOrSenior(int[][] a) {
        int i, j, sum;
        String[] abo = new String[a[0].length];
        for (i = 0; i < a.length; i++)
            for (j = 0; j  62)
                   abo[i] = "Senior";
                else
                   abo[i] = "Open"; //this would be line 12
            }
        return abo;
}

    public static void main(String[] args) {
        int [][] a = {{42, 12},{55, 21},{19,-2}};
        String[] x = openOrSenior(a);    //this would be line 20
        Out.print(x);    //here was to see what i'd get if i let it run

    }
}

This is the error i get:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
     at montecarlo.openOrSenior(montecarlo.java:12)      at
  montecarlo.main(montecarlo.java:20)

I would really appreciate some help.

Body:
import java.util. * ;
import java.lang. * ;
import java.io. * ;

class montecarlo {
    static String[] openOrSenior(int[][] a) {
        int i,
        j,
        sum,
        x;
        /*Declare x here, otherwise in your code it will create a new variable everytime in your for loop*/
        String[] abo = new String[a.length];
        /* a.length not a[0].length */

        for (i = 0; i < a.length; i++) {
            sum = 0;
            /* sum should initialised to zero here every time outside the inner for loop*/

            for (j = 0; j < a[0].length; j++) {

                x = a[i][j];
                sum = sum + x;

            }
            /* check outside for loop whether the total sum is greater than 62 */

            if (sum > 62) {
                abo[i] = "Senior";

            }
            else {
                abo[i] = "Open";

            }

        }
        return abo;

    }

    public static void main(String[] args) {
        int[][] a = {
            {
                42,
                12
            },
            {
                55,
                21
            },
            {
                19,
                -2
            },
            {
                72,
                74
            }
        };
        String[] x = openOrSenior(a);
        System.out.print(x);

    }

}

Here is the working demo of what you wanted.
I have pointed out your mistakes in comments.
You have done several mistakes, Please watch the code carefully and understand what you did wrong.

Also there is a flaw in your logic which you should fix yourself.
for example age=60, handicap  level=3
total=60+3=63, which is greater than 62 and hence should be "Senior" according to your logic but it is wrong since the handicap level is below 7.


问:
Failed to add fields.Selection to parent model
I'm working on access restriction to res.partner.
Currently I have two questions:

1.Why does this code don't create new field to inherited model (first error was something like "unknown object _", now it's gone): (Now it works, first question is answered)

```<code>from odoo import models, fields
class partner(models.Model):
    _inherit = 'res.partner'
    privacy_visibility = fields.Selection([
            ('followers', _('On invitation only')),
            ('employees', _('Visible by all employees')),
         #error was here. according to odoo documentation, here is a comma
         #if you remove it, the code works: [![enter image description here][1]][1]([('',''),('',''),('','')])
        ],
        string='Privacy', required=True,
        default='employees',
        help="Holds visibility of the partner that affects currently logged user:\n"
                "- On invitation only: Employee may only see the followed partners\n"
                "- Visible by all employees: Employee may see selected partner\n")
</code>```

Later, when my restrictions would be applied, how to make selected users to access all pertners anyway? (my ideas - 1.to hide "privacy_visibility" field to be visible in developer mode only, as it made for project's "sub-task project". 2.to create a new group, but I have no idea how to use access groups with row-level access), which way wold you recommend to go?

答:
You are calling the translate object (the underscore "_") to translate your selection values, but you did not import it.

Change:

```<code>from odoo import models, fields
</code>```

To:

```<code>from odoo import models, fields, _
</code>```

Body:
I'm working on access restriction to res.partner.
Currently I have two questions:

1.Why does this code don't create new field to inherited model (first error was something like "unknown object _", now it's gone): (Now it works, first question is answered)

from odoo import models, fields
class partner(models.Model):
    _inherit = 'res.partner'
    privacy_visibility = fields.Selection([
            ('followers', _('On invitation only')),
            ('employees', _('Visible by all employees')),
         #error was here. according to odoo documentation, here is a comma
         #if you remove it, the code works: [![enter image description here][1]][1]([('',''),('',''),('','')])
        ],
        string='Privacy', required=True,
        default='employees',
        help="Holds visibility of the partner that affects currently logged user:\n"
                "- On invitation only: Employee may only see the followed partners\n"
                "- Visible by all employees: Employee may see selected partner\n")

Later, when my restrictions would be applied, how to make selected users to access all pertners anyway? (my ideas - 1.to hide "privacy_visibility" field to be visible in developer mode only, as it made for project's "sub-task project". 2.to create a new group, but I have no idea how to use access groups with row-level access), which way wold you recommend to go?

Body:
You are calling the translate object (the underscore "_") to translate your selection values, but you did not import it.

Change:

from odoo import models, fields

To:

from odoo import models, fields, _


问:
Excel VBA Nested Finds
I have a situation where I need to search for each instance where the value entered by a user (tbISearch1) appears in Column C on sheet3. For each instance found I need to take the corresponding value in Column B on sheet 3 and use these values to search sheet 2, column B and populate a listbox with the associate values in the range column A to D. So far I have the following code but I receive an error after the first loop when it tries to find the next instance for Set rngFind = .FindNext(rngFind)

```<code>With Sheet3.Range("C6:C" & lastRow)
    Set rngFind = .Find(tbISearch1, After:=.Cells(.Cells.Count), LookIn:=xlValues, lookat:=xlPart)
    '   If value found then set a variable for the address
    If Not rngFind Is Nothing Then
        strFirstFind = rngFind.Address
        '   Add the values to the listbox
        Do
            strToFind = rngFind.Offset(0, -1)
            With Sheet2.Range("B6:B" & lastRow2)
                Set rngFind2 = .Find(strToFind, After:=.Cells(.Cells.Count), LookIn:=xlValues, lookat:=xlPart)
                '   If value found then set a variable for the address
                If Not rngFind2 Is Nothing Then
                    '   Add the values to the listbox
                        If rngFind2.Row > 1 Then
                            lbISearch.AddItem rngFind2.Offset(0, -1)
                            lbISearch.List(lbISearch.ListCount - 1, 1) = rngFind2.Value
                            lbISearch.List(lbISearch.ListCount - 1, 2) = rngFind2.Offset(0, 1)
                            lbISearch.List(lbISearch.ListCount - 1, 3) = rngFind2.Offset(0, 2)
                        End If
                        Set rngFind2 = Nothing
                End If
            End With
            '   Find the next address to add
            Set rngFind = .FindNext(rngFind)
        Loop While Not rngFind Is Nothing And rngFind.Address <> strFirstFind
    End If
End With
</code>```

Any help gratefully appreciated

答:
You can't call .findnext on a nested find, therefore the easiest solution is to just perform the find again, but use cell address with the 'After' parameter to get to the next found cell.</p>

```<code>Set rngFind = .Find(rngFind, After:=Range(rngFind.Address))
</code>```

Title: Excel VBA Nested Finds

Body:
I have a situation where I need to search for each instance where the value entered by a user (tbISearch1) appears in Column C on sheet3. For each instance found I need to take the corresponding value in Column B on sheet 3 and use these values to search sheet 2, column B and populate a listbox with the associate values in the range column A to D. So far I have the following code but I receive an error after the first loop when it tries to find the next instance for Set rngFind = .FindNext(rngFind)

With Sheet3.Range("C6:C" & lastRow)
    Set rngFind = .Find(tbISearch1, After:=.Cells(.Cells.Count), LookIn:=xlValues, lookat:=xlPart)
    '   If value found then set a variable for the address
    If Not rngFind Is Nothing Then
        strFirstFind = rngFind.Address
        '   Add the values to the listbox
        Do
            strToFind = rngFind.Offset(0, -1)
            With Sheet2.Range("B6:B" & lastRow2)
                Set rngFind2 = .Find(strToFind, After:=.Cells(.Cells.Count), LookIn:=xlValues, lookat:=xlPart)
                '   If value found then set a variable for the address
                If Not rngFind2 Is Nothing Then
                    '   Add the values to the listbox
                        If rngFind2.Row > 1 Then
                            lbISearch.AddItem rngFind2.Offset(0, -1)
                            lbISearch.List(lbISearch.ListCount - 1, 1) = rngFind2.Value
                            lbISearch.List(lbISearch.ListCount - 1, 2) = rngFind2.Offset(0, 1)
                            lbISearch.List(lbISearch.ListCount - 1, 3) = rngFind2.Offset(0, 2)
                        End If
                        Set rngFind2 = Nothing
                End If
            End With
            '   Find the next address to add
            Set rngFind = .FindNext(rngFind)
        Loop While Not rngFind Is Nothing And rngFind.Address <> strFirstFind
    End If
End With

Any help gratefully appreciated

Body:
You can't call .findnext on a nested find, therefore the easiest solution is to just perform the find again, but use cell address with the 'After' parameter to get to the next found cell.

Set rngFind = .Find(rngFind, After:=Range(rngFind.Address))


问:
Simple Ajax Jquery script- How can I get information for each of the rows in the table?
I'm following  a simple ajax>php>mysql example posted here http://openenergymonitor.org/emon/node/107

I can only display information from the first row.
My table is set up like so

```<code>--------------
|  id  | name|
--------------
| 1    | Pat |
| 2    | Joe |
| 3    | Rob |
--------------
</code>```

The php code

```<code> $result = mysql_query("SELECT * FROM $tableName");          //query
 $array = mysql_fetch_row($result);                          //fetch result
 echo json_encode($array);
</code>```

The script

```<code>$(function ()
  {
    $.ajax({
      url: 'api.php', data: "", dataType: 'json',  success: function(data)
      {
        var id = data[0];              //get id
        var vname = data[1];           //get name
         $('#output').html("<b>id: </b>"+id+"<b> name: </b>"+vname);
      }
    });
  });
</code>```

ROW 1

If I put the var id = data[0]; I get the value 1.
If I put the var name = data[1]; I get Pat.

ROWS 2 n 3 are undefined

Example var id=data[2]; returns undefined
etc

My Questions

Why do I only get the values from the first row?

How can I get information for rows other than the first one?

From other questions on Stackoverflow I see that I will probably have to use a while loop, but I'm not really sure why or how.

答:
<pre class="lang-php prettyprint-override"><code>$result = mysql_query("SELECT * FROM $tableName");
$array = array(mysql_fetch_row($result));

// To store every row in the $array
while($row = mysql_fetch_row($result)) {
    $array[] = $row;
}
echo json_encode($array);
</code>```

Body:
I'm following  a simple ajax>php>mysql example posted here http://openenergymonitor.org/emon/node/107

I can only display information from the first row.
My table is set up like so

--------------
|  id  | name|
--------------
| 1    | Pat |
| 2    | Joe |
| 3    | Rob |
--------------

The php code

 $result = mysql_query("SELECT * FROM $tableName");          //query
 $array = mysql_fetch_row($result);                          //fetch result
 echo json_encode($array);

The script

$(function ()
  {
    $.ajax({
      url: 'api.php', data: "", dataType: 'json',  success: function(data)
      {
        var id = data[0];              //get id
        var vname = data[1];           //get name
         $('#output').html("id: "+id+" name: "+vname);
      }
    });
  });

ROW 1

If I put the var id = data[0]; I get the value 1.
If I put the var name = data[1]; I get Pat.

ROWS 2 n 3 are undefined

Example var id=data[2]; returns undefined
etc

My Questions

Why do I only get the values from the first row?

How can I get information for rows other than the first one?

From other questions on Stackoverflow I see that I will probably have to use a while loop, but I'm not really sure why or how.


问:
How does language design influence VM and bytecode design?
For example, how did the design of C# and VB.NET shape the development of CIL (and vice-versa)? What about Java and the JVM? How did the nature of PHP affect the development of HHBC/the HHVM, or Perl and Parrot, or Smalltalk and the VMs for various implementations?</p>

答: Language design will influence the VM if the designers want it to. Some VMs are more independent than others. For example, Java does not have multiple inheritance, so JVM does not either.</p>


问:
Will ReactDOM.hydrate() trigger lifecycle methods on the client?
From the React 16 docs about ReactDOM.hydrate(),

Same as render(), but is used to hydrate a container whose HTML contents were rendered by ReactDOMServer. React will attempt to attach event listeners to the existing markup.

Will ReactDOM.hydrate() also trigger lifecycle methods on the client such as componentWillMount(), componentDidMount() during initial render?

Will render() method be called on the client during hydration? I suppose not, because that's the difference between ReactDOM.render() and ReactDOM.hydrate()?

If render method won't be called on the client, we wouldn't expect componentDidMount() lifecycle method to be triggered.

If none of the lifecycle methods are called on the client, how would we know when has React finished rendering. I suppose the callback in the following syntax:

ReactDOM.hydrate(element, container[, callback])

I want to understand if there are lifecycle methods / hooks (which give more control over the application) available when React is "attempting to attach event listeners to existing markup".

答:
Since ReactDOM.hydrate is (and should be) called on the client then YES it is supposed to run componentDidMount. componentWillMount is already called when rendered on the server.
componentDidMount does not run on the server, therefore when you call hydrate, the app runs the event.

Think about hydrate as a different render method. It does render but not in the same way. It looks for mismatches between your server rendered React and your client React. It does not render everything again.

React expects that the rendered content is identical between the server and the client. It can patch up differences in text content (such as timestamps), but you should treat mismatches as bugs and fix them

However you might want to do some crazy stuff like rendering something completely different on the client side (than what was rendered on the server). For this pay attention to this paragraph

If you intentionally need to render something different on the server and the client, you can do a two-pass rendering. Components that render something different on the client can read a state variable like this.state.isClient, which you can set to true in componentDidMount(). This way the initial render pass will render the same content as the server, avoiding mismatches, but an additional pass will happen synchronously right after hydration. Note that this approach will make your components slower because they have to render twice, so use it with caution.

So as you can see it does a render pass. If there are no mismatches React is optimized for that.

I hope it was clarifying. I speak from experience with React SSR and basic understanding of reading the docs.


问:
Node.js repeat database request in .then chain
I use a promise .then chain. In this chain I calculate some bounds, build the sql statement and send a request to the database. If the database request gives no result, I want to change something by calculating the bounds and do the same steps again. I want to repeat this until there is a database result.

This is my code:

```<code>.then(function(){
    return calcBound.calcBounds(req.body,0);
  })
  .then(function(options){
    return sqlStatementBuilder.sqlStatementBuilder(options);
  })
  .then(function(statement){
    return db_request.db_request(statement);
  })
  .then(function(dbResult){
    if(dbResult.length <= 0){ // if there are no results from the database
      console.log("There are no results for this filter options");
      var newDBResult;
      do{
        newDBResult = calcBound.calcBounds(req.body, addToOffset)
                .then(function(options){
                  return sqlStatementBuilder.sqlStatementBuilder(options);
                })
                .then(function(statement){
                  return db_request.db_request(statement);
                })
      } while(dbResult.length <= 0);
      return newDBResult.sort(sortArray.compareRecordId);
    }else{
      return dbResult.sort(sortArray.compareRecordId);
    }
  })
</code>```

The while loop is not a good idea her this will end up as "heap out of memory".

What would be a better solution to do this?

答:
Create a function dummyRecursiveFunction with addToOffset as a parameter and call it until you get results in dbResult

```<code>function dummyRecursiveFunction(addToOffset) {
  someFunction()
  .then(function(){
    return calcBound.calcBounds(req.body, addToOffset);
  })
  .then(function(options){
    return sqlStatementBuilder.sqlStatementBuilder(options);
  })
  .then(function(statement){
    return db_request.db_request(statement);
  })
  .then(function(dbResult) {
    if(dbResult.length > 0) {
      return dbResult.sort(sortArray.compareRecordId);
    } else {
      // newOffset: Your recalculated offset value.
      dummyRecursiveFunction(newOffset);
    }
  });
}
</code>```

Body:
I use a promise .then chain. In this chain I calculate some bounds, build the sql statement and send a request to the database. If the database request gives no result, I want to change something by calculating the bounds and do the same steps again. I want to repeat this until there is a database result.

This is my code:

.then(function(){
    return calcBound.calcBounds(req.body,0);
  })
  .then(function(options){
    return sqlStatementBuilder.sqlStatementBuilder(options);
  })
  .then(function(statement){
    return db_request.db_request(statement);
  })
  .then(function(dbResult){
    if(dbResult.length <= 0){ // if there are no results from the database
      console.log("There are no results for this filter options");
      var newDBResult;
      do{
        newDBResult = calcBound.calcBounds(req.body, addToOffset)
                .then(function(options){
                  return sqlStatementBuilder.sqlStatementBuilder(options);
                })
                .then(function(statement){
                  return db_request.db_request(statement);
                })
      } while(dbResult.length <= 0);
      return newDBResult.sort(sortArray.compareRecordId);
    }else{
      return dbResult.sort(sortArray.compareRecordId);
    }
  })

The while loop is not a good idea her this will end up as "heap out of memory".

What would be a better solution to do this?

Body:
Create a function dummyRecursiveFunction with addToOffset as a parameter and call it until you get results in dbResult

function dummyRecursiveFunction(addToOffset) {
  someFunction()
  .then(function(){
    return calcBound.calcBounds(req.body, addToOffset);
  })
  .then(function(options){
    return sqlStatementBuilder.sqlStatementBuilder(options);
  })
  .then(function(statement){
    return db_request.db_request(statement);
  })
  .then(function(dbResult) {
    if(dbResult.length > 0) {
      return dbResult.sort(sortArray.compareRecordId);
    } else {
      // newOffset: Your recalculated offset value.
      dummyRecursiveFunction(newOffset);
    }
  });
}


问:
javascript google maps api - dynamic search place
i've done like this video has shown but something just not working. mine not showing the place i seaching for and the marker also didnt move to that place. Youtube tutorial

and this is my code

```<code>var map = new google.maps.Map(document.getElementById('map-canvas'),{
    center:{
      lat:-7.9666,
      lng:112.6326
    },
    zoom:15
  } );
  var marler = new google.maps.Marker({
    position:{
      lat:-7.9666,
      lng:112.6326
    },
    map:map,
    draggable:true
  });
  var searchBox = new google.maps.places.SearchBox(document.getElementById('mapsearch'));
  google.maps.event.addListener (searchBox, 'places_changed', function(){
     var places = searchBox.getPlaces();

     var bounds = new google.maps.LatLngBounds();
     var i, place;
     for (i=0; place=places[i];i++){
      //console.log(place.geometry.location);
      bounds.extend(place.geometry.location);
      marker.setPosition(place.geometry.location);
     }
     map.fitBounds(bounds);
     map.setZoom(15);
  });
</code>```

problem starts from var searchBox line down below

im using libraries=places at the end of google api script.
thanks for your help :beer

答:
viola, i actually have a typo for the marker that written as marler.
case close everyone,
you should go to that youtube tutorial, that works!

Body:
i've done like this video has shown but something just not working. mine not showing the place i seaching for and the marker also didnt move to that place. Youtube tutorial

and this is my code

var map = new google.maps.Map(document.getElementById('map-canvas'),{
    center:{
      lat:-7.9666,
      lng:112.6326
    },
    zoom:15
  } );
  var marler = new google.maps.Marker({
    position:{
      lat:-7.9666,
      lng:112.6326
    },
    map:map,
    draggable:true
  });
  var searchBox = new google.maps.places.SearchBox(document.getElementById('mapsearch'));
  google.maps.event.addListener (searchBox, 'places_changed', function(){
     var places = searchBox.getPlaces();

     var bounds = new google.maps.LatLngBounds();
     var i, place;
     for (i=0; place=places[i];i++){
      //console.log(place.geometry.location);
      bounds.extend(place.geometry.location);
      marker.setPosition(place.geometry.location);
     }
     map.fitBounds(bounds);
     map.setZoom(15);
  });

problem starts from var searchBox line down below

im using libraries=places at the end of google api script.
thanks for your help :beer


问:
css: how to "center" a big image inside limited width and height without changing dimensions
before anything: No I don't mean centering an image inside a div

WHAT I WANT TO DO IS SIMILAR TO THE DESKTOP 'CENTER' OPTION HENCE THE TITLE PLEASE DON'T BE CONFUSED I JUST DON'T KNOW THE SUITABLE TERM OF WHAT I WANT

I am making a certian css template for my use, but I have this question that I couldn't figure out ..

basically, there is an image before each post, so the width is known. I set it to 100% of a container called "post". post has a width of 75% of the browser

```<code><div class="post">
  <h1>post title</h1>
  <img class="post-img" src="myImg.png" />
  <!--other elements-->
</div>
</code>```

css:

```<code>.post {
  width: 75%;
.post-img {
  max-width: 100%;
}
</code>```

Now to the problem ..
although the width now is fixed regardless of the image, the height is pretty much automatic

I want to set the height to a certain value, like max-height: 500px; for example .. so when a picture is big:

make width = 100% of the post div

is the height > 500px? no then make it auto. yes then crop the extra part

an image

as you can see, the black stroke is the limited width and height

the width was checked first so no extra parts to the left and right

the height is more than 500px, so it will be cropped and the viewed image would be the one inside the black frame

答:
What you are trying to achieve may be something like that, using background instead of , so you have a much more simple control on the image :

.post {
  width: 75%;
}

.container {
  width: 100%;
  height: 500px;
  overflow: hidden;
  background: url('https://s3-eu-west-1.amazonaws.com/hasselblad-masters/web-hi-res-content/X1D-Sample-Images/X1D5_B0001993.jpg') center no-repeat;
  background-size: cover;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="post">
  <h1>post title</h1>
  <div class="container">
  </div>
  <article>
    <p>Other content</p>
  </article>
</div></code>```

Body:
before anything: No I don't mean centering an image inside a div

WHAT I WANT TO DO IS SIMILAR TO THE DESKTOP 'CENTER' OPTION HENCE THE TITLE PLEASE DON'T BE CONFUSED I JUST DON'T KNOW THE SUITABLE TERM OF WHAT I WANT

I am making a certian css template for my use, but I have this question that I couldn't figure out ..

basically, there is an image before each post, so the width is known. I set it to 100% of a container called "post". post has a width of 75% of the browser

post title

css:

.post {
  width: 75%;
.post-img {
  max-width: 100%;
}

Now to the problem ..
although the width now is fixed regardless of the image, the height is pretty much automatic

I want to set the height to a certain value, like max-height: 500px; for example .. so when a picture is big:

make width = 100% of the post div

is the height > 500px? no then make it auto. yes then crop the extra part

an image

as you can see, the black stroke is the limited width and height

the width was checked first so no extra parts to the left and right

the height is more than 500px, so it will be cropped and the viewed image would be the one inside the black frame

Body:
What you are trying to achieve may be something like that, using background instead of <img>, so you have a much more simple control on the image :

.post {
  width: 75%;
}

.container {
  width: 100%;
  height: 500px;
  overflow: hidden;
  background: url('https://s3-eu-west-1.amazonaws.com/hasselblad-masters/web-hi-res-content/X1D-Sample-Images/X1D5_B0001993.jpg') center no-repeat;
  background-size: cover;
}

<div class="post">
  <h1>post title</h1>
  <div class="container">
  </div>
  <article>
    <p>Other content</p>
  </article>
</div>


答:
Here's a more straightforward version with syntax errors fixed.</p>

```<code>public class montecarlo {
    static String[] openOrSenior(int[][] a) {
        String[] abo = new String[a.length]; // you had a[0] here instead of a
        for (int i = 0; i < a.length; i++) {
            if (a[i][0] >= 55 && a[i][1] > 7) {
                abo[i] = "Senior";
            } else {
                abo[i] = "Open";
            }
        }
        return abo;
    }
}
</code>```

Title: multiple int[][] array to single[] String array in java

Body:
Here's a more straightforward version with syntax errors fixed.

public class montecarlo {
    static String[] openOrSenior(int[][] a) {
        String[] abo = new String[a.length]; // you had a[0] here instead of a
        for (int i = 0; i < a.length; i++) {
            if (a[i][0] >= 55 && a[i][1] > 7) {
                abo[i] = "Senior";
            } else {
                abo[i] = "Open";
            }
        }
        return abo;
    }
}


问:
Binary Crossentropy to penalize all components of one-hot vector
I understand that binary cross-entropy is the same as categorical cross-entropy in case of two classes.

Further, it is clear for me what softmax is.

Therefore, I see that categorical cross-entropy just penalizes the one component (probability) that should be 1.

But why, can't or shouldn't I use binary cross-entropy on a one-hot vector?

```<code>Normal Case for 1-Label-Multiclass-Mutual-exclusivity-classification:
################
pred            = [0.1 0.3 0.2 0.4]
label (one hot) = [0   1   0   0]
costfunction: categorical crossentropy
                            = sum(label * -log(pred)) //just consider the 1-label
                            = 0.523
Why not that?
################
pred            = [0.1 0.3 0.2 0.4]
label (one hot) = [0   1   0   0]
costfunction: binary crossentropy
                            = sum(- label * log(pred) - (1 - label) * log(1 - pred))
                            = 1*-log(0.3)-log(1-0.1)-log(1-0.2)-log(1-0.4)
                            = 0.887
</code>```

I see that in binary cross-entropy the zero is a target class, and corresponds to the following one-hot encoding:

```<code>target class zero 0 -> [1 0]
target class one  1 -> [0 1]
</code>```

In summary: Why do we just calculate/summarize the negative log likelihood for the predicted class. Why don't we penalize the other SHOULD-BE-ZERO-/NOT-THAT-CLASS classes?

In case one uses binary cross-entropy to a one-hot vector. Probabilities to expected zero labels would be penalized too.

答:
See my answer on a similar question. In short, binary cross-entropy formula doesn't make sense for the one-hot vector. It's either possible to apply softmax cross-entropy for two or more classes or use the vector of (independent) probabilities in label, depending on the task.

But why, can't or shouldn't I use binary crossentropy on a one-hot vector?

What you compute is binary cross-entropy of 4 independent features:

```<code>pred   = [0.1 0.3 0.2 0.4]
label  = [0   1   0   0]
</code>```

The model inference predicted that first feature is on with 10% probability, the second feature is on with 30% probability and so on. Target label is interpreted this way: all features are off, except for the second one. Note that [1, 1, 1, 1] is a perfectly valid label as well, i.e. it's not one-hot vector, and pred=[0.5, 0.8, 0.7, 0.1] is a valid prediction, i.e. the sum doesn't have to equal to one.

In other words, your computation is valid, but for a completely different problem: multi-label non-exclusive binary classification.

See also the difference between softmax and sigmoid cross-entropy loss functions in tensorflow.

Body:
I understand that binary cross-entropy is the same as categorical cross-entropy in case of two classes.

Further, it is clear for me what softmax is.

Therefore, I see that categorical cross-entropy just penalizes the one component (probability) that should be 1.

But why, can't or shouldn't I use binary cross-entropy on a one-hot vector?

Normal Case for 1-Label-Multiclass-Mutual-exclusivity-classification:
################
pred            = [0.1 0.3 0.2 0.4]
label (one hot) = [0   1   0   0]
costfunction: categorical crossentropy
                            = sum(label * -log(pred)) //just consider the 1-label
                            = 0.523
Why not that?
################
pred            = [0.1 0.3 0.2 0.4]
label (one hot) = [0   1   0   0]
costfunction: binary crossentropy
                            = sum(- label * log(pred) - (1 - label) * log(1 - pred))
                            = 1*-log(0.3)-log(1-0.1)-log(1-0.2)-log(1-0.4)
                            = 0.887

I see that in binary cross-entropy the zero is a target class, and corresponds to the following one-hot encoding:

target class zero 0 -> [1 0]
target class one  1 -> [0 1]

In summary: Why do we just calculate/summarize the negative log likelihood for the predicted class. Why don't we penalize the other SHOULD-BE-ZERO-/NOT-THAT-CLASS classes?

In case one uses binary cross-entropy to a one-hot vector. Probabilities to expected zero labels would be penalized too.

Body:
See my answer on a similar question. In short, binary cross-entropy formula doesn't make sense for the one-hot vector. It's either possible to apply softmax cross-entropy for two or more classes or use the vector of (independent) probabilities in label, depending on the task.

But why, can't or shouldn't I use binary crossentropy on a one-hot vector?

What you compute is binary cross-entropy of 4 independent features:

pred   = [0.1 0.3 0.2 0.4]
label  = [0   1   0   0]

The model inference predicted that first feature is on with 10% probability, the second feature is on with 30% probability and so on. Target label is interpreted this way: all features are off, except for the second one. Note that [1, 1, 1, 1] is a perfectly valid label as well, i.e. it's not one-hot vector, and pred=[0.5, 0.8, 0.7, 0.1] is a valid prediction, i.e. the sum doesn't have to equal to one.

In other words, your computation is valid, but for a completely different problem: multi-label non-exclusive binary classification.

See also the difference between softmax and sigmoid cross-entropy loss functions in tensorflow.


问:
Get rows affected by an update
How can you get the exact rows affected by an SQL UPDATE statement in DB2 on AS400?

It's very usefull to see which are the rows just updated, even more during tests.

I saw this question: is the same, but specific for MySQL. Is there a standard SQL way or DB2 specific way for doing this?

I saw also this technique, but I can't use it because my update query is too much complicated.

An additional feature could be: getting also previous version of these rows, so you can compare it with the actual version (after the update) and see the modifications.

EDIT: my DB2 versions are the ones for IBM i V5R3 and V6R1

答:
You don't say what version of i5/OS you are running, but if you are running V6R1 or later, you can use "data change table references" to see the rows that are modified by the update statement.  For example:

```<code>select * from FINAL TABLE ( update yourtable set c1 = x where ... )
</code>```

FINAL TABLE will give you the rows after any/all triggers are fired.  Please note there are also another data change table references, NEW TABLE - which will show the rows before they are affected by any triggers.

You can read about data change table references in the i5/OS documentation.

Title: Get rows affected by an update

Body:
You don't say what version of i5/OS you are running, but if you are running V6R1 or later, you can use "data change table references" to see the rows that are modified by the update statement.  For example:

select * from FINAL TABLE ( update yourtable set c1 = x where ... )

FINAL TABLE will give you the rows after any/all triggers are fired.  Please note there are also another data change table references, NEW TABLE - which will show the rows before they are affected by any triggers.

You can read about data change table references in the i5/OS documentation.

ContentLicense: CC BY-SA 2.5