text:
Q: Error with Sign Up PHP page EDIT

SO I figured out a fix. I replaced the while statement with an if and it worked perfectly. Thanks to everyone who helped out!

I was making a sign up page when this error came up ( I'm still kind of new to programming and php so this might explain what the error is and I just don't know)

Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in /Users/Jacob/Sites/website/postregister.php on line 22

Here's my code:

            <?php
            include("config.php");
            $firstname = mysql_real_escape_string($_REQUEST['firstname']);
            $lastname = mysql_real_escape_string($_REQUEST['lastname']);
            $email = mysql_real_escape_string($_REQUEST['email']);
            $birthyear = mysql_real_escape_string($_REQUEST['birthyear']);
            $city = mysql_real_escape_string($_REQUEST['city']);
            $address = mysql_real_escape_string($_REQUEST['address']);
            $state = mysql_real_escape_string($_REQUEST['state']);
            $phone = mysql_real_escape_string($_REQUEST['phone']);
            $password = mysql_real_escape_string($_REQUEST['password']);
            $zipcode= mysql_real_escape_string($_REQUEST['zipcode']);
            $active = 0;
            $hash = md5( rand(0,1000) ); // Generate random 32 character hash and assign it to a local variable.
            $sql= mysql_query("INSERT INTO member (firstname, lastname, email, phone, city, state, address, zipcode, password, hash, active)
            VALUES

            ('$firstname','$lastname','$email','$phone', '$city', '$state','$address', '$zipcode', '$password', '$hash', '$active')")or die(mysql_error());
                                    while($row == mysql_fetch_array($sql)){
                                    $to = $email; //Send email to our user
                                    $subject = 'Signup | Verification'; //// Give the email a subject
                                    $message = '

                                    Thanks for signing up!

                                    Your account has been created, you can login with the following credentials after you have activated your account by pressing the url below.

                                    ------------------------------------------------------------------------------

                                    Email: '.$email.'

                                    Password: '.$password.'

                                    ------------------------------------------------------------------------------

                                    Please Click Here to Activate Your Account

                                    '; // Our message above including the link

                                    $headers  = "From: customersupport@example.com\r\n";
                                    $headers .= "Content-type: text/html\r\n";
                                    mail($to, $subject, $message, $headers); // Send the email
                                }

            ?>
            <form action="postregister.php" method="post">
                First Name:

                <input type="text" name="firstname" value="" size='90' style='height:20px;' />

                Last Name:

                <input type="text" name="lastname" value="" size='90' style='height:20px;'/>

                Email:

                <input type="text" name="email" value="" size='90' style='height:20px;'/>

                Birthyear:

                <input type="text" name="birthyear" value="" size='90' style='height:20px;'/>

                City:

                <input type="text" name="city" value="" size='90' style='height:20px;'/>

                Phone:

                <input type="text" name="phone" value="" size='90' style='height:20px;'/>

                Address:

                <input type="text" name="address" value="" size='90' style='height:20px;'/>

                Zipcode:

                <input type="text" name="zipcode" value="" size='90' style='height:20px;'/>

                State:

                <input type="text" name="state" value="" size='90' style='height:20px;'/>

                Password:

                <input type="password" name="password" value="" size='90' style='height:20px;'/>

                <input type="submit" class="submit_button" value="Sign up" />
            </form>

Any help would be GREATLY appreciated. Thanks!

A: Please read the manual for mysql_query(). Under Return Values...

For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error.

As your query is an INSERT type statement, mysql_query() will return a boolean. There are also no rows to fetch.
You can probably change your code to the following
$result = mysql_query("All that SQL");
if ($result === false) {
    // or die() is a terrible way to handle errors
    throw new Exception(mysql_error());
}

$to = $email;
// and so on

A: Most people seeing this message have simply forgotten to check for an error in executing their statement. You've already got that covered with the or die portion of the mysql_query line.
Your problem is that you're trying to loop through the resulting rows from an INSERT, but an INSERT doesn't return a set of rows. From the PHP docs:

For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc,
  mysql_query() returns TRUE on success or FALSE on error.

You're not actually using $row inside your loop anyway.
Instead of the loop and mysql_fetch_array, you could just check to see if mysql_query returned true, in which case your row was added and you can send your email. The way you've already written the query, though I wouldn't personally recommend it, actually makes this very easy: you just have to send the email right after the query line, because you're already dieing in case of an error.

A: It looks like your query is returning false.  I would imagine there's an error with your database connection.  Try printing your query and running it manually on your database to confirm it's running properly.  You can also just try a simple:
 $result = mysql_query("SELECT * FROM member LIMIT 10");
 $row = mysql_fetch_array($result);
 print_r($row);

And see what happens.  I imagine this will error out too.  Check your include("config.php"); and be sure your DB link is set up and working properly.  To confirm your $sql isn't getting a valid result you can try dumping it out and seeing what type it is using either print_r or var_dump.  Good luck.


text:
Q: Monthly percentage returns to actual values I'm given three consequent monthly returns: 0.02, -0.03, 0.04. And I'm asked to plot the growth of an investment. Therefore I need to transform these into some kind of actual values. I think I can do it with for the following way:
test <- c(0.02, -0.03, 0.04)
z <- c(1)
for (i in 1:length(test)) {
    z[i+1] <- z[i] + z[i] * test[i]
}
z

But it's a bad practice to use for, I assume, and, on the other side, I bet it's also possible to achieve the same result with the apply family, isn't it?
Thus, I'd be grateful for any advice, thanks :).

A: You can try:
z <- z*c(1, cumprod(1+test))

Example:
test <- c(0.02, -0.03, 0.04)
z <- 1
z <- z*c(1, cumprod(1+test))

The result of the multiplication is:
> z*c(1, cumprod(1+test))
[1] 1.000000 1.020000 0.989400 1.028976

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do you add multiple events OnClick on an IHTMLElement? I am using MSHTML_TLB unit.
I used to cast a IHTMLElement interface to IEventTarget which was supported like one month ago. Then, I would use the method addEventListener to add another OnClick event.
Now, it doesn't work. It says that it cannot convert the IHTMLElement to the IEventTarget because the interface is not supported. It is the same HTML element that was used one month ago.
I changed the code a week ago by importing the MSHTML unit, so I use two units which are MSHTML and MSHTML_TLB.
So before the changes, it looked like that:
uses MSHTML_TLB;

{...}

procedure {...}
var
  MyHTMLElement: IHTMLElement;
  EventHandler: IEventTarget;
begin
  { ... some code here }
  { It uses the object IEventTarget from the unit MSHTML_TLB by default }

  if (Supports(MyHTMLElement, IEventTarget, EventHandler)) then
    EventHandler.AddEventListener(...);
end;

Now it looks like this:
uses MSHTML, MSHTML_TLB;

{...}

procedure {...}
var
  MyHTMLElement: MSHTML_TLB.IHTMLElement;
  EventHandler: MSHTML_TLB.IEventTarget;
begin
  { ... some code here }
  { I have to specify that I use a IEventTarget from MSHTML_TLB by default because otherwise, it will take the IEventTarget from the MSHTML unit. }

  if (Supports(MyHTMLElement, MSHTML_TLB.IEventTarget, EventHandler)) then
    EventHandler.AddEventListener(...);
end;

My code works fine until it tries to convert the IHTMLElement to an IEventTarget element and it says that the interface is not supported, so the method "Supports" here return false.
I'm thinking that this maybe caused by importing the MSHTML unit, but if so, why? I cannot remove the MSHTML unit because I really need it for something else.


text:
Q: Can OSX still sync dropbox while "asleep"? If a Mac Mini running macOS 10.11 is in sleep mode, but powered on and connected to the network, will Dropbox still sync in the background?

A: You might want to consult Apple's documentation about Power Nap.
Mac Minis (Late 2012 and later) are Power Nap compatible.
From what I can see, the only services which are available when a Power Nap compatible computer is in sleep mode are Apple-only:
If your Mac supports Power Nap, these activities can occur while your Mac is asleep:

*

*Mail receives new messages.

*Contacts keep up to date with changes made on other devices.

*Calendar receives new invitations and calendar updates.

*Reminders keep up to date with changes made on other devices.

*Notes keep up to date with changes made on other devices.

*Documents stored in iCloud keep up to date with changes made on other devices.

*Photo Stream keeps up to date with changes made on other devices.

*Find My Mac updates the location of the Mac, so you can find it while it's asleep.

*VPN on demand continues working so that your corporate email updates securely. (Power Nap supports VPN connections that use a certificate to authenticate, not VPN connections that require entering a password.)

*Mobile Device Management can remotely lock and wipe your Mac.

And these activities can occur while your Mac is asleep and plugged in to an AC power outlet:

*

*Software updates download.

*Mac App Store items (including software updates), download in the background.

*Time Machine performs backups.

*Spotlight performs indexing.

*Help Center content updates.

*Wireless base stations can wake your Mac using Wake on Wireless.

Content lifted directly from the Apple Support document linked above.

A: Dropbox (as of March 2019) appears to be Power Nap compatible. I started 14GB syncing (uploading) before I went to bed, closed the lid, and it was all synced by morning.  Computer was cool to touch in the morning so I don't think it was awake with lid closed.


text:
Q: Do not print information in the internet browser because CodeIgniter method I have a problem in this method produtos_categoria the model folder, was to print all the information that is in the database, but that is not what happens. He behaves as if there was no information from the database table produtos.
 public function produtos_categoria($categoria){
        $this->db->where('id_categoria',$categoria);
        return $this->db->get('produtos')->result();
    }

in my database there are some tables, one of them is the Categorias table and the Produtos table.
I created a method to print the information from the category table and the Products table, but only information appears on the table categories browser. I messed up something in the project and need to find the error, I'm new to PHP programming.
this class is to be created produtos_categoria the method;
<?php

class Categorias_model extends CI_Model{

    var $id_categorias;
    var $categoria_nome;
    var $categoria_slug;
    var $data_alteracao;

    function __construct() {
        parent::__construct();
    }
    public function listar_categorias(){
        return $this->db->get('categorias')->result();
    }
    public function produtos_categoria($categoria){
        $this->db->where('id_categoria',$categoria);
        return $this->db->get('produtos')->result();
    }

    public function detalhes_categoria_by_slug($slug){
        $this->db->where('categoria_slug',$slug);
        $categorias = $this->db->get('categorias')->result();
        if(count($categorias) == 1){
            foreach ($categorias as $categoria){
                $this->id_categorias = $categoria->id_categorias;
                $this->categoria_nome = $categoria->categoria_nome;
                $this->categoria_slug = $categoria->categoria_slug;
                $this->data_alteracao = $categoria->data_alteracao;
            }

            $dados['categoria'] = $this;
            $dados['produtos_categoria']= $this->produtos_categoria($this->id_categorias);

        }
        else{
            $dados['categoria']= null;
            $dados['produtos_categoria']= null;
        }

        return $dados;
    }

}

and this class that this line of code that prints the information in the browser
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Home extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->model('Categorias_model','categorias');
    }

    public function index()
    {
        $dados_header = array(
                    'titulo' => 'Super loja legal - Home',
                    'descricao' => 'descrição que vai no cabeçalho html',
                    'palavras_chave' => 'palavra 1,palavra 2, palavra N'
                );
                $dados_cabecalho = array(
                    'titulo_h2' => 'Catálago de produtos'
                );

                $dados_cabecalho['categorias'] = $this->categorias->listar_categorias();

                $this->layout->region('html_header','view_html_header',$dados_header);
                $this->layout->region('cabecalho','view_cabecalho',$dados_cabecalho);
                $this->layout->region('corpo','view_conteudo');
                $this->layout->region('rodape','view_rodape');
                $this->layout->region('html_footer','view_html_footer');
                $this->layout->show('layout');

    }
        public function categoria($slug){
            $dados_cabecalho['categorias'] = $this->categorias->listar_categorias();
            $dados['categoria'] = $this->categorias->detalhes_categoria_by_slug($slug);
            echo "<pre>";
            print_r($dados_cabecalho);
            print_r($dados);

        }
}

is this piece of code that prints the information;
public function categoria($slug){
            $dados_cabecalho['categorias'] = $this->categorias->listar_categorias();
            $dados['categoria'] = $this->categorias->detalhes_categoria_by_slug($slug);
            echo "<pre>";
            print_r($dados_cabecalho);
            print_r($dados);

here is the result;
http://localhost/Carrinho_de_Compras/index.php/home/categoria/algum-slug-de-categoria

be returning as if it had no information on the bank;
[categoria] => Array
        (
            [categoria] =>
            [produtos_categoria] =>
        )

)


text:
Q: The best way of flushing data buffers in DirectFB I am working with a Set-Top-Box MMI (Multi Media Interface) based on Opera Browser. Opera sends continuously data buffers to be flushed on the screen. I have two solutions implementing this feature.

*

*The first one uses only a double buffered primary surface (named 'surface'). Opera writes directly on it.

*The second solution has two surfaces: an offscreen surface 'bsurface' and a primary double buffered surface 'surface'.

I want to know which one offers more performance and stability for the STB device ? and why ? You should know that my STB hardware is based on Intel Chipset. All your opinions are welcome.
/*******************************************************************************
1) flush_buffer: flush callback
*******************************************************************************/
static void flush_buffer(GogiRect *rects, int num_rects, GogiScreenHandle screen)
{
   int i;
   for (i = 0; i < num_rects; ++i)
   {
      DFBRegion update_region = {rects[i].x,
                                 rects[i].y,
                                 rects[i].x+rects[i].w,
                                 rects[i].y+rects[i].h};

      DFBCHECK(surface->Flip(surface, &update_region, DSBLIT_NOFX));
   }

}

/*******************************************************************************
2) flush_buffer: flush callback
*******************************************************************************/.
static void flush_buffer(GogiRect *rects, int num_rects, GogiScreenHandle screen)
{
   int i;
   DFBRegion update_region = {op_width, op_height, 0, 0};
   DFBCHECK(surface->SetBlittingFlags(surface, DSBLIT_NOFX));
   for (i = 0; i < num_rects; ++i)
   {
      DFBRectangle rect = {rects[i].x,
                           rects[i].y,
                           rects[i].w,
                           rects[i].h};

      DFBCHECK(surface->Blit( surface, bsurface, &rect, rect.x, rect.y ));

      if (rects[i].x < update_region.x1) {
         update_region.x1 = rects[i].x;
      }
      if (rects[i].y < update_region.y1) {
         update_region.y1 = rects[i].y;
      }
      if (rects[i].x+rects[i].w > update_region.x2) {
         update_region.x2 = rects[i].x+rects[i].w;
      }
      if (rects[i].y+rects[i].h > update_region.y2) {
         update_region.y2 = rects[i].y+rects[i].h;
      }
   }
   DFBCHECK(surface->Flip(surface, &update_region, DSFLIP_BLIT));

}


text:
Q: ORA-01861: literal does not match format string for comparing date in Oracle I have assigned date value into a variable which is 2017-03-15T00:00:00+05:30
and I am comparing with other date whose value is TO_DATE('01-10-16', 'dd-mm-yy')
So here is my query for the same
IF TO_DATE(r.FINAL_SR_DATE, 'dd-mm-yy') >= TO_DATE('01-10-16', 'dd-mm-yy')
  THEN
v_STD_REVISED_AMT_INT := (V_STANDRD_AMT - v_OD_Discount) + (V_STANDRD_AMT - v_OD_Discount) *
 2.5/100;

But I am getting error as

ORA-01861: literal does not match format string

Please suggest how I can resolve the issue

A: The string '2017-03-15T00:00:00+05:30' represents a timestamp with time zone. If you want to ignore the time and zone you could just use the date part of the string, but you still need to provide the correct format mask:
TO_DATE(SUBSTR(r.FINAL_SR_DATE, 1, 10), 'YYYY-MM-DD')

You could also keep the time part and ignore the time zone (if you're sure that's a valid thing to do):
TO_DATE(SUBSTR(r.FINAL_SR_DATE, 1, 19), 'YYYY-MM-DD"T"HH24:MI:SS')

although as you are comparing against a date at midnight the time part of your value is a bit irrelevant.
You should also use a 4-digit year for the right hand side of the comparison:
TO_DATE('01-10-2016', 'dd-mm-yyyy')

or more simply a date literal:
DATE '2016-10-01'

so you would end up with:
TO_DATE(SUBSTR(r.FINAL_SR_DATE, 1, 10), 'YYYY-MM-DD') >= DATE '2016-10-01'

If you want to keep the time zone offset as well then you need a different data type:
TO_TIMESTAMP_TZ(r.FINAL_SR_DATE, 'YYYY-MM-DD"T"HH24:MI:SSTZH:TZM')

and then adjust the time zone if necessary, and compare with another timestamp with time zone value, which can also be a literal, e.g.:
TIMESTAMP DATE '2016-10-01 00:00:00 UTC'

or
TIMESTAMP DATE '2016-10-01 00:00:00+05:30'

so you woudl end up with:
TO_TIMESTAMP_TZ(r.FINAL_SR_DATE, 'YYYY-MM-DD"T"HH24:MI:SSTZH:TZM')
  >= TIMESTAMP DATE '2016-10-01 00:00:00+05:30'

or whatever offset is appropriate for your environment; or preferably with a time zone region instead of an offset.


text:
Q: Object binding does not work I'm using XF list view, and want to binding the whole object and then use converter to format the data based on some conditions, but object binding does not work anymore in XF. Test is on XF 2.5.0.91635, and android support library 26.1.0.1. First, when do not use item template, the list view is rendered correctly, though content is showing default object string:
<ListView x:Name="lv"></ListView>

But when using item template, nothing is show, though the number of items are indeed added in list view, and item selected event is fired correctly. Also, debug outputs following messages:
        <ListView x:Name="lv">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>

                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

[0:] Binding: Models.DataItem can not be converted to type 'System.String'
[0:] Binding: Models.DataItem can not be converted to type 'System.String'
[0:] Binding: Models.DataItem can not be converted to type 'System.String'
[0:] Binding: Models.DataItem can not be converted to type 'System.String'
[0:] Binding: Models.DataItem can not be converted to type 'System.String'

And when I add converter to binding expression, the convert function always receives null in its arguments.
add binding code:
List<DataItem> list = new List<DataItem>();
        for(int i = 0; i < 10; i++)
        {
            list.Add(new DataItem
            {
                N = "L " + i.ToString(),
                C = i + 1,
            });
        }
        lv.ItemsSource = list;

A:
And when I add converter to binding expression, the convert function always receives null in its arguments.

If you want to bind to entire object you will need to modify the DataItem like this:
public class DataItem
{
    public String N { get; set; }
    public int C { get; set; }

    //use an Item property to reference itself
    public DataItem Item { get { return this; } }
}

Then you can use it in your ListView together with converter:
<ListView  x:Name="lv" >
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>

                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
 </ListView>

A: Correct way to bind is "Binding collection to ListView" and by providing ItemSource for list:
For example:
private ObservableCollection<Models.DataItem> _dataList;
public ObservableCollection<Models.DataItem> DataList
{
    get { return _dataList; }
    set
    {
        _dataList = value;
        RaisePropertyChanged(() => DataList); // you can use your own property notification mechanism here.
    }
}

Then after setting binding context to your ViewModel:
<ListView ItemsSource="{Binding DataList}" >
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>

            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

Or if you want to display properties from following DataItem:
public class Model.DataItem
{
    public string Property1 {get; set; }
    public string Property2 {get; set; }
    public string Property3 {get; set; }
}

use
<ViewCell>

</ViewCell>

Hope this helps


text:
Q: How to create two different calculations for different options using JavaScript.? This is probably a simple question but I'm not finding anything in my searches and I'm a JavaScript beginner. Maybe I'm not getting the exact clue for my answer
I would like to make a calculator for calculation HRA exemption with the following conditions:
•   Actual HRA received from an employer
•   For those living in metro cities: 50% of (Basic salary + Dearness allowance)
For those living in non-metro cities: 40% of (Basic salary + Dearness allowance)
I have made calculator but stuck up at select option i.e. yes/no as for both options the conditions are different I have searched so many articles in google but could not get the correct solutions, either I may not understand properly if anybody can help me will be appreciated from my heart.
Thanks in advance.
This is my code
`
<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<title> HRA Exemption Form</title>

 HRA Exemption Calculator

        <form>

 HRA Input data

            <form class="container">

                   Basic Salary received p.m
                  <input type="text" class="form-control" id="one"  placeholder="Basic salary received">

                   Dearness Allowance received
                  <input type="text" class="form-control" id="two" placeholder="Dearness Allownace">

                   HRA received
                 <input type="number" class="form-control" id="HRA" placeholder="HRA  received">

                   Total rent paid
                 <input type="text" class="form-control" id="TRP" placeholder="Total rent paid ">

              </form>
              <form name="forms"
                 onsubmit ="return myfun()" >

 Do you live in metros like Mumbai, Delhi, Kolkatta ?

                    <input class="form-check-input" type="radio" name="livingstatus" id="inlineRadio1"
                    value="Yes">
                    Yes

                  <input class="form-check-input" type="radio" name="livingstatus" id="inlineRadio2"
                   value="No">
                  No

                  <button type="button" class="btn btn-warning" onclick="calculate()"> Calculate
             Now</button>

          </form>

`

A: You can select the two inputs and then calculate the answer depending on which one is checked or if none of then are checked show an error message.

<!doctype html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
  <title> HRA Exemption Form</title>

 HRA Exemption Calculator

        <form>

 HRA Input data

          <form class="container">

                 Basic Salary received p.m
                <input type="text" class="form-control" id="one" placeholder="Basic salary received">

                 Dearness Allowance received
                <input type="text" class="form-control" id="two" placeholder="Dearness Allownace">

                 HRA received
                <input type="number" class="form-control" id="HRA" placeholder="HRA  received">

                 Total rent paid
                <input type="text" class="form-control" id="TRP" placeholder="Total rent paid ">

          </form>
          <form name="forms" onsubmit="return myfun()">

 Do you live in metros like Mumbai, Delhi, Kolkatta ?

              <input class="form-check-input" type="radio" name="livingstatus" id="inlineRadio1" value="Yes">
              Yes

              <input class="form-check-input" type="radio" name="livingstatus" id="inlineRadio2" value="No">
              No

                <button type="button" class="btn btn-warning" onclick="calculate()"> Calculate
             Now</button>

          </form>

A: You could also use the .value of the option itself (I changed the checkbox values to "0.5" and "0.4" in the html) and use a ternary operator ( test ? value for true : value for wrong):

        function calculate() {
          var opt = document.querySelector(".form-check-inline input:checked");
          var y = document.getElementById('result');
          var x = document.getElementById('result1');
          var a = +document.getElementById("one").value;
          var b = +document.getElementById("two").value;
          var e = document.getElementById('result2');
          y.innerHTML = a * 12;
          x.innerHTML = b * 12;
          e.innerHTML = opt
            ? opt.value * (a+b)
            : "Please click one option!";
        }
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
  <title> HRA Exemption Form</title>

 HRA Exemption Calculator

        <form>

 HRA Input data

          <form class="container">

                 Basic Salary received p.m
                <input type="text" class="form-control" id="one" placeholder="Basic salary received">

                 Dearness Allowance received
                <input type="text" class="form-control" id="two" placeholder="Dearness Allownace">

                 HRA received
                <input type="number" class="form-control" id="HRA" placeholder="HRA  received">

                 Total rent paid
                <input type="text" class="form-control" id="TRP" placeholder="Total rent paid ">

          </form>
          <form name="forms" onsubmit="return myfun()">

 Do you live in metros like Mumbai, Delhi, Kolkatta ?

              <input class="form-check-input" type="radio" name="livingstatus" id="inlineRadio1" value="0.5">
              Yes

              <input class="form-check-input" type="radio" name="livingstatus" id="inlineRadio2" value="0.4">
              No

                <button type="button" class="btn btn-warning" onclick="calculate()"> Calculate
             Now</button>

          </form>


text:
Q: Getting web fonts to work in IE10 I'm trying to make my website more IE-compatible (now that developing for it is less of a nightmare), but I can't get some web fonts to work. Here's my markup:
@font-face syntax:
@font-face {
    font-family:Roboto Thin;
    font-weight:100;
    font-style:normal;
    src:url(/fonts/ttf/roboto-thin-webfont.ttf) format("truetype"),
        url(/fonts/eot/roboto-thin-webfont.eot) format("embedded-opentype"),
        url(/fonts/svg/roboto-thin-webfont.svg) format("svg"),
        url(/fonts/otf/roboto-thin-webfont.otf) format("opentype"),
        url(/fonts/woff/roboto-thin-webfont.woff) format("woff");
}

Implementation in CSS file:
.animation-text {
    font-family:Roboto Thin,Helvetica Neue,Helvetica,Arial,sans-serif;
    font-weight:100;
    font-style:normal;
    text-align:center;
    margin:auto;
    position: absolute;
    background-position: center;
    background-size: contain;
    animation-fill-mode: forwards;
    top: 1px;
}

#design {
    transform-origin:50% 75%;
    font-size:60px;
    color:#ccc;
    height:auto;
    padding-top:540px;
    opacity:0;
    z-index:4;
    animation-name:text;
    animation-delay:3000ms;
    animation-duration:500ms;
    animation-timing-function:ease-out;
}

HTML:

Design

I've also tested out the code in the four other major browsers running under OS X (Firefox 19, Chrome 25, Safari 6.1, Opera 12), and they all display Roboto flawlessly. IE10 running under Windows 8 falls back to Arial. Shouldn't including .eot and .otf versions of the fonts have fixed this?

A: Try quoting the font and removing the space like the following... (you'll need to change the paths accordingly)
@font-face {
    font-family: 'RobotoThin';
    src: url('Roboto-Thin-webfont.eot');
    src: url('Roboto-Thin-webfont.eot?#iefix') format('embedded-opentype'),
         url('Roboto-Thin-webfont.woff') format('woff'),
         url('Roboto-Thin-webfont.ttf') format('truetype'),
         url('Roboto-Thin-webfont.svg#RobotoThin') format('svg');
    font-weight: normal;
    font-style: normal;
}

.animation-text {
    font-family: 'RobotoThin',Helvetica Neue,Helvetica,Arial,sans-serif;
    /* ... other styles ... */
}


text:
Q: How we merge two database into new database using php I have two databases in my phpmyadmin
 test and test1 now I want to merge it into other  database  i.e test3
Database test has 15 tables . Database test 2 has 23 tables  so that database test 3 contain 15+23 i.e 38  table
I also  check Merge two database into a single database and  How can we merge two databases with identical schemas? link but not found any solution
How it can be done with the help of php??

A: Using php file first of all you need to take dump of multiple database using exec() and mysqldump as
exec("mysqldump --user root -p --databases test1 test2 > file.sql");

This will export multiple database into one file now you can import database into test3 using
exec("mysql -u username -p test3 < file.sql");

A: Since you mentioned phpmyadmin you can do this all in phpmyadmin.
First export both databases (test1 and test2) as SQL. You can follow instructions in this post. Then you can import both of these databases in into test3 using phpmyadmin also.
You probably want to make sure that there are no conflicts with table names to avoid test1 overwriting test2 tables (or vice versa). If you want to keep these tables separate then you can add a prefix to all tables but it really depends what you're trying to do. Since you're expecting 38 tables I am assuming that you don't want to mix the data.

A: Assuming all of the table names are different and we are talking tables only (Im unsure on triggers and other operations) you could use the "Copy database to:
" feature in PHPmyAdmin to do this follow these steps;

*

*Select the database test1

*Go to the operations navigation item along the top

*Go to the Copy database to: section and then enter test3 as the database you wish to migrate to.

*Repeat for test2


text:
Q: Bypass Gatekeeper in Mac OS X Apps without a Mac Developer Membership Scenario
I want to release an app for Mac OS X, but not on the AppStore. The app runs on 10.6 - 10.8 and up.
Problem
Apple requires all apps for Mac OS X 10.8+ to be signed by the developer to get past Gatekeeper. And unless I tell each user to temporarily disable and re-enable gatekeeper just for my app, according to this document and the Mountain Lion change log... my app won't be allowed to run.
From the wording on Apple's website, it sounds like I'll have to pay the $99.00 a year for the certificate. However, I do not want to pay the $99 - I'm not publishing to the AppStore!
Question
Is there any way I can get around paying the $99 for distribution on 10.8+? I know my app will work on 10.6 and 10.7, but according to Apple it won't be allowed to run on 10.8 without the certificate. Is that true? How can I distribute on 10.8+ (preferably a DMG) without a $99 distribution certificate? Thanks in advance!
Edit #1

*

*DMG files are not authenticated by Gatekepper, only the app itself is.

*OS X Lion 10.7.5+ also has Gatekeeper * angry face *

A: Apple currently provides no way to get around Gatekeeper without paying the $99 / year membership fee. To me, this seems unfair because it squishes out the smaller developers (but that's a discussion for elsewhere).
For a rather cumbersome workaround, one can include a ReadMe or note on the download page for their software to explain to users that they need to right click your app and then click 'Open' and then click confirm to run it. I have also found through experimenting that Gatekeeper does not run security checks on DMG files or the installation of files, only the execution / running of Apps. So one could include some kind of note in their DMG installer that told the user exactly how to install and run the app.
Hopefully Apple will provide a workaround for developers (possibly a cheaper solution for a limited membership) that distribute freeware and open source software.

A: You don't need to purchase membership. Just get a code signing certificate from any agency and sign your app with it. Then it will bypass the Gatekeeper check. Gatekeeper only checks whether the app is from identified developer or not.


text:
Q: Was there a reason a probe couldn't have been used in Season 1, Episode 1? In Season 1, Episode 1

 Burnham puts on a space suit and flies out to investigate an anomaly that they can't see from the ship's location.  During the approach the suit apparently has a built-in navigation system and takes evasive action to avoid a space rock.  They know there's a risk of lethal radiation exposure.

My question is, was there an in-universe reason why the ship couldn't have sent out an automated probe to investigate and report back?  I think I might have missed the explanation in the dialog with the captain and the science officer.

A: While Star Trek: Discovery is not adhering strictly to 1966-1969 canon (for example, "Turnabout Intruder" establishes that there's either an institutional ban or a glass ceiling preventing women commanding starships!), the first time, in The Original Series, we see, using automated drone probes of any kind is "The Immunity Syndrome", stardate 4307.1, despite several situations where such a probe might have been useful. Even shuttlecraft are rarely used to extend the ship's sensor range (that same episode being a rare counter-example), unless the ship itself is needed elsewhere.
As such, we can safely assume that Shenzhou does not have robot or remote-control probes it can use. Further evidence for this comes from the fact that someone was going to have to manually pilot a worker-bee to deliver a torpedo. If Shenzhou had robot/remote-control probes, then a torpedo warhead could have been mounted in or on such a probe just as easily as it was beamed out to be planted on a corpse.
It's worth noting that this does not mean that Shenzhou has never been equipped with such a probe, or that they don't exist in this time period at all; only that none were available at the time they were needed. These stories pre-date matter replication on the level we see in TNG. It's possible that Shenzhou can carry such probes, but had used them all up and not been re-supplied.

A: I am going to give a speculative answer since I can think of no evidence with which this can be answered definitively at the moment:

*

*As was mentioned in the comments above, the "scattering field" may have incapacitated the probe, making the sending of one futile.

*Since a shuttle (very small human supporting space craft) was considered not maneuverable enough for the asteroid density, perhaps the probes were also lacking in maneuverability as well, essentially rendering them useless in this situation.

*Perhaps the U.S.S Shenzhou was either not equipped with remote automated probes, or, since it was established that it's an older ship and that they are on the edge of federation space, it may have not had any probes left on board.


text:
Q: Truncate table on migration down method of ActiveRecord Rails 3.1 I have the following defined on my up method on my migration to set initial data:
  def up
    Color.create!({:id=>1,:name=>"",:color=>"FF6633"})
    Color.create!({:id=>2,:name=>"",:color=>"93B233"})
    Color.create!({:id=>3,:name=>"",:color=>"4D90D9"})
    Color.create!({:id=>4,:name=>"",:color=>"C43092"})
  end

Is there any truncate directive I can put on the down method like:
def down
   Color.truncate
end

Or since I'm setting the IDs on the create should I use only the destroy_all method of the model Color ?

A: You can simple use this in your up method, this will solve your both truncate and id resetting problem also.
def up
   ActiveRecord::Base.connection.execute("TRUNCATE table_name")
   Color.create!({:id=>1,:name=>"",:color=>"FF6633"})
   Color.create!({:id=>2,:name=>"",:color=>"93B233"})
   Color.create!({:id=>3,:name=>"",:color=>"4D90D9"})
   Color.create!({:id=>4,:name=>"",:color=>"C43092"})
end

Cheers!

A: Firstly, you don't have to pass :id into create! because ActiveRecord will automatically handle that, thus :id likely to get ignored (standard case assumed).
Secondly, it is not a good practice to use ActiveRecord query builder in migration because should the model Color name be changed, you are to have a broken migration. I highly recommend you to use pure SQL and execute that query with execute().
Thirdly, for the #down method, you shouldn't truncate the table. You should destroy those 4 colors that you created in #up.
Here's how I would write it:
def down
  colors = ["FF6633", "93B233", "4D90D9", "C43092"]
  Color.where(:color => colors).destroy_all
end


text:
Q: Parsing JSON parameters in Android {"vsUserName":"d475","vsPassword":"8080","vsIPAddress":"192.168.1.1"}

This is the key value pairs that I have to parse in Android and used to login and password. I am new in android so no knowledge of parsing in android.

A: If you would like to parse JSON into model, then you can use google gson library its easy to use.
{"vsUserName":"d475","vsPassword":"8080","vsIPAddress":"192.168.1.1"}
Other approach is to parse json manually as:
Get the json object first
    JSONObject jObject = new JSONObject(result);

then get key-value pairs
String aJsonString = jObject.getString("STRINGNAME");

and so on...
For further assistance you can visit this link
How to parse JSON in Android

A: you should take a look at this - http://www.javatpoint.com/android-json-parsing-tutorial
your json like - {"vsUserName":"d475","vsPassword":"8080","vsIPAddress":"192.168.1.1"}
with help of - http://hayageek.com/android-http-post-get/
try this may be this could be helpful.. i'm not tested it -- pls let me know if problem persist -  The steps to do it below -
Follow the steps to send HTTP POST requests.
1. Create an object of HttpClient

*Create an object of HttpPost

*Add POST parameters with url

*Finally making an HTTP POST request

A:     Boolean bIsSuccess = false; // Write according to your logic this is demo.

    public void parseResponse(JSONObject response) {

        try {
            JSONObject jObject = new JSONObject(String.valueOf(response));
            bIsSuccess = jObject.getBoolean("success");

        } catch (JSONException e) {
            e.printStackTrace();
            Toast.makeText(Class.this, "" + e.toString(), Toast.LENGTH_LONG).show(); // Test
        }

    }


text:
Q: IndexError: list index out of range for list of lists in for loop I've looked at the other questions posted on the site about index error, but       I'm still not understanding how to fix my own code. Im a beginner when it comes to Python. Based on the users input, I want to check if that input lies in the fourth position of each line in the list of lists.
Here's the code:
#create a list of lists from the missionPlan.txt
from __future__ import with_statement

listoflists = []
with open("missionPlan.txt", "r") as f:
    results = [elem for elem in f.read().split('\n') if elem]
    for result in results:
        listoflists.append(result.split())
#print(listoflists)
#print(listoflists[2][3])

choice = int(input('Which command would you like to alter: '))
i = 0
for rows in listoflists:
    while i < len(listoflists):
        if listoflists[i][3]==choice:
            print (listoflists[i][0])

        i += 1

This is the error I keep getting:

not getting inside the if statement

A: So, I think this is what you're trying to do - find any line in your "missionPlan.txt" where the 4th word (after splitting on whitespace) matches the number that was input, and print the first word of such lines.
If that is indeed accurate, then perhaps something along this line would be a better approach.
choice = int(input('Which command would you like to alter: '))

allrecords = []

with open("missionPlan.txt", "r") as f:
    for line in f:

        words = line.split()
        allrecords.append(words)

        try:
            if len(words) > 3 and int(words[3]) == choice:
                print words[0]
        except ValueError:
            pass

Also, if, as your tags suggest, you are using Python 3.x, I'm fairly certain the from __future__ import with_statement isn't particularly necessary...
EDIT: added a couple lines based on comments below. Now in addition to examining every line as it's read, and printing the first field from every line that has a fourth field matching the input, it gathers each line into the allrecords list, split into separate words as a list - corresponding to the original questions listoflists. This will enable further processing on the file later on in the code. Also fixed one glaring mistake - need to split line into words, not f...
Also, to answer your "I cant seem to get inside that if statement" observation - that's because you're comparing a string (listoflists[i][3]) with an integer (choice). The code above addresses both that comparison mismatch and the check for there actually being enough words in a line to do the comparison meaningfully...


text:
Q: need c program for 5 minutes timer i am building a project for a cycling bath in which the motor goes up and down. the micrlimit switch senses up & down position. once switch is activated motor cuts off and timer starts. after 5 minutes the motor starts in reverse direction and moves till it trips the switch theis continues indefinitly. i had written a program as below
#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>
#include <stdbool.h>

int main(void){
    DDRD=0x00;// for input port-UP & DOWN Micro Switch
    DDRC=0xff;// for output port- UP & DOWN Motor
    while(1){
        if(PIND==0xff)// checking the status of PIN PD5 & PD6, if both is '1', turns ON the down Motor
            _delay_ms(100); // for debouncing of switch
        PORTC=0x40;// turns ON down motor

        if(PIND==0xbf)// checking the status of PIN PD6 (Dn sw), if it is '0', turns off the down Motor
        {
            _delay_ms(100); // for debouncing of switch
            PORTC=0x00;   // Turning off the down Motor
            int32_t second;
            for (second=0; second <5LL*60;++second)
            {
                if (second > 5)
                {
                    PORTC=0X80; // turn ON UP motor
                } else
                { PORTC = 0x00;}
            }
            {
                if(PIND==0xdf);// checking the status of PIN PD5 (UP SW), if it is '0' turns off the UP motor,
                _delay_ms(100); // For debouncing of switch
                PORTC=0x00;// Turning off the UP Motor
                int32_t second;
                for (second=0; second <5LL*60;++second)
                {
                    if (second > 5)
                    {
                        PORTC=0X40; // turn ON DOWN motor
                    } else
                    { PORTC = 0x00;}
                }

            }

            {
                if(PIND==0x9f);// checking the status of PIN PD5 & 6 if both 0 then stop motor
                _delay_ms(100); // for debounicng of switch
                PORTC=0x00; // trun off up/down motor

            }
        }
    }
}

pls advise this will work

A: Your code does not get the style award. It might compile, but I will not work as intended.
First you need to define what you want to do. Create a flowchart.
Then you look up how you create a state machine in C. Because this looks like a perfect job for a state machine.
Create a small dummy application perhaps, on the pc.
You'll also want to look up how to compare, for set inputs.
if(PIND==0xdf); is not the way. Try if(PIND & (1<<PIN).
Then you will have learned a lot, and perhaps your able to run this on target.
Or, you get a Siemens LOGO (PLC) and program it with an IEC 61131-3 variant.
It will provide you with the building blocks to build this reliably and quickly. At the small cost of the hardware.

To answer your title, to create a wait time this long on an embedded platform a software timer is used. One way to do this is with a system tick.
uint32_t stim1 = 0; // unsigned 32 bit software timer 1

const unsigned int interval = 20; // Interval of hardware timer in milliseconds

// Timer 1 Compare interrupt, constant interval, 20 ms for example.
ISR (TIMER1_COMPA_vect)
{
    // Saturating increment software timer1
    if(stim1 < (0xFFFFFFFF-interval))
      stim1 += interval;
}

int main(void){
  init_tim1();

  while(1){
    if(stim1 > 1000){      // wait 1 second
      PORTB ^= (1 << 0);   // toggle led
      stim1 = 0;           // reset software timer
    }
  }
}


text:
Q: Visualize autocorrelation with python in multiple timeseries one dataset Background
Performing multiple linear regression analysis on dataset containing 21 time-series of 4 data points. Each data points represents 9 variables which could describe a value. The 21 data points are for hydrological catchments.
R² adjusted is not decreasing rapidly after adding more variables.
Problem statement
Since the 4 data points are a static window of a longer time-series I am thinking autocorrelation between the data-points is the problem.
Question
How to visualize or estimate if there is autocorrelation inside the different time-series? Preferably with stats-models.
What I have tried:

I think ACF of the residuals is not working since I have 21 time-series.


text:
Q: How to write a string containing private ssh key to a file? I am using Azure DevOps for my pipeline. I have a copy of the public and private keys. The public key is already added to the server via the creation process using Terraform.
For testing purposes, I have created a variable $key to store the private key. The variable is part of the DevOps pipeline and it can be retrieved by the bash script on the build server.
I want to use that key to SSH to a remote server. When I try to write the $key to a file and then use it e.g.
ssh user@10.10.10.10 -i keyfile

I get asked for a passphrase. I believe that this is to do with the format of the private key file. It appears as a long string without line breaks.
The private key appears as follows when echoed:
-----BEGIN RSA PRIVATE KEY----- MIIEowIBAAKCAQEAiyaucjBXLAy4yEFKez7b1uBUNmkycyAeOE3f9a37XqX9WRj46mH/cUE+18Oc DZWQyu5Pei3wRarv19E6XMLYcis63pbogncdIqHlvc25QLHKz+mZ6TQm/CDBKhK5GHifJSODcsNa YH7Gwy7y3T46LOicoz+cKhPm7McQ3uthSSsEZQyjlnOhQ+s4cjPa29rszlnp8HvMm+hniouCD2Kh b9/xv0yomh1d+pd3RtvdksqX4Zac0vmshpeMYZEVTPabhkfJksd8VnYYzGjjlf0Axxf+gSEM8Ime LGtdcefl4S/lNwLuYBZxjgqbSl23oHsT/ZmiWxIXfqBOHm6mcv+qLQIDAQABAoIBAGF6aX4Iqyhq iQ+P3XNU54AxigzLyNGpUEI1G4zpokv9j+rYeZcHq4BVKobPuwQxIEtogjie8dB8HKRdJ7tPq3zf F9BSevLaKojWTTCXaw0M/3yCspURObYp4+drUkr4RNQpeq3sd+VdKjQVMYEXVH2dPg2GRAmeA4kf MoxW68Hq1w2bByUnrrehoidu46r6KBlQyUApJmu5y2Xbo5izbyEoRQoGF0Sz2EHW2AckxTwMkovF 78dh8L3b3DAd0aAF8ijewA/aCy+gSzZzihGcpFMKVxVh5McrzssS74ThjaeKKnDRIPlP02je0rtf DOuWoivc9RP/o5nJvNU2qzLri4ECgYEA7edgmf/FVIrIBc8QqWpvF0WYhWMusgBm8DUvOGnnevPo MFRgNTAjl+rDKfTvOTnphYrEKYoLJTDpNZGvopSUsra5IANAcHSxM8dpUyXGqIlIC9rdzOQNZhON Ss/f4d9wT1fX8mWaIPiC0wC/s1V9fCRKDKARhc4mtIKlm+S7Wj0CgYEAlbxTLuoHN6Na7UOoPpp8 HEPGGItHx/QFHLwFuhe663xLaFIXqJsVgQUd88dUs5lRZ6ydGba6LeUNEOvFvHiSV7cj0YydvyJJ 7wjlu5Ge13fYTNm2uEDDhARLBum2Rx1wwBD/ovsjnevNjZeYU9ahZhiMjIv90RT7mTDLGiNBvrEC gYBWfXHfSt9gtvu1MOxryygMG98xTzeguwixd4RtTAM97gKR33sCmze1eUHutP9rnKRLSoG6YFdg 9AE02nwx7TaKKmfvPX9l4uaxXmPqOKeaih5JQQ61+Irue1k4w44vPd5E2jjGBS4dontdXr5S4le2 lDLfmCoGrUXhBkZTALskOQKBgDRr2jNye1RfPFYUebJxI0JB9/hfyqGWLLQCn36nECmhOkUreFzu 7nhc8j+GaYD3DCjfpaB6+HNY3VovMOrqy1EqLMAQGqnvtzKYStWABbwpmPBOyEl5Yvm1Bw9Egywi gna7fMPyaGXBSBVqHUo8ugSkU5Bg8ltgnTTkgDaGYV4BAoGBAKKAaI7hajJKYkWgbW5L744f2XvX coi5CAEdqQ+Bfah/THt+s57tfAOAiQWutnmv7vzLlWjiHip+MrJYnQ+Whb5VzeDS1qNYbcZfgNNl 6OOkPcq7v0NVczeaoGWtKFdL4ZCcwciw08YolSthBUvY8ZAZoLoyE3YoBFaa7VKil1iO -----END RSA PRIVATE KEY-----

What is the best way to format the string and write it to a .pem file?
Or if this is a silly question, where is the best place to store a private key file for automation?
An alternative way that I have done this for testing is to store the private key as part of a repository and then pulled that down during build. This method works fine but I fear it is not "best practice".

A: Not really sure if this counts as an answer but I got it working. I used the "Install SSH key" task in Azure DevOps to store the public and private keys. You can paste the keys in as strings into this task and it will install the keys and make them available for use with other servers.
More information about the SSH Key Task


text:
Q: Recognize active backend login I set diffrent identityCookie name and session name for frontend section and backend section.
My question is how to recognize active backend login in frontend section? I have two separately login form each for my sections.
I used abhi1693/yii2-user from github and advnaced yii2 template.
Thanks.

A: You should write you own code. If frontend & backend located on one domain you can store user id in cookies. Frontend will know that if a cookie with a specific name is exists that user have active backend login.
Yii2 have useful manual about cookie. Try write after backend login. Of course you should protect, and validate cookie value before read, because client can replace it.
$cookie = new Cookie([
    'name' => 'isBackendLogin',
    'value' => \Yii::$app->security->hashData(Yii::$app->user->id, 'salt'),
    'expire' => time() + 86400 * 365,
]);
\Yii::$app->getResponse()->getCookies()->add($cookie);

in Frontend you can check this cookie:
$isBackendLoginHash = \Yii::$app->request->cookies->getValue('isBackendLogin');
$isBackendLogin = \Yii::$app->security->validateData($isBackendLoginHash, 'salt');


text:
Q: String similarity Search in R I have a big list of Product Descriptions something like
Water bottles 1L
Water Can 1L
Aerated Drinks 1L
Chips Potato
Doritos Chips
Bread
Yogurt 300ML
Milk

Ofcourse the list is in Millions.
I am trying to create a search similarity. I want a search function which will Pick Similarity descriptions. If I search on Milk Products, it should bring Milk, Butter, Yogurt something like that.
For that I used levenshteinSim and run all the descriptions in Loop and compare with my search string. By the time it ran for all Million records it is taking long time. Is there any algorithm that will take data frame and string as input parameter and min score to get the values?

A: This is a pretty straight forward case for grep
grep("milk", searchDF[["description"]], ignore.case = TRUE)

EDIT:
Sorry didn't realize you were searching a list of dataframes rather than just one dataframe with all of the descriptions in one long string.
vapply(searchList, function(x) any(grepl("milk", x, ignore.case = TRUE)),
       logical(1))

vapply will look through all the elements of your list in a vectorized fashion and speed things up.  grepl is like grep, but it returns a logical rather than an index.  any then checks all of the logicals returned by grepl to see if the search string "milk" was there.  The logical(1) at the end just indicates that the function will return a single logical value for each index of the searchList.  You could also use sapply and avoid having to put the logical(1) at the end, but vapply is generally safer since sapply will sometimes return an unexpected data type.
Edit 2:
I am not familiar with levenshteinSim but the function adist in utils also calculates the levenshtein distance.  If you want the minimum distance instead of just presence or absence in your list of strings you can use a similar strategy but with adist.
vapply(searchList, function(x) min(adist(x, "milk 1L",
                                         ignore.case = TRUE)),
       numeric(1))


text:
Q: Homeomorphism $\mathbb{B}^n \to \mathbb{B}^n$ that is not a diffeomorphism I am trying to prove that for any $s > 0, F_s(x) = |x|^{s-1}x$ defines a homeomorphism from $\mathbb{B}^n$ to itself, which is a diffeomorphism iff $s = 1$.
My attempt so far:
Let $F_s(x) = |x|^{s-1}x = |x|^s \widehat{x}$, where $\widehat{x} = \frac{x}{|x|}$ is the normalisation of $x$. Hence, we see that $|F_s(x)| < 1$ if $|x| < 1$, and thus that $F_s(\mathbb{B}^n) \subset \mathbb{B}^n$. Also, for $s,t > 0$  we see that
$$
F_t \circ F_s (x) = F_t(|x|^s \widehat{x}) = ||x|^s \widehat{x}|^t \widehat{|x|^s \widehat{x}} = |x|^{st} \underbrace{|\widehat{x}|^t}_{=1} \widehat{|x|^s \widehat{x}} = |x|^{st} \widehat{x} = F_{st}(x).
$$
In particular, this gives that $F_{1/s} \circ F_{s} = F_s \circ F_{1/s} = F_1 = id_{\mathbb{B}^n}$. So $F_s$ is a bijection. It is a homeomorphism because $F_s$ is a composition and quotient of the continuous maps $|\cdot|$ and $(\cdot)^s$ for $x \neq 0$. For $x = 0$ we see that $F_s(x) \to 0$ as $x \to 0$, so it is also continuous in $x =0$. Finally, for $s = 1$ we have the identity map, which is a diffeomorphism. For $s < 1$, then $F_s(x) = |x|^{s-1}x = \frac{x}{|x|^{1-s}}$, I suspect that this is not differentiable in the origin, but I don't know how to show this, that's where I am stuck. For $s > 1$, then the inverse $F_{1/s}$ is not smooth since $\frac{1}{s} < 1$.

A: First, remark that if $F_s$ is a diffeo, then its differential is invertible at any point by the chain rule:
$$F^{-1}\circ F=\mathrm{id}\implies\forall x,D(F^{-1})_{F(x)}\circ DF_x=\mathrm{id}.$$
Thus it has trivial kernel at all points of $\mathbb{B}^n$.
Now take the smooth curve $\gamma:(-1,1)\to\mathbb{B}^n$ defined by $\gamma(t)=(t,0,\dots,0)$. You can check that for $t>0$, $(F_s\circ \gamma)(t)=(t^s,0,\dots,0)$. If $F_s$ was smooth, then $F_s\circ\gamma$ would also be by composition: for $s<1$, this is not the case. Now, for $s>1$, note that by the chain rule
$$(DF_s)_0((1,0,\dots,0))=(DF_s)_{\gamma(0)}(\gamma'(0))=(F_s\circ\gamma)'(0)=(st^{s-1},0,\dots,0)|_{t=0}=0,$$
and this contradicts the triviality of the kernel of $(DF_s)_0$.
You can also conclude for $s>1$ as you did in the post, namely showing that $F_s$ is not a diffeo since $(F_s)^{-1}=F_{\frac{1}{s}}$ is not differentiable at $0$ since$\frac{1}{s}<1$ and this case has already been dealed with.


text:
Q: PyCharm not connecting to Python 3 console When I code in PyCharm and press Run, no window opens to run the program.  Nothing really happens. Do I have to input the coding language when setting up the application?

A: You have to create/define a project interpreter first:
Go to File -> Settings -> Project: YourProject -> Project Interpreter

Choose / create your environment and hit OK. PyCharm can use already exisitng environments or you can create a new one (using pip or anaconda).
Afterwards you also can edit the Run/Debug configuration (you can find it in the standard menu bar next to the Run button). Here you have to choose the script that you want to run with your new environment: Configurations Tab -> Script Path. But just simply hit run should already invoke the Project Interpreter for your script.


text:
Q: Can a user able to see the extra achievements as well when the app goes live on the Google Play store? I have created some achievements for my app and published them on GPGS, but now I don't want them and created some more achievements and drafted the previously created achievements.
So, the current status for old achievements (example 6 achievements) is 'Changes available to testers'
and for the newly created (example 5 achievements)'Available to everyone'.
I have configured only 5 newly created (published on GPGS) achievements in the game.
All the 11 achievements are visible to Tester.
My question is, does the other achievements which are in the 'Changes available to testers' state is visible to users in the achievement section when my app goes live on the Google Play Store? or the user can only see the achievement which is in publish state and configured in the game?


text:
Q: OpenCV LabView Copy Image to a bigger one I have a big problem since some days. I have created in LabView an empty Image with the size 4096x4096 and want to copy a smaller Image to it in OpenCV.
As a result I will get everytime a black image.
Mat imgIn = Mat(SizeX, SizeY, CV_16U, &image[0]);          // Small pic
Mat imOut = Mat(4096, 4096, CV_16U, &imgOut[0]);

imgIn.copyTo(imOut(Rect(500, 500, imgIn.size().width, imgIn.size().height)));

for(int i = 0;i < 4096;i++){
    for(int j = 0;j < 4096;j++){

         if((imOut.data[i,j])>300) *test += 1;
         *imgOut++ = imOut.data[i,j];
    }
}

Here my new VI from Labview:

My result:

Update: after the updated code:
Mat imgIn = Mat(SizeX, SizeY, CV_16U, &image[0]);          // Small pic
Mat imOut = Mat(4096, 4096, CV_16U, &imgOut[0]);

imgIn.copyTo(imOut(Rect(500, 500, imgIn.size().width, imgIn.size().height)));

Pic:

Update 2 Code:
// --- Dll entry point ---
 BOOL APIENTRY DllMain( HANDLE hModule,
                   DWORD  ul_reason_for_call,
                   LPVOID lpReserved
                 )
{
UNREFERENCED_PARAMETER(hModule);
UNREFERENCED_PARAMETER(lpReserved);
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
    break;
}
return TRUE;
}

#ifdef __cplusplus
extern "C" {
#endif  /* __cplusplus */

__declspec(dllexport) INT myDoSomething(unsigned int *test, unsigned short *image, int SizeX, int SizeY, unsigned short *imgOut){

// Alloc Memory
Mat imgIn = Mat(SizeX, SizeY, CV_16U, &image[0]);          // Small pic
Mat imOut = Mat(4096, 4096, CV_16U, &imgOut[0]);           // Big pic

imgIn.copyTo(imOut(Rect(1000, 1000, imgIn.size().width, imgIn.size().height)));

A: Problem Solved:
OpenCV treats Matrices not as in LabView like X,Y (column, row), but as row,column!!
Mat imgIn = Mat(SizeY, SizeX, CV_16UC1, &image[0]);


text:
Q: Delphi XE3 watches that create a new instance of a class I'm new to Delphi and I'm using Rad Studio XE3.
For debug purposes, I'd like to see at runtime what value would have a TDateTime variable if it was assigned some value. For example, having var date : TDateTime:
date := 0

So, I was wandering if is it possible to use the watches window for that purpose. I tried something like TDateTime.Create(0) or TDateTime := 0, but both give erroro messages as output.
Is there a way to do what I need with watches?
Thanks in advance.
Update 1 0 As TDateTime does not work too.

A: A watch only works to watch existing variables; AFAICT, you can't create new variables to add to the watch window at runtime.
(Also, TDateTime isn't an object in Delphi, as others have noted in the comments to your question. It's simply a double that encodes the date in the integral portion of the value, and the time in the fractional (decimal) part, oo you can't create a TDateTime instance.)
You can use the evaluate/modify window (available when the debugger is at a breakpoint via View->Debug Windows->Evaluate/Modify or the right-click menu, Run->Evaluate/Modify, or Ctrl+F7) to evaluate an expression like `DateToStr(0)'. The only way to watch a variable is to actually declare (and use) the variable in your code, and then set a watch on that variable; simply declaring it isn't enough, as the compiler will optimize away unused variables. Also, the function you're evaluating must be actually used somewhere in your code itself, or it won't be available. (The linker doesn't include functions in your executable that aren't actually called in most cases.)
If you only want the variable available when debugging, but not in your release code, you can surround it with {$IFDEF DEBUG} (which is pre-defined in the Debug build configuration automatically).
procedure TForm1.FormCreate(Sender: TObject);
{$IFDEF DEBUG}
var
  CurrDate: TDateTime;
{$ENDIF}
begin
  {$IFDEF DEBUG}
  CurrDate := Date;
  // Use CurrDate so the compiler doesn't eliminate it.
  {$ENDIF}
  // Your other code here as usual
end;


text:
Q: How to get a Rails form that is submitted with invalid data to repopulate the user entered fields I'm working to build a Rails 3 + devise, user registration page. This will be an additional page that does not replace the existing devise registration page. This page will include user info and billing info.
I'm trying to get the form to submit and if the form fields do not save, have the reloaded page include the user's previously inputted data. Here's a snippet:
<%= form_for(User.new, :url => '/pricing/sign_up') do |f| %>
    <%= f.label :email %>
    <%= f.email_field :email %>
<% end %>

When the form submits with invalid data. When the view re-renders, the existing email entered is not persisted. How can I make the existing user's input persist to help the user quickly correct mistakes and submit a valid form?

A: The key is to have the form_for use the right object. So, instead of
<%= form_for(User.new, :url => '/pricing/sign_up') do |f| %>

you should be using an instance variable to contain the object, like this
<%= form_for(@user, :url => '/pricing/sign_up') do |f| %>

The controller actions would look like this:
# Note: this may need to be an `edit` method instead?
def new
  @user = User.new
end

# Note: this may need to be an `update` method instead?
def create
  @user = User.new(params[:user])
  if @user.save
    # Do something... Usually a redirect with success message.
  else
    render :new
  end
end

What this create method is doing is it's filling the @user object with params from the form. And then the call to @user.save will, behind the scenes, call @user.valid? and, if no errors are returned, then the record is saved to the database. But this part is key. If @user.valid? does result in errors, then the errors collection on @user will be populated. Then, after the render :new completes, and re-renders your user form, the form will be able to spit out errors messages by accessing the @user.errors collection. Otherwise, the way you had it before, you always had a User.new object in the form which would never have had any errors because it was never used to attempt record validation before.
How to display the errors in your form is a matter of preference and a little beyond the scope of this question. Here's a guide: http://guides.rubyonrails.org/active_record_validations.html#displaying-validation-errors-in-views

A: I think it's because of your form_for declaration where you're creating new instance of User on every call.
If you move the User.new to your controller and render the new action upon failure in create action then you should see the user entered values in the form fields.
Something like the following should work:
# app/controllers/users_controller.rb

def new
  @user = User.new
end

def create
  @user = User.new(params[:user])

  respond_to do |format|
    if @user.save
      ...
    else
      format.html { render :new }
    end
  end
end

Then in your view:
<%= form_for(@user, :url => '/pricing/sign_up') do |f| %>
  <%= f.label :email %>
  <%= f.email_field :email %>
<% end %>

A: The values of the form fields are driven by the model you pass to form_for, so in your case they will always be empty because you are passing a brand new user object.
You should be using an instance variable which is set in the controller; in the new action this will be a new User model but in the create action it will be a model which has attributes set via the form:
# app/controllers/users_controller.rb
def new
  @user = User.new
end

def create
  @user = user.create(user_params)

  if @user.save
    redirect_to user_path(@user)
  else
    render :new
  end
end

Then in the form:
<%= form_for(@user, :url => '/pricing/sign_up') do |f| %>
  <%= f.label :email %>
  <%= f.email_field :email %>
<% end %>


text:
Q: How to align image? I've got thumbnails which larger side is 70px (e.g 70x40 or 52x70).
I need to create a gray box 70x70px and put the thumbnail in it, so that image is aligned with the box at top vertically and center horizontally.
How to do that?
I've tried with an ImageView 70x70px, gray background, but image is not positioned as it should (it's in vertical and horizontal center, instead of vertical top and horizontal center).
I've also tried wrapping it with LinearLayout 70x70px, gray background and then positioning it, but then i get 1 or 2px line between LinearLayout and ImageView. I tried to set padding and margins to 0, but the gray line stays on...

A: I had exactly the same issue and found the solution in that thread. For those who struggle with that problem, just add this line to your ImageView:
android:adjustViewBounds="true"

A: Use a RelativeLayout. Set the background to be gray and the size to be 70px square. Put the ImageView as a child of the RelativeLayout, with android:layout_alignParentTop="true" and android:layout_centerHorizontal="true".

A: Damn!!
Of course, it was so simple: just had to add android:scaleType="fitStart" to ImageView - no need for all those layouts..


text:
Q: Display a specified content on a Page and all its child pages I have a website with 5 main pages (consider them as sections), then 3-5 sub pages for each of them. I would like to display a flash banner for each section, i.e. it should display the flash banner on that page and all its sub pages.
Right now i am able to get that o the main page by using the following code.
<?php if (is_page('our-school-district')) { ?>
                    <object width="664" height="217">
                        <param name="movie" value="<?php bloginfo('url'); ?>/wp-content/uploads/2011/03/school_district.swf" />
                        <param name="wmode" value="transparent" />
                        <embed src="<?php bloginfo('url'); ?>/wp-content/uploads/2011/03/school_district.swf" width="664" height="217" wmode="transparent"></embed>
                        <!-- It Is Not Just About The Seeds That Are Planted, but the Garden That Surrounds Them. -->
                    </object>
                    <?php } ?>

How do I get it on all sub pages too?

A: You can do that by using this nice little function:
function is_page_or_child_of($slug){
    global $post;
    if (empty($slug))
        return false;
    //is it the page?
    if ($post->post_name = $slug)
        return true;
    //check the children
    $page = get_page_by_path($slug);
    $children = get_pages('child_of='.$page->ID.'&sort_column=post_date&sort_order=desc');
    foreach ($children as $sub){
        if ($post->ID == $sub->ID){
            return true;
        }
    }
    return false;
}

and instead of using is_page('our-school-district') use s_page_or_child_of('our-school-district')

A: You should create a template for each page that way you can add the banner directly to it without having to mess with a bunch of php unless the banner will be outside of the page template view this link for a better explanation Wordpress Codex - Pages


text:
Q: How do I use widget collision to switch screens in kivy? Im trying to create a game which consists of several areas, accessed by moving the circle onto the boundaries of the screen. I created a transit widget and defined a function to switch screens when there's a collision but it keeps giving errors. The error I got is that WindowManager does not have an attribute manager.
.py file:
class Transit(Widget):

    def transit(self,circle):
        if self.collide_widget(circle):
            WindowManager.manager.current = "a1"
    pass

class Wall(Widget):

    def collision(self, circle):
        if circle.collide_widget(self):
            if circle.center_x > (self.pos[0] + self.size[0]) or circle.center_x < self.pos[0]:
                circle.velocity_x = -1 * circle.velocity_x
            elif circle.center_x > self.pos[0] and circle.center_x < (self.pos[0] + self.size[0]):
                circle.velocity_y = -1 * circle.velocity_y

class Circle(Widget):
    velocity_x = NumericProperty(0)
    velocity_y = NumericProperty(0)
    velocity = ReferenceListProperty(velocity_x, velocity_y)

    def move(self):
        self.pos = Vector(*self.velocity) + self.pos

class Move(Widget):

    circle = ObjectProperty(None)
    wall1 = ObjectProperty(None)
    wall2 = ObjectProperty(None)
    wall3 = ObjectProperty(None)
    wall4 = ObjectProperty(None)
    transit1 = ObjectProperty(None)

    def __init__(self, **kwargs):
        super(Move, self).__init__(**kwargs)
        self._keyboard = Window.request_keyboard(self._keyboard_closed, self)
        self._keyboard.bind(on_key_down = self._on_keyboard_down)
        Clock.schedule_interval(self.update, 0)

    def update(self, dt):
        self.circle.move()
        self.wall1.collision(self.circle)
        self.wall2.collision(self.circle)
        self.wall3.collision(self.circle)
        self.wall4.collision(self.circle)

        self.transit1.transit(self.circle)

    def _keyboard_closed(self):
        self._keyboard.unbind(on_key_down=self._on_keyboard_down)
        self._keyboard = None

    def _on_keyboard_down(self, keyboard, keycode, text, modifiers):
        if keycode[1] == 'left':
            self.circle.velocity_x -= 0.1
        elif keycode[1] == 'right':
            self.circle.velocity_x += 0.1
        elif keycode[1] == 'up':
            self.circle.velocity_y += 0.1
        elif keycode[1] == 'down':
            self.circle.velocity_y -= 0.1
        return True

class Menu(Screen):

    pass

class Start(Screen):

    pass

class area1(Screen):

    pass

class WindowManager(ScreenManager):

    pass

kv = Builder.load_file("dw.kv")

class Adventure(App):
    def build(self):
        return kv

Adventure().run()

and heres my .kv file
Circle:

    size: 30,30
    canvas:
        Ellipse:
            pos: self.pos
            size: self.size

WindowManager:

    Menu:
    Start:
    area1:

Menu>:

    name: "menu"
    #Adding gridlayout
    GridLayout:
        rows :3
        cols :  1

        AnchorLayout:
            anchor_x : "center"
            anchor_y : "center"

            Label:
                text: "Adventure"
                font_size: 40

        AnchorLayout:
            anchor_x : "center"
            anchor_y : "center"

            TextInput:
                id: ign
                size_hint : (.4, None)
                height : 30
                hint_text : "Enter your name"
                multiline : False

        AnchorLayout:
            anchor_x : "center"
            anchor_y : "center"

            Button:
                text: "Start"
                font_size: 40
                size: 100, 75
                size_hint: (None, None)
                on_release: app.root.current = "start"
Start>:

    name: "start"
    Move:
        wall1 : r1
        wall2 : r2
        wall3 : r3
        wall4 : r4
        transit1 : t1
        circle : circle
        Circle:
            id : circle
            pos: root.center_x , root.center_y

        Wall:
            id : r1
            pos: 0, 400
            size: 350, 250
            canvas:
                Rectangle:
                    pos: self.pos
                    size: self.size
        Wall:
            id : r2
            pos: 0 , 0
            size: 350, 250
            canvas:
                Rectangle:
                    pos: self.pos
                    size: self.size
        Wall:
            id : r3
            pos: 500 , 400
            size: 800, 250
            canvas:
                Rectangle:
                    pos: self.pos
                    size: self.size
        Wall:
            id : r4
            pos: 500 , 0
            size: 800, 250
            canvas:
                Rectangle:
                    pos: self.pos
                    size: self.size
        Transit:
            id : t1
            pos: 0, root.center_y
            size: 1, 600

area1>:

    name: 'a1'

A: Your only problem is that the line:
WindowManager.manager.current = "a1"

is trying to access the manager attribute of the WindowManager class. You actually want to access that attribute of the WindowManager instance. To do that, you can replace that line with:
App.get_running_app().root.current = "a1"


text:
Q: WordPress Recent Post should be 5 with continue reading link I set my front page as recent posts. But It display all the posts at front page.

*

*I need to display only 5 recent posts at first page.

*I like to have that "Continue reading" after 10 lines of the each post content.

A: Q1 - Controlling Amount Of Posts Displayed

*

*Dashboard -> Settings -> Reading -> Blog pages show at most -> change to 5 -> Save Changes -> test

*If that didn't work you may be using a custom theme which controls posts per page with a function. Check functions.php for something like if ( $query->is_front_page() and in that if statement may be something similar to $query->set( 'posts_per_page', '10' ); You will want to change 10 to 5.
Q2 - Controlling Post Excerpt Length

*

*The easiest way if one has no experience working with wordpress template files is to add the <!--more--> tag in your post editor and wordpress will cut the post at exactly that spot. Here's some info about using it.

*You will see on the above linked page the option to customize it with a function. It requires messing around with the template files a little. Leave a comment if you want to know more about that and I can try to help you with a better explanation.


text:
Q: How to execute only "mvn test" without executing dependent goals "clean' and "compile"? I am executing Cucumber test suite from multiple command prompts, but "mvn test" command executed from each cmd, calls 'clean' and 'compile' goals internally, which refresh the classes in JVM and that throws  'NoClassDefFoundError' exception for any random classes while the scripts are executing.
I want to execute multiple feature files in parallel to reduce execution time.
Since my framework is integration of Selenium/Cucumber/TestNG/Maven & OATS and executes as complex workflow, I can not use 'fork' feature to execute in multiple threads. Just looking for some way to execute "mvn test" goal independently.
Also tried with "mvn surefire:test" but something is wrong in my pom.xml  node, so that is not working. Please suggest the template for pom.xml to execute using "mvn surefire:test"


text:
Q: If C and C++'s double (and float) is IEEE 754-1985, then are the integer representations and Infinity, -0, NaN, etc, all left unused? It appears that JavaScript's number type is exactly the same as C and C++'s double type, and both are IEEE 754-1985.
JavaScript can use IEEE 754 as integers but when the number becomes big or gets an arithmetic calculation such as divided by 10 or by 3, it seemed like it can switch into floating point mode. Now C and C++ only use IEEE 754 as double and therefore only use the floating point portion and do not use the "integer" portion. Therefore, do C and C++ left the integer representations unused?
(and C left the NaN, Infinite, -Infinite, -0 unused as I recalled never using them in C).

A:
If that's the case, isn't it true that the IEEE 754's representations of [integers and some special values] were all unused, as C and C++ didn't have the capability of referencing them?

This notion appears as if it might stem from the fact that JavaScript uses the IEEE-754 binary64 format for all numbers and performs (or at least defines) bitwise operations by converting the binary64 format to an integer format for the actual operation. (For example, a bitwise AND in JavaScript is defined, via the ECMAScript specification, as the AND of the bits obtained by converting the operands to a 32-bit signed integer.)
C and C++ do not use this model. Floating-point and integer types are separate, and values are not kept in a common container. C and C++ evaluate expressions based on the types of the operands and do so differently for integer and floating-point operations. If you have some variable x with a floating-point value, it has been declared as a floating-point type, and it behaves that way. If some variable y has been declared with an integer type, it behaves as an integer type.
C and C++ do not specify that IEEE 754 is used, except that C has an optional annex that specifies the equivalent of IEEE 754 (IEC 60559), and C and C++ implementations may choose to conform use IEEE-754 formats and to conform to it. The IEEE-754 binary64 format is overwhelmingly used for double by C and C++ implementations, although many do not fully conform to IEEE-754 in their implementation.
In the binary64 format, the encoding as a sign bit S, an 11-bit "exponent" code E, and a 52-bit "significand code," F (for "fraction," since S for significand is already taken for the sign bit). The value represented is:

*

*If E is 2047 and F is not zero, the value represented is NaN. The bits of F may be used to convey supplemental information, and S remains an isolated sign bit.

*If E is 2047 and F is zero, the value represented is +∞ or −∞ according to whether S is 0 or 1.

*If E is neither 0 nor 2047, the value represented is (−1)S•(1 + F/252)•2E−1023.

*If E is zero, the value represented is (−1)S•(0 + F/252)•21−1023. In particular, when S is 1 and F is 0, the value is said to be −0, which is equal to but distinguished from +0.

These representations include all the integers from −253−1 to +253−1 (and more), both infinities, both zeros, and NaN.
If a double has some integer value, say 123, then it simply has that integer value. It does not become an int and is not treated as an integer type by C or C++.

But from (-253 - 1) to (253 - 1), that's a lot of numbers unused…

There are no encodings unused in the binary64 format, except that one might consider the numerous NaN encodings wasted. Indeed many implementations do waste them by making them inaccessible or hard to access by programs. However, the IEEE-754 standard leaves them available for whatever purposes users may wish to put them to, and there are people who use them for debugging information, such as recording the program counter where a NaN was created.

A: The int number 123 is exactly the same as the double number 123.0, as you can easily see by testing 123 == 123.0.  Their representations are different internally though.


text:
Q: JS import module and run on page load I want to call my function main() using html onload event and console.log text imported from another (generateObject.js) file, but when I import function, onload event stop working and function main() is not anymore used.
html:
<!DOCTYPE html>
<html>
  <head>
    <script type="text/javascript" src="main.js"></script>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  </head>
  <body onload="main()">
  </body>
</html>

generateObject.js:
export function hello() {
    return "Hello";
}

main.js:
import { hello } from './generateObject.js';
function main(){
      console.log(hello());
}

main();

When I try console.log("text") in main() it works but when I try to use imported function it's not.
What should I do to fix that?
Errors in Chrome console:
Uncaught SyntaxError: Cannot use import statement outside a module (main.js:1)

index.html:8 Uncaught ReferenceError: main is not defined at onload (index.html:8)

A: modules will have its own scope. They are not available in the global scope like the normal scripts. So it's accessible only inside main.js in your case.
To make it work you need to add it to global scope explicitly.
import { hello } from './generateObject.js';
function main(){
      console.log(hello());
}

window.main = main;

Alternatively, you can remove the event handler from HTML and add it in the JS file.
html
<!DOCTYPE html>
<html>
  <head>
    <script type="text/javascript" src="main.js"></script>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  </head>
  <body>
  </body>
</html>

main.js
import { hello } from './generateObject.js';
function main(){
      console.log(hello());
}

window.addEventListener('load', main)

A: generateObject.js:
export function hello() {
    return "Hello";
}

main.js:
import { hello } from './generateObject.js';
function main(){
      console.log(hello());
}

main();

Working example

A: You should add at the end of main.js a call to the main function. Try writing main(); at the bottom of the file.


text:
Q: Disable save as image on smartphones using all browsers ( chrome, firefox, ie, cm, opera ) i want to disable the option to save as images on smartphones (android and IOS) using mobile browsers like chrome, firefox, ie, cm, opera, ie. Could anyone have a solution to this?
chi

A: These days it is not really possible anymore to distinguish between mobile and other browsers, but you may try wp_is_mobile. There are plugins that try to do a better job.
Then, if the user agent is mobile you may try to disable saving of the image, but there is no definite way to do this. To display the image it must be sent to the smartphone. You cannot take over the smartphone, so the user will always have methods to wrestle the image from you.
That said, there are methods to make it difficult for users. The most obvious one is to set images as backgrounds with css. This disables the normal way of saving images. Here are some other options.


text:
Q: Can JsonProvider deserialise to a Generic.Dictionary? I'm learning about type providers and it looks like a ground breaking feature. However, I can't manage to deserialise json with JsonProvider so that the target type has a Generic.Dictionary property. It can be done with Json.NET. Here is the code:
type ByProv = JsonProvider<"""{"dict":{"A":1,"B":2}}""">
type ByHand(d:Dictionary<string,int>) =
    member val dict = d with get,set

let text = """{"dict":{"C":3,"D":4}}"""
let newt = JsonConvert.DeserializeObject<ByHand> text
let prov = ByProv.Parse text
printfn "%A" newt.dict.["C"]
//Can only call statically inferred A or B (and it will throw at run-time)
printfn "%A" prov.Dict.A

Apparently, dict is inferred to be a record type and not a Dictionary by default. Can this be overriden?

A: The JSON type provider assumes that JSON records are used for storing records (with fixed field names) and that JSON arrays are used for storing collections. Your example is one of the cases where this does not work all that great.
When you need to access a JSON record which has dynamically named fields, you can use the underlying JsonValue that is exposed by the provided type:
type ByProv = JsonProvider<"""{"dict":{"A":1,"B":2}}""">

let text = """{"dict":{"C":3,"D":4}}"""
let prov = ByProv.Parse text

prov.Dict.JsonValue.["C"].AsInteger()

This is not as nice and I suppose the JSON type provider could be extended to handle this better (and treat records more like arrays). Feel free to submit an issue for discussion & perhaps submit a pull request to F# Data on GitHub!

A: If you want to convert a JSON dictionary to a .net dictionary you can use the Properties() method, and the dict function, like this:
type ByProv = JsonProvider<"""{"dict":{"A":1,"B":2}}""">

let text = """{"dict":{"C":3,"D":4}}"""

let prov = ByProv.Parse text

let d = prov.Dict.JsonValue.Properties() |> dict

the type of d is System.Collections.Generic.IDictionary<string,JsonValue>. If you want it to be integer you can use a Seq.map in the middle:
let d =
    prov.Dict.JsonValue.Properties()
    |> Seq.map (fun (k,v) -> k,v.AsInteger())
    |> dict


text:
Q: Confusion with Entity Framework versions I am having hard time understanding the Entity Framework versions released by Microsoft. I have a base entity framework version of 4.1 which didn't support enums by itself. After the June 2011 CTP was released I was excited to use it so that I can get LINQ support for enums. So I planned to develop my application for the time being using enums support of June 2011 CTP, hoping that by the time my application was ready, the next version would appear and support enums. After June 2011 CTP, the Entity Framework 4.1 Update 1 was released which to my understanding doesn't support enums. After that version 4.2 appeared and I doubt again whether it supports enums. So being the first time that I am developing application using Microsoft technologies, I am a little confused. I have a couple of issues

*

*If CTP version is released, then shouldn't the next release be based on that rather than discontinuing what was supported earlier in the CTP as a major feature ?

*If I need to deploy my application(with EntityFramework June 2011 CTP) on a separate machine for testing, will I need to install anything extra for the Entity Framework June 2011 CTP version to work.
Please pardon me if I don't understand the versions of Entity Framework correctly. Also the first issue above may be my ignorance, but what I am primarily concerned with is the second issue.

A: *

*No. CTP is preview of something that can be released. But when it will be released nobody knows. It even be never released or the final version doesn't have to include enums at all. Current CTP doesn't have go live licence so you can easily invest into development of something that would never reach production code.

*You will need .NET 4.0 and that CTP.

CTPs are only for previewing new API not for real development because any next CTP version or RTM version can introduce breaking changes or remove features previously available in CTP. In case of EF this already happened before releasing EF 4.1 where custom conventions were completely removed from RTM so it can happen again. In case of enums I somehow hope that support will be either completely redesigned or removed because current implementation is not sufficient.


text:
Q: Geocoding without map Can I to use Google maps geocode API without map?
I have a textbox with autocomplete Google Maps API Place and I want after the user has typed the street number, I get the zip code.
Regards

A: Autocomplete is one of a small number of cases where it is permitted to use a Google Maps API service without a map, although if you do use it in conjunction with a map that map must be a Google Map:
https://developers.google.com/maps/documentation/javascript/places#places_autocomplete
You don't need to use the Geocoder to extract the zipcode. It is provided in the PlaceResult object returned by a getPlaces() call on the Autocomplete object after place_changed event has occurred (ie. once a user has selected a completion):
https://developers.google.com/maps/documentation/javascript/places#getting_place_information

A: I'm sure that you can.  Check out the Geocoding API. It's simply a set of web services you can call to get a geocoding result that contains the postal code, among other things.


text:
Q: Does $\sum\frac{1}{2^n}^{\frac{1}{2^n}} $ converge? Does $\Sigma\frac{1}{2^n}^{\frac{1}{2^n}} $ converge?  I am using this to test whether $\Sigma\frac{1}{n(n^{\frac{1}{n}})} $ converges using Cauchy's condensation test.  I suspect that it does not converge because the exponent is not greater or equal to 2, by analogy to $\Sigma \frac {1}{u}^{\frac{1}{u}}$.

A: Stealing MathematicsStudent1122's comment, we have $$\lim_{n \to +\infty} \left(\frac{1}{n}\right)^{\frac 1n} = 1$$.  Once your $n \ge 2$ the terms are greater than $\frac 12$ so the sum diverges.


text:
Q: Which AMQPSpout are you using? I would like to consume messages from the RabbitMQ using a an AMQP Spout.
Can you recommend me some good one (meaning tested also on the production)?

A: I found this spout https://github.com/ppat/storm-rabbitmq suitable for my project. I didn't tested yet in production, but it behaves well in the development phase.
  I hope that this answer will help others.
Good luck.
  Florin


text:
Q: Internal structure of jagged array in .NET I created simple jagged array:
int[][] a = new int[2][];
for (int i = 0; i < 2; i++)
{
    a[i] = new int[3];
    for (int j = 0; j < 3; j++)
        a[i][j] = i * 3 + j;
}

After that I started debugging my application and looked to this array sturcture in memory (x86):
0x03022478           0  // SyncBlockIndex (a)
0x0302247C  0x61B8D5BC  // TypeHandle (a)
0x03022480           2  // a.Length
0x03022484  0x617A4C8A  // ???
0x03022488  0x03022494  // a[0]
0x0302248C  0x030224AC  // a[1]
0x03022490           0  // SyncBlockIndex (a[0])
0x03022494  0x61B9C448  // TypeHandle (a[0])
0x03022498           3  // a[0].Length
0x0302249C           0  // a[0][0]
0x030224A0           1  // a[0][1]
0x030224A4           2  // a[0][2]
0x030224A8           0  // SyncBlockIndex (a[1])
0x030224AC  0x61B9C448  // TypeHandle (a[1])
0x030224B0           3  // a[1].Length
0x030224B4           3  // a[1][0]
0x030224B8           4  // a[1][1]
0x030224BC           5  // a[1][2]

I understand almost all the data: SyncBlockIndexes, TypeHandles, Lengths, Elements. But I can't understand only one line:
0x03022484  0x617A4C8A  // ???

What it is?
Update 1:
I tried resolve this address value with different SOS command:
!DumpArray 0x617A4C8A
<Note: this object has an invalid CLASS field>
Invalid object

!DumpAssembly 0x617A4C8A
Fail to fill Assembly

!DumpClass 0x617A4C8A
Invalid EEClass address

!DumpDomain 0x617A4C8A
Fail to fill AppDomain

!DumpMD 0x617A4C8A
617a4c8a is not a MethodDesc

!DumpMT 0x617A4C8A
617a4c8a is not a MethodTable

!DumpObj 0x617A4C8A
<Note: this object has an invalid CLASS field>
Invalid object

!DumpSig 0x617A4C8A
!DumpSig <sigaddr> <moduleaddr>

Update 2:
In array of references types this DWORD should mean address of array element MethodTable. For example, for object[10] this DWORD is address of MethodTable for System.Object. But in the case of int[][] this DWORD is not valid MethodTable address (I use SOS-command DumpMT for checking it).

A: Quoting from the SSCLI source code (\sscli20_20060311\sscli20\clr\src\vm\object.h):
// ArrayBase encapuslates all of these details.  In theory you should never
// have to peek inside this abstraction
class ArrayBase : public Object
{
    ...
    // This MUST be the first field, so that it directly follows Object.  This is because
    // Object::GetSize() looks at m_NumComponents even though it may not be an array (the
    // values is shifted out if not an array, so it's ok).
    DWORD       m_NumComponents;
    ...
    // What comes after this conceputally is:
    // TypeHandle elementType;        Only present if the method table is shared among many types (arrays of pointers)
    // INT32      bounds[rank];       The bounds are only present for Multidimensional arrays
    // INT32      lowerBounds[rank];  Valid indexes are lowerBounds[i] <= index[i] < lowerBounds[i] + bounds[i]

The extra word you are seeing should be the TypeHandle elementType:

Only present if the method table is shared among many types (arrays of pointers)

\sscli20_20060311\sscli20\clr\src\vm\typehandle.h:
// At the present time a TypeHandle can point at two possible things
//
//      1) A MethodTable    (Intrinsics, Classes, Value Types and their instantiations)
//      2) A TypeDesc       (all other cases: arrays, byrefs, pointer types, function pointers, generic type variables)

int[][] is array of int[], TypeHandle of int[] is TypeDesc. So, strange data is TypeHandle, but it can't resolved by !DumpMT because it's not a MethodTable.
The SSCLI is of course not the real Microsoft CLR implementation, but I understand it is a stripped down version of the 2.0 CLR.


text:
Q: Batch file that hides open cmd windows I have a console application which runs another 3 console applications.
I need to write a script like a batch file or vb script which can show/hides all open cmd windows on my windows xp/7.
How can I do this?

A: I have done this using a command line utility called nircmd which provides an additional library of commands. The win command allows manipulation of windows. The following command will hide any windows with cmd.exe in the title bar:
nircmd win hide stitle cmd.exe
A hidden window can also be revealed by replacing "hide" with "show".


text:
Q: How do I resolve hibernate c3p0 throwing StaleStateException when checkoutTimeout is configured? My hibernate configuration is:
.... <hibernate config of username,password etc> ...
hibernate.c3p0.min_size           = 75;
hibernate.c3p0.max_size           = 100;
hibernate.c3p0.timeout            = 3600;
hibernate.c3p0.idle_test_period   = 300;
hibernate.c3p0.acquireRetryAttempts = 5;
hibernate.c3p0.acquireRetryDelay  = 10;
hibernate.c3p0.checkoutTimeout    = 50;

I added the last three configurations (acquireRetryAttempts, acquireRetryDelay, checkoutTimeout) recently.
Without these configurations I do not see any problems.
However, with these configurations I see StaleStateException only for operations that write to the database (no exceptions at all for any other database operations).
I want checkoutTimeout so that I can track all instances when my connection pool becomes devoid of free connections. Without checkoutTimeout my app will wait indefinitely for a connection -- even if the pool is devoid of free connections. I want to specifically avoid that scenario.
I set checkoutTimeout at 50ms by measuring the time required for getEntityManager() to execute. The p99.99 were under 10ms. The p100 were under 1250m; however, these were rare outliers (maybe 12 data points). The requests volume on average is 3000tps.
I noticed that setting the timeout value to be higher, at 500ms or 1000ms does not cause StaleStateException. I don't understand why.