问:
Calculate the module of a vector, in VHDL
How can I calculate the module of a vector?

As a vector is not a pre-defined type in VHDL it makes sense to me that there is no function implementing the modue of a vector. If there is such I have not found it.

This is basically a problem of obtaining the square root of a number, as the module can be defined as:

sqrt(a^2+b^2+...+n^2)

Implementing the sum of all the members of the vector squared is not a challenge so I think the most necessary part is having a function to calculate the square root of a number.

As far as I'm concerned there isn't any official package implementing this function. How to implement a function to calculate the module of a vector?

Or if you prefer it, how to implement a square root?

答:
This is one possible solution. I will provide you 3 codes.

-The first one provides the type definition used for the vector. Its not important but it is needed to make it work.

-The second one is the package in which the function is defined. It is commented so that you can easily adapt it to any kind of vector. It can probably be upgraded to make it adapt by itself using some parameters by this works fine.

-The third one is a testbench to try it out.

```<code>library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;

package tipos is
constant bandas : positive := 4;
type vector32 is array (0 to bandas-1) of signed (31 downto 0);
end package tipos;
</code>```

Be aware of calling properly the library with the vector definition. In my case it was compiled to work for the ModelSim simulation

```<code>library IEEE;
use IEEE.std_logic_1164.all;
use IEEE.numeric_std.all;
library work; use work.tipos.all;

package propios is
--function declaration.
function module (a : vector32; bands: natural) return unsigned;
end propios;   --end of package.

package body propios is  --start of package body
--definition of function
--based on: https://en.m.wikipedia.org/wiki/Methods_of_computing_square_roots#Binary_numeral_system_.28base_2.29
function module (a : vector32; bands: natural) return unsigned is --To adapt it to a diferent number of bits in the input vector:
--substitute the 71 for the needed number. Number of bits in each element of the vector *2 + power of two that can represent the maximum
--number of bands, or fields. In this case, 32bit numbers, maximum number of bands, 256, so 2^8. 32*2+8=72.
variable sum : unsigned(71 downto 0):= (others => '0');
variable b : unsigned(71 downto 0):=(0=>'0', 70 => '1', others => '0');
variable a_unsig: unsigned(31 downto 0):=(others =>'0');--for this vector use the same length as the input vector, 32bit in my case.
variable result: unsigned (71 downto 0):= (others => '0');
begin

for i in 0 to bands-1 loop--Sum of all the elements squared
    a_unsig:=unsigned(a(i));
    sum:=sum + (a_unsig * a_unsig);
end loop;

--Square root of sum
while b>sum loop--Do any needed changes here. You only have to change the 71's
    b:='0'&'0'& b(71 downto 2);
end loop;

while (b/=0) loop
    if (sum>=result+b) then
        sum:=sum - (result + b);
        result:=('0'& result(71 downto 1))+b;
    else
        result:='0'& result(71 downto 1);
    end if;
    b:='0' & '0' & b(71 downto 2);
end loop;

return result(35 downto 0);--sqrt(2^72)=2^36. Use half of the bits you put in place of 71
end module;

end propios;  --end of the package body
</code>```

And here is the testbench. Again take care of calling the packages properly

```<code>library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;
library work;
use work.propios.all;
use work.tipos.all;

ENTITY test IS

END test;
Architecture simple of test is
signal a:vector32;
signal c: unsigned(35 downto 0);
signal b: natural:= 4;
begin
a(0)<="00000000110010011010011100000000";
a(1)<="00000000110010011010011100000000";
a(2)<="00000000110010011010011100000000";
a(3)<="00000000110010011010011100000000";

process
begin
wait for 200ps;
c<= module (a , b);
wait;
end process;

end simple;
</code>```

Body:
This is one possible solution. I will provide you 3 codes.

-The first one provides the type definition used for the vector. Its not important but it is needed to make it work.

-The second one is the package in which the function is defined. It is commented so that you can easily adapt it to any kind of vector. It can probably be upgraded to make it adapt by itself using some parameters by this works fine.

-The third one is a testbench to try it out.

library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;

package tipos is
constant bandas : positive := 4;
type vector32 is array (0 to bandas-1) of signed (31 downto 0);
end package tipos;

Be aware of calling properly the library with the vector definition. In my case it was compiled to work for the ModelSim simulation

library IEEE;
use IEEE.std_logic_1164.all;
use IEEE.numeric_std.all;
library work; use work.tipos.all;

package propios is
--function declaration.
function module (a : vector32; bands: natural) return unsigned;
end propios;   --end of package.

package body propios is  --start of package body
--definition of function
--based on: https://en.m.wikipedia.org/wiki/Methods_of_computing_square_roots#Binary_numeral_system_.28base_2.29
function module (a : vector32; bands: natural) return unsigned is --To adapt it to a diferent number of bits in the input vector:
--substitute the 71 for the needed number. Number of bits in each element of the vector *2 + power of two that can represent the maximum
--number of bands, or fields. In this case, 32bit numbers, maximum number of bands, 256, so 2^8. 32*2+8=72.
variable sum : unsigned(71 downto 0):= (others => '0');
variable b : unsigned(71 downto 0):=(0=>'0', 70 => '1', others => '0');
variable a_unsig: unsigned(31 downto 0):=(others =>'0');--for this vector use the same length as the input vector, 32bit in my case.
variable result: unsigned (71 downto 0):= (others => '0');
begin

for i in 0 to bands-1 loop--Sum of all the elements squared
    a_unsig:=unsigned(a(i));
    sum:=sum + (a_unsig * a_unsig);
end loop;

--Square root of sum
while b>sum loop--Do any needed changes here. You only have to change the 71's
    b:='0'&'0'& b(71 downto 2);
end loop;

while (b/=0) loop
    if (sum>=result+b) then
        sum:=sum - (result + b);
        result:=('0'& result(71 downto 1))+b;
    else
        result:='0'& result(71 downto 1);
    end if;
    b:='0' & '0' & b(71 downto 2);
end loop;

return result(35 downto 0);--sqrt(2^72)=2^36. Use half of the bits you put in place of 71
end module;

end propios;  --end of the package body

And here is the testbench. Again take care of calling the packages properly

library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;
library work;
use work.propios.all;
use work.tipos.all;

ENTITY test IS

END test;
Architecture simple of test is
signal a:vector32;
signal c: unsigned(35 downto 0);
signal b: natural:= 4;
begin
a(0)<="00000000110010011010011100000000";
a(1)<="00000000110010011010011100000000";
a(2)<="00000000110010011010011100000000";
a(3)<="00000000110010011010011100000000";

process
begin
wait for 200ps;
c<= module (a , b);
wait;
end process;

end simple;


来源: stackexchange

问:
send mail via php yii until success on time
i have php function that send mail on special time ever 7 days but when i send mail its sometimes not sent because server busy or not available ,my question is how to try send my email many times when its something wrong every 10 minute until its send success </p>

```<code>    private function sendEMailMessage($args) {
    $failed = true;
    for($i = 0; $i < 5 && $failed; $i ++) {
        $failed = Utilities::sendEMailMessage ( $args ) != '';
        if ($failed) {
            sleep ( 15 );
        }
    }
}
</code>```

<p>//its this work or not ???</p>

答: The another way you can do this is setting a flag in database table. Based on the flag  value you can send/resend the email. On successful sending of email you can delete or reset the flag .</p>

ContentLicense: CC BY-SA 3.0

Body:
i have php function that send mail on special time ever 7 days but when i send mail its sometimes not sent because server busy or not available ,my question is how to try send my email many times when its something wrong every 10 minute until its send success

    private function sendEMailMessage($args) {
    $failed = true;
    for($i = 0; $i < 5 && $failed; $i ++) {
        $failed = Utilities::sendEMailMessage ( $args ) != '';
        if ($failed) {
            sleep ( 15 );
        }
    }
}

//its this work or not ???


问:
MySQL query with a JOIN and WHERE clause not working
I'm trying to get a MySQL query to work but keep getting an error. I want to join two tables tbl_collab and tbl.uploads with a WHERE clause but can't figure out what I've got wrong. Thanks.

```<code> SELECT tbl_collab.collab_userid, tbl_collab.file, tbl_collab.tbl_upload_id,
    tbl_uploads.id,tbl_uploads.title,
    FROM tbl_uploads
    LEFT JOIN tbl_uploads.id ON tbl_collab.tbl_upload_id
WHERE tbl_collab.collab_userid='2'
</code>```

I get this error:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM tbl_uploads LEFT JOIN tbl_uploads.id ON tbl_collab.tbl_upload_id WHERE ' at line 3

答: There is a comma (,) in your SELECT clause after tbl_uploads_title that should be removed.</p>

Body:
I'm trying to get a MySQL query to work but keep getting an error. I want to join two tables tbl_collab and tbl.uploads with a WHERE clause but can't figure out what I've got wrong. Thanks.

 SELECT tbl_collab.collab_userid, tbl_collab.file, tbl_collab.tbl_upload_id,
    tbl_uploads.id,tbl_uploads.title,
    FROM tbl_uploads
    LEFT JOIN tbl_uploads.id ON tbl_collab.tbl_upload_id
WHERE tbl_collab.collab_userid='2'

I get this error:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM tbl_uploads LEFT JOIN tbl_uploads.id ON tbl_collab.tbl_upload_id WHERE ' at line 3


问:
JavaScript unexpected NaN?
So I have to make some code that, when the user types a number from 1-4, it will do either + - * or /, depending on what number they choose.

```<code>console.log("Calculator program");
console.log("1. Add numbers");
console.log("2. Subtract numbers");
console.log("3. Multiply numbers");
console.log("4. Divide numbers");

var choice = prompt ("What is your choice?");

if (choice == 1)
{
  console.log(number1 + number2);
}
if (choice == 2)
{
  console.log(number1 - number2);
}
if (choice == 3)
{
  console.log(number1 * number2);
}
if (choice == 4)
{
  console.log(number1 / number2);
}

var number1 = prompt("Type in a number");
var number2 = prompt("Type in another number");
</code>```

The user is meant to put the numbers in after they have chosen a function, however when the user types in the first number, a NaN appears.

I assume this is because the user has not even types in the 2 numbers, but I need the user to type the numbers last.

Any help and advice would be very appreciated, thanks

答: assignments don't hoist so number1 and number 2 aren't defined at the time you use them</p>

Title: JavaScript unexpected NaN?

Body:
So I have to make some code that, when the user types a number from 1-4, it will do either + - * or /, depending on what number they choose.

console.log("Calculator program");
console.log("1. Add numbers");
console.log("2. Subtract numbers");
console.log("3. Multiply numbers");
console.log("4. Divide numbers");

var choice = prompt ("What is your choice?");

if (choice == 1)
{
  console.log(number1 + number2);
}
if (choice == 2)
{
  console.log(number1 - number2);
}
if (choice == 3)
{
  console.log(number1 * number2);
}
if (choice == 4)
{
  console.log(number1 / number2);
}

var number1 = prompt("Type in a number");
var number2 = prompt("Type in another number");

The user is meant to put the numbers in after they have chosen a function, however when the user types in the first number, a NaN appears.

I assume this is because the user has not even types in the 2 numbers, but I need the user to type the numbers last.

Any help and advice would be very appreciated, thanks


问:
Typical latencies on unladen networks
I'd like to know typical round-trip times on networks in order to determine whether or not they will be the limiting factor in the latency of a whole application. Measuring it on a laden 100Mbps network here I get 95% of pings under 500µs with a median of 400µs.

What are typical latencies on unladen networks and how does the bandwidth spec (e.g. 1Gb, 10Gb) of the network affect the latency?

答:
On 1gb hardware I see 80µs ICMP latency, I cannot help on 10GigE or InfiniBand.

At faster fabrics though it really depends upon what protocols you are using, TCP often has more acceleration options than other protocols and hence can reach higher performance figures.  Similarly it also depends upon what NIC and operating system and how the NICs are configured, whether you want lower latency or higher bandwidth.

Looking at 10GigE NICs you will find many have a TCP offload engine (ToE) which manages everything for you.  Without ToE you need to look at interrupt coalescing configuration, how long the OS will wait before pushing and pulling packets from the NIC.

ContentLicense: CC BY-SA 2.5

Title: Typical latencies on unladen networks


问:
Removing columns that satisfy a condition from a big data.frame in R
I have a big data.frame; 100,000 observations of 700 variables.

Most of the variables have actually value 0 in all the observations, and I would like to remove that variables/columns.

I tried the following,

```<code>data <- data[apply(data, 2, function(x){all(x == 0)})]
</code>```

But the apply took a lot of time to resolve.

I tried a while, in case the problem was working with all data at once.

```<code>i <- 1
while (i <= ncol(data)) {
  if (all(data[i] == 0)) {
    data[i] <- NULL
  } else {
    i <- i+1
  }
}
</code>```

But I kept having the same problem, it took a lot.

So,

Why does that operation take THAT long? Even though the data.frame is big, the operation is pretty simple.

and, above all

Is there any way to do this faster?

答:
Using vectorized operation like colSums speeds up the operation on my machine -

```<code>> set.seed(123)
> df = data.frame(matrix(sample(0:1,100000*700,replace = T,prob = c(0.9999999,0.0000001)), ncol = 700))
> system.time(df1 <- df[apply(df, 2, function(x){all(x == 0)})])
user  system elapsed
1.386   0.821   2.225
> system.time(df2 <- df[,which(colSums(df)==0)])
user  system elapsed
0.243   0.082   0.326
> identical(df1, df2)
[1] TRUE
</code>```

Body:
I have a big data.frame; 100,000 observations of 700 variables.

Most of the variables have actually value 0 in all the observations, and I would like to remove that variables/columns.

I tried the following,

data <- data[apply(data, 2, function(x){all(x == 0)})]

But the apply took a lot of time to resolve.

I tried a while, in case the problem was working with all data at once.

i <- 1
while (i <= ncol(data)) {
  if (all(data[i] == 0)) {
    data[i] <- NULL
  } else {
    i <- i+1
  }
}

But I kept having the same problem, it took a lot.

So,

Why does that operation take THAT long? Even though the data.frame is big, the operation is pretty simple.

and, above all

Is there any way to do this faster?

Body:
Using vectorized operation like colSums speeds up the operation on my machine -

> set.seed(123)
> df = data.frame(matrix(sample(0:1,100000*700,replace = T,prob = c(0.9999999,0.0000001)), ncol = 700))
> system.time(df1 <- df[apply(df, 2, function(x){all(x == 0)})])
user  system elapsed
1.386   0.821   2.225
> system.time(df2 <- df[,which(colSums(df)==0)])
user  system elapsed
0.243   0.082   0.326
> identical(df1, df2)
[1] TRUE


问:
Scala.js - pass command line arguments from SBT run
When running the app using the sbt run while developing normal JVM app, I can pass command line arguments using run <args>. When I try the same with Scala.js, I get an error "No valid parser available". When trying runMain variant like runMain Main.main arg, the error is "Expected non-whitespace character", with arrow pointing just behind Main.main.

Is there some way how to pass arguments to the Scala.js / Node.js application when running it from SBT?

(I am using Scala.js 0.6.15).

答:
One can define a custom task calling node.js, and parse arguments using SBT parsers. Add this into build.sbt:

```<code>import complete.DefaultParsers._

lazy val runa = inputKey[Unit]("Run app with arguments")

runa := {
  (fastOptJS in Compile).value // build it first
  val args: Seq[String] = spaceDelimited("<arg>").parsed
  val npmRun = "node index.js" + args.map("\"" + _ + "\"").mkString(" "," ","")
  npmRun.!
}
</code>```

You also need to create a file index.js in your project root, containing something like this:

```<code>require("./target/scala-2.12/xxxx-jsdeps.js");

require("./target/scala-2.12/xxxx-fastopt.js");
</code>```

Body:
One can define a custom task calling node.js, and parse arguments using SBT parsers. Add this into build.sbt:

import complete.DefaultParsers._

lazy val runa = inputKey[Unit]("Run app with arguments")

runa := {
  (fastOptJS in Compile).value // build it first
  val args: Seq[String] = spaceDelimited("<arg>").parsed
  val npmRun = "node index.js" + args.map("\"" + _ + "\"").mkString(" "," ","")
  npmRun.!
}

You also need to create a file index.js in your project root, containing something like this:

require("./target/scala-2.12/xxxx-jsdeps.js");

require("./target/scala-2.12/xxxx-fastopt.js");


答:
You need to accept the numbers before the if else logic and also convert those numbers either to int or float for computation (by default user prompt gets as string):

console.log("Calculator program");
console.log("1. Add numbers");
console.log("2. Subtract numbers");
console.log("3. Multiply numbers");
console.log("4. Divide numbers");

var number1 = prompt("Type in a number");
var number2 = prompt("Type in another number");
number1 = parseFloat(number1);
number2 = parseFloat(number2);
var choice = prompt ("What is your choice?");

if (choice == 1)
{
  console.log(number1 + number2);
}
if (choice == 2)
{
  console.log(number1 - number2);
}
if (choice == 3)
{
  console.log(number1 * number2);
}
if (choice == 4)
{
  console.log(number1 / number2);
}```

Title: JavaScript unexpected NaN?


问:
Getting 404 error when submitting a form
Routes:

```<code>Route::post('orders/edit-order-content/{$id}', 'Admin\OrderController@addProduct')->name('addProductToOrder');
Route::resource('/orders', 'Admin\OrderController');
</code>```

Controller:

```<code>public function addProduct($id){
  dd($id);
}
</code>```

View:

```<code>{!! Form::open(['route' =>['addProductToOrder',$order->id], 'id'=>'editOrderContent']) !!}
{!! Form::label('product_id','Product ID') !!}<br>
{!! Form::input('text','product_id') !!}<br>
{!! Form::label('qty','Quantity') !!}<br>
{!! Form::input('number','qty',1,['min'=>'1'])!!}<br>
{!! Form::submit('Add product',['class'=>'btn btn-info ','id'=>'addProduct']) !!}
{!! Form::close() !!}
</code>```

Why am I getting 404 page? I tried to do it with new controller, but also got 404 error...

答:
So, the solutions is, you cannot use the $ sign in your routes as a variable:

Replace

```<code>Route::post('orders/edit-order-content/{$id}', 'Admin\OrderController@addProduct')->name('addProductToOrder');
</code>```

With

```<code> Route::post('orders/edit-order-content/{id}', 'Admin\OrderController@addProduct')->name('addProductToOrder');
</code>```

Body:
Routes:

Route::post('orders/edit-order-content/{$id}', 'Admin\OrderController@addProduct')->name('addProductToOrder');
Route::resource('/orders', 'Admin\OrderController');

Controller:

public function addProduct($id){
  dd($id);
}

View:

{!! Form::open(['route' =>['addProductToOrder',$order->id], 'id'=>'editOrderContent']) !!}
{!! Form::label('product_id','Product ID') !!}

{!! Form::input('text','product_id') !!}

{!! Form::label('qty','Quantity') !!}

{!! Form::input('number','qty',1,['min'=>'1'])!!}

{!! Form::submit('Add product',['class'=>'btn btn-info ','id'=>'addProduct']) !!}
{!! Form::close() !!}

Why am I getting 404 page? I tried to do it with new controller, but also got 404 error...

Body:
So, the solutions is, you cannot use the $ sign in your routes as a variable:

Replace

Route::post('orders/edit-order-content/{$id}', 'Admin\OrderController@addProduct')->name('addProductToOrder');

With

 Route::post('orders/edit-order-content/{id}', 'Admin\OrderController@addProduct')->name('addProductToOrder');


问:
Add and remove a TextView dynamically in Android
I have set up a FrameLayout which has a TextView on top of a ListView. Now, in the MainActivity, after executing some code, I check whether the ListView is empty. If it is, I display the TextView, if not, I remove the TextView.

The code is as follows:

Following is the main.xml file:

```<code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/flMain"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/tvAddItem"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Add some subjects"
        android:textSize="20sp" />

    <ListView
        android:id="@+id/ItemsList"
        android:layout_width="match_parent"
        android:layout_height="0dip"
        android:layout_weight="1" />

</FrameLayout>
</code>```

In the MainActivity class, I do the following:

MainActivity.java

```<code>TextView tvNoItem = (TextView) findViewById(R.id.tvAddItem);
ListView subListView = (ListView) findViewById(R.id.itemsList);
FrameLayout fl = (FrameLayout) findViewById(R.id.flMain);

ArrayList<Item> itemsList;

//some code

if(itemsList.isEmpty()) {
    fl.addView(tvNoItem);
} else {
    fl.removeView(tvNoItem);
}
</code>```

Now, when I run it and I add some items to the list, the TextView (tvNoItem) is removed indeed. But all I see is a blank list - the list items are not visible. [BTW, the list is working fine. When I remove the TextView from main.xml, I can see all the list items.] Please help.

答:
Before getting views dynamically in layouts reset first that

```<code>LinearLayout lc2 = (LinearLayout) findViewById(R.id.leftcode1);
LinearLayout lc3 = (LinearLayout) findViewById(R.id.lcvalue1);

lc2.removeAllViews();
lc3.removeAllViews();
</code>```

Above lines are worked for me to prevent duplicates dynamically adding textviews in that linear layouts

Body:
I have set up a FrameLayout which has a TextView on top of a ListView. Now, in the MainActivity, after executing some code, I check whether the ListView is empty. If it is, I display the TextView, if not, I remove the TextView.

The code is as follows:

Following is the main.xml file:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/flMain"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/tvAddItem"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Add some subjects"
        android:textSize="20sp" />

    <ListView
        android:id="@+id/ItemsList"
        android:layout_width="match_parent"
        android:layout_height="0dip"
        android:layout_weight="1" />

</FrameLayout>

In the MainActivity class, I do the following:

MainActivity.java

TextView tvNoItem = (TextView) findViewById(R.id.tvAddItem);
ListView subListView = (ListView) findViewById(R.id.itemsList);
FrameLayout fl = (FrameLayout) findViewById(R.id.flMain);

ArrayList<Item> itemsList;

//some code

if(itemsList.isEmpty()) {
    fl.addView(tvNoItem);
} else {
    fl.removeView(tvNoItem);
}

Now, when I run it and I add some items to the list, the TextView (tvNoItem) is removed indeed. But all I see is a blank list - the list items are not visible. [BTW, the list is working fine. When I remove the TextView from main.xml, I can see all the list items.] Please help.

Body:
Before getting views dynamically in layouts reset first that

LinearLayout lc2 = (LinearLayout) findViewById(R.id.leftcode1);
LinearLayout lc3 = (LinearLayout) findViewById(R.id.lcvalue1);

lc2.removeAllViews();
lc3.removeAllViews();

Above lines are worked for me to prevent duplicates dynamically adding textviews in that linear layouts


问:
Find out if a business is currently open in T-SQL
I am storing business opening hours in this table. Businesses can have multiple opening hours in the same day. The closing time can be after midnight of the current day.

```<code>CREATE TABLE [Process].[OpeningHours](
    [openinghoursid] [int] IDENTITY(1,1) NOT NULL,
    [businessid] [int] NOT NULL,
    [daynumber] [int] NOT NULL,
    [opentime] [time](7) NOT NULL,
    [duration] [int] NOT NULL,
    [closetime]  AS (dateadd(minute,[duration],[opentime])
)
</code>```

Sample data in this table includes:

```<code>INSERT [Process].[OpeningHours]
([openinghoursid], [businessid], [daynumber], [opentime], [duration])
VALUES (79, 18, 2, CAST(N'12:00:00' AS Time), 165),
       (80, 18, 2, CAST(N'18:00:00' AS Time), 240),
       (81, 18, 3, CAST(N'12:00:00' AS Time), 165),
       (82, 18, 3, CAST(N'18:00:00' AS Time), 240),
       (83, 18, 4, CAST(N'12:00:00' AS Time), 165),
       (84, 18, 4, CAST(N'18:00:00' AS Time), 240),
       (85, 18, 5, CAST(N'12:00:00' AS Time), 165),
       (86, 18, 5, CAST(N'18:00:00' AS Time), 240),
       (87, 18, 6, CAST(N'12:00:00' AS Time), 165),
       (88, 18, 6, CAST(N'18:00:00' AS Time), 300),
       (89, 18, 7, CAST(N'12:00:00' AS Time), 165),
       (90, 18, 7, CAST(N'18:00:00' AS Time), 600),
       (91, 18, 1, CAST(N'12:00:00' AS Time), 180);
</code>```

Now I want to create a function which returns if a business is currently open or closed.

```<code>CREATE FUNCTION [Process].[ufnIsSpaceOpen](@businessid int)
RETURNS BIT
AS
BEGIN
    DECLARE @currentdatetime DATETIME = GETDATE();
    DECLARE @dayofweek INT = DATEPART(dw,@currentdatetime);
    DECLARE @currentdate DATETIME = CONVERT(DATE, @currentdatetime);
    DECLARE @isopen BIT;

    SELECT @isopen = COUNT(*)
    FROM Process.OpeningHours
    WHERE
    daynumber = @dayofweek
    AND businessid = @businessid
    AND
    (
        @currentdatetime >= @currentdate + CONVERT(DATETIME, opentime)

        AND

        @currentdatetime <=
            CASE
                WHEN closetime < '00:00:00' THEN @currentdate + CONVERT(DATETIME, closetime)
                ELSE DATEADD(DAY,1,@currentdate) + CONVERT(DATETIME, closetime)
            END
    );

    RETURN @isopen;

END;

GO
</code>```

I am using the COUNT() to see if any of the rows matches the condition, if 0 match it means it is closed, if COUNT() is greater than 0 it is open. This works when the closing time is within the same day, however it does not work when the closing time is after midnight or if the current time is after midnight.

Any idea how I can fix it?

EDIT: Thank you for all the responses. Finally I went ahead with @DenisRubashkin's solution. For anyone interested this is the final function I used:

```<code>CREATE FUNCTION [Process].[ufnIsSpaceOpen](@businessid int)
RETURNS BIT
AS
BEGIN

    DECLARE @isopen BIT;
    DECLARE @Date DATETIME = GETDATE();

    SELECT @isopen = COUNT(*)
    FROM
    (
        SELECT (CAST(CAST(@Date AS DATE) AS DATETIME) + CAST(h.opentime AS DATETIME)) AS Opened,
            DATEADD(mi, h.duration, (CAST(CAST(@Date AS DATE) AS DATETIME) + CAST(h.opentime AS DATETIME))) AS Closed
        FROM Process.OpeningHours h
        WHERE h.daynumber = DATEPART(dw, @Date)
        AND businessid = @businessid

        UNION

        SELECT (CAST(DATEADD(day, -1, CAST(@Date AS DATE)) AS DATETIME) + CAST(h.opentime AS DATETIME)) AS Opened,
            DATEADD(mi, h.duration, (CAST(DATEADD(day, -1, CAST(@Date AS DATE)) AS DATETIME) + CAST(h.opentime AS DATETIME))) AS Closed
        FROM Process.OpeningHours h
        WHERE h.daynumber = CASE WHEN DATEPART(dw, @Date) = 1
                                 THEN 7
                                 ELSE DATEPART(dw, @Date) - 1
                                 END
        AND businessid = @businessid
    ) w
    WHERE @Date BETWEEN Opened AND Closed

    RETURN @isopen;

END;
</code>```

答:
Convert a row with day-border crossing interval into pair of rows, and simply check time between. Demo</p>

```<code>with [OpeningHours+] as (
    select oh.[openinghoursid], oh.[businessid], oh.duration, t.*
    from [OpeningHours] oh
    cross apply (
        select [daynumber], [opentime]
           ,case when datediff(minute,[opentime],'23:59:59') + 1 >= [duration]
           then dateadd(minute,[duration],[opentime])
           else cast('23:59:59' as time) end [closetime]
        union all
        select case [daynumber] when 7 then 1 else [daynumber] + 1 end, cast('00:00:00' as time)
         , dateadd(minute,[duration] - (datediff(minute,[opentime],'23:59:59') + 1), cast('00:00:00' as time))
        where datediff(minute,[opentime],'23:59:59') + 1 < [duration]
        )  t
)
select *
from [OpeningHours+]
where [businessid] = 18 and [daynumber] = 1 and cast('00:03:00' as time) between [opentime] and [closetime]
</code>```

Body:
I am storing business opening hours in this table. Businesses can have multiple opening hours in the same day. The closing time can be after midnight of the current day.

CREATE TABLE [Process].[OpeningHours](
    [openinghoursid] [int] IDENTITY(1,1) NOT NULL,
    [businessid] [int] NOT NULL,
    [daynumber] [int] NOT NULL,
    [opentime] [time](7) NOT NULL,
    [duration] [int] NOT NULL,
    [closetime]  AS (dateadd(minute,[duration],[opentime])
)

Sample data in this table includes:

INSERT [Process].[OpeningHours]
([openinghoursid], [businessid], [daynumber], [opentime], [duration])
VALUES (79, 18, 2, CAST(N'12:00:00' AS Time), 165),
       (80, 18, 2, CAST(N'18:00:00' AS Time), 240),
       (81, 18, 3, CAST(N'12:00:00' AS Time), 165),
       (82, 18, 3, CAST(N'18:00:00' AS Time), 240),
       (83, 18, 4, CAST(N'12:00:00' AS Time), 165),
       (84, 18, 4, CAST(N'18:00:00' AS Time), 240),
       (85, 18, 5, CAST(N'12:00:00' AS Time), 165),
       (86, 18, 5, CAST(N'18:00:00' AS Time), 240),
       (87, 18, 6, CAST(N'12:00:00' AS Time), 165),
       (88, 18, 6, CAST(N'18:00:00' AS Time), 300),
       (89, 18, 7, CAST(N'12:00:00' AS Time), 165),
       (90, 18, 7, CAST(N'18:00:00' AS Time), 600),
       (91, 18, 1, CAST(N'12:00:00' AS Time), 180);

Now I want to create a function which returns if a business is currently open or closed.

CREATE FUNCTION [Process].[ufnIsSpaceOpen](@businessid int)
RETURNS BIT
AS
BEGIN
    DECLARE @currentdatetime DATETIME = GETDATE();
    DECLARE @dayofweek INT = DATEPART(dw,@currentdatetime);
    DECLARE @currentdate DATETIME = CONVERT(DATE, @currentdatetime);
    DECLARE @isopen BIT;

    SELECT @isopen = COUNT(*)
    FROM Process.OpeningHours
    WHERE
    daynumber = @dayofweek
    AND businessid = @businessid
    AND
    (
        @currentdatetime >= @currentdate + CONVERT(DATETIME, opentime)

        AND

        @currentdatetime <=
            CASE
                WHEN closetime < '00:00:00' THEN @currentdate + CONVERT(DATETIME, closetime)
                ELSE DATEADD(DAY,1,@currentdate) + CONVERT(DATETIME, closetime)
            END
    );

    RETURN @isopen;

END;

GO

I am using the COUNT() to see if any of the rows matches the condition, if 0 match it means it is closed, if COUNT() is greater than 0 it is open. This works when the closing time is within the same day, however it does not work when the closing time is after midnight or if the current time is after midnight.

Any idea how I can fix it?

EDIT: Thank you for all the responses. Finally I went ahead with @DenisRubashkin's solution. For anyone interested this is the final function I used:

CREATE FUNCTION [Process].[ufnIsSpaceOpen](@businessid int)
RETURNS BIT
AS
BEGIN

    DECLARE @isopen BIT;
    DECLARE @Date DATETIME = GETDATE();

    SELECT @isopen = COUNT(*)
    FROM
    (
        SELECT (CAST(CAST(@Date AS DATE) AS DATETIME) + CAST(h.opentime AS DATETIME)) AS Opened,
            DATEADD(mi, h.duration, (CAST(CAST(@Date AS DATE) AS DATETIME) + CAST(h.opentime AS DATETIME))) AS Closed
        FROM Process.OpeningHours h
        WHERE h.daynumber = DATEPART(dw, @Date)
        AND businessid = @businessid

        UNION

        SELECT (CAST(DATEADD(day, -1, CAST(@Date AS DATE)) AS DATETIME) + CAST(h.opentime AS DATETIME)) AS Opened,
            DATEADD(mi, h.duration, (CAST(DATEADD(day, -1, CAST(@Date AS DATE)) AS DATETIME) + CAST(h.opentime AS DATETIME))) AS Closed
        FROM Process.OpeningHours h
        WHERE h.daynumber = CASE WHEN DATEPART(dw, @Date) = 1
                                 THEN 7
                                 ELSE DATEPART(dw, @Date) - 1
                                 END
        AND businessid = @businessid
    ) w
    WHERE @Date BETWEEN Opened AND Closed

    RETURN @isopen;

END;

Body:
Convert a row with day-border crossing interval into pair of rows, and simply check time between. Demo

with [OpeningHours+] as (
    select oh.[openinghoursid], oh.[businessid], oh.duration, t.*
    from [OpeningHours] oh
    cross apply (
        select [daynumber], [opentime]
           ,case when datediff(minute,[opentime],'23:59:59') + 1 >= [duration]
           then dateadd(minute,[duration],[opentime])
           else cast('23:59:59' as time) end [closetime]
        union all
        select case [daynumber] when 7 then 1 else [daynumber] + 1 end, cast('00:00:00' as time)
         , dateadd(minute,[duration] - (datediff(minute,[opentime],'23:59:59') + 1), cast('00:00:00' as time))
        where datediff(minute,[opentime],'23:59:59') + 1 < [duration]
        )  t
)
select *
from [OpeningHours+]
where [businessid] = 18 and [daynumber] = 1 and cast('00:03:00' as time) between [opentime] and [closetime]


问:
Hibernate n+1 issue
I have these classes:

Orders:

```<code>@Table(name = "ORDERS")
public class Order {

    @Id
    @Column(name = "order_id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "user_id", nullable = false)
    private Long userId;

    @JsonManagedReference
    @OneToMany(mappedBy = "order", fetch = FetchType.EAGER)
    private Set<OrderDetail> orderDetails;

    @JsonManagedReference(value = "order-note")
    @OneToMany(mappedBy = "order", fetch = FetchType.EAGER)
    private Set<Note> notes;

}
</code>```

Details

```<code>@Table(name = "ORDER_DETAILS")
public class OrderDetail {
    @Id
    @Column(name = "order_detail_id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @JsonBackReference
    @ManyToOne
    @JoinColumn(name = "order_id")
    private Order order;

    @JsonManagedReference
    @OneToMany(mappedBy = "orderDetail", fetch = FetchType.EAGER)
    private Set<OrderSize> orderSizes;

    @JsonManagedReference(value="order-detail-note")
    @OneToMany(mappedBy = "orderDetail", fetch = FetchType.EAGER)
    private Set<Note> notes;
}
</code>```

Sizes:

```<code>@Table(name = "ORDER_SIZES")
public class OrderSize {

    @Id
    @Column(name = "order_size_id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @JsonBackReference
    @ManyToOne
    @JoinColumn(name = "order_detail_id")
    private OrderDetail orderDetail;
}
</code>```

Notes

```<code>@Table(name = "NOTES")
public class Note {

    @Id
    @Column(name = "note_id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @JsonBackReference(value="order-note")
    @ManyToOne
    @JoinColumn(name = "order_id", nullable = true)
    private Order order;

    @JsonBackReference(value="order-detail-note")
    @ManyToOne
    @JoinColumn(name = "order_detail_id", nullable = true)
    private OrderDetail orderDetail;
}
</code>```

I want to perform a query (using Hibernate's criteria), and get all the orders with their associated details, sizes and notes.

```<code>public List<Order> findByUser(Long userId) {
    Criteria criteria = createEntityCriteria();
    criteria.add(Restrictions.eq("userId", userId));
    return (List<Order>) criteria.list();
}
</code>```

At the moment Hibernate generates n queries like this:

```<code>Hibernate:
    select
        notes0_.order_detail_id as order_de4_17_0_,
        notes0_.note_id as note_id1_15_0_,
        notes0_.note_id as note_id1_15_1_,
        notes0_.note_text as note_tex2_15_1_,
        notes0_.order_id as order_id3_15_1_,
        notes0_.order_detail_id as order_de4_15_1_,
        order1_.order_id as order_id1_16_2_,
        order1_.client_id as client_i2_16_2_,
        order1_.company_id as company_3_16_2_,
        order1_.delivery_id as delivery4_16_2_,
        order1_.discount as discount5_16_2_,
        order1_.order_date as order_da6_16_2_,
        order1_.order_name as order_na7_16_2_,
        order1_.signature as signatur8_16_2_,
        order1_.order_status as order_st9_16_2_,
        order1_.payment_method_id as payment10_16_2_,
        order1_.user_id as user_id11_16_2_
    from
        NOTES notes0_
    left outer join
        ORDERS order1_
            on notes0_.order_id=order1_.order_id
    where
        notes0_.order_detail_id=?
</code>```

I haven't been able to come up with a solution to get everything I need in just one query.

答:
After inserting:

2 Note entities

2 OrderDetail entities (each containing the 2 Note entities)

1 Order entity (containing the 2 OrderDetail entities, and the 2 Note entities)

Using the following annotations in the Order entity:

```<code>@OneToMany(mappedBy = "order", fetch = FetchType.EAGER)
@Fetch(FetchMode.JOIN)
private Set<OrderDetail> orderDetails = new HashSet<>();

@OneToMany(mappedBy = "order", fetch = FetchType.EAGER)
@Fetch(FetchMode.JOIN)
private Set<Note> notes;
</code>```

Generates the following query:

```<code>Hibernate:
    select
        this_.order_id as order_id1_3_4_,
        this_.user_id as user_id2_3_4_,
        notes2_.order_id as order_id2_0_6_,
        notes2_.note_id as note_id1_0_6_,
        notes2_.note_id as note_id1_0_0_,
        notes2_.order_id as order_id2_0_0_,
        notes2_.order_detail_id as order_de3_0_0_,
        orderdetai3_.order_detail_id as order_de1_1_1_,
        orderdetai3_.order_id as order_id2_1_1_,
        order4_.order_id as order_id1_3_2_,
        order4_.user_id as user_id2_3_2_,
        ordersizes5_.order_detail_id as order_de2_2_7_,
        ordersizes5_.order_size_id as order_si1_2_7_,
        ordersizes5_.order_size_id as order_si1_2_3_,
        ordersizes5_.order_detail_id as order_de2_2_3_
    from
        orders this_
    left outer join
        notes notes2_
            on this_.order_id=notes2_.order_id
    left outer join
        order_details orderdetai3_
            on notes2_.order_detail_id=orderdetai3_.order_detail_id
    left outer join
        orders order4_
            on orderdetai3_.order_id=order4_.order_id
    left outer join
        order_sizes ordersizes5_
            on orderdetai3_.order_detail_id=ordersizes5_.order_detail_id
    where
        this_.user_id=?
Hibernate:
    select
        orderdetai0_.order_id as order_id2_1_0_,
        orderdetai0_.order_detail_id as order_de1_1_0_,
        orderdetai0_.order_detail_id as order_de1_1_1_,
        orderdetai0_.order_id as order_id2_1_1_
    from
        order_details orderdetai0_
    where
        orderdetai0_.order_id=?
</code>```

If however you are still facing difficulties fetching the data as one query, I would suggest using QueryDSL [1], with examples and maven setup details here [2].

LE:

An example of how your query would be created in QueryDSL is:

```<code>public List<Order> findByUserQueryDsl(Long userId) {
    System.out.println("Finding by User ID query dsl");

    EntityManager em = this.entityManagerFactory.createEntityManager();

    return new JPAQuery<>(em, HQLTemplates.DEFAULT)
            .select(QOrder.order)
            .from(QOrder.order)
            .leftJoin(QOrder.order.notes).fetchJoin()
            .leftJoin(QOrder.order.orderDetails, QOrderDetail.orderDetail).fetchJoin()
            .leftJoin(QOrderDetail.orderDetail.notes).fetchJoin()
            .where(QOrder.order.userId.eq(userId))
            .fetch();
}
</code>```

Which would generate the following query:

```<code>select
    order0_.order_id as order_id1_3_0_,
    notes1_.note_id as note_id1_0_1_,
    orderdetai2_.order_detail_id as order_de1_1_2_,
    notes3_.note_id as note_id1_0_3_,
    order0_.user_id as user_id2_3_0_,
    notes1_.order_id as order_id2_0_1_,
    notes1_.order_detail_id as order_de3_0_1_,
    notes1_.order_id as order_id2_0_0__,
    notes1_.note_id as note_id1_0_0__,
    orderdetai2_.order_id as order_id2_1_2_,
    orderdetai2_.order_id as order_id2_1_1__,
    orderdetai2_.order_detail_id as order_de1_1_1__,
    notes3_.order_id as order_id2_0_3_,
    notes3_.order_detail_id as order_de3_0_3_,
    notes3_.order_detail_id as order_de3_0_2__,
    notes3_.note_id as note_id1_0_2__
from
    orders order0_
left outer join
    notes notes1_
        on order0_.order_id=notes1_.order_id
left outer join
    order_details orderdetai2_
        on order0_.order_id=orderdetai2_.order_id
left outer join
    notes notes3_
        on orderdetai2_.order_detail_id=notes3_.order_detail_id
where
    order0_.user_id=?
</code>```

[1] http://www.querydsl.com/

[2] http://www.querydsl.com/static/querydsl/4.1.4/reference/html/ch02s02.html

Title: Hibernate n+1 issue

Body:
I have these classes:

Orders:

@Table(name = "ORDERS")
public class Order {

    @Id
    @Column(name = "order_id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "user_id", nullable = false)
    private Long userId;

    @JsonManagedReference
    @OneToMany(mappedBy = "order", fetch = FetchType.EAGER)
    private Set<OrderDetail> orderDetails;

    @JsonManagedReference(value = "order-note")
    @OneToMany(mappedBy = "order", fetch = FetchType.EAGER)
    private Set<Note> notes;

}

Details

@Table(name = "ORDER_DETAILS")
public class OrderDetail {
    @Id
    @Column(name = "order_detail_id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @JsonBackReference
    @ManyToOne
    @JoinColumn(name = "order_id")
    private Order order;

    @JsonManagedReference
    @OneToMany(mappedBy = "orderDetail", fetch = FetchType.EAGER)
    private Set<OrderSize> orderSizes;

    @JsonManagedReference(value="order-detail-note")
    @OneToMany(mappedBy = "orderDetail", fetch = FetchType.EAGER)
    private Set<Note> notes;
}

Sizes:

@Table(name = "ORDER_SIZES")
public class OrderSize {

    @Id
    @Column(name = "order_size_id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @JsonBackReference
    @ManyToOne
    @JoinColumn(name = "order_detail_id")
    private OrderDetail orderDetail;
}

Notes

@Table(name = "NOTES")
public class Note {

    @Id
    @Column(name = "note_id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @JsonBackReference(value="order-note")
    @ManyToOne
    @JoinColumn(name = "order_id", nullable = true)
    private Order order;

    @JsonBackReference(value="order-detail-note")
    @ManyToOne
    @JoinColumn(name = "order_detail_id", nullable = true)
    private OrderDetail orderDetail;
}

I want to perform a query (using Hibernate's criteria), and get all the orders with their associated details, sizes and notes.

public List<Order> findByUser(Long userId) {
    Criteria criteria = createEntityCriteria();
    criteria.add(Restrictions.eq("userId", userId));
    return (List<Order>) criteria.list();
}

At the moment Hibernate generates n queries like this:

Hibernate:
    select
        notes0_.order_detail_id as order_de4_17_0_,
        notes0_.note_id as note_id1_15_0_,
        notes0_.note_id as note_id1_15_1_,
        notes0_.note_text as note_tex2_15_1_,
        notes0_.order_id as order_id3_15_1_,
        notes0_.order_detail_id as order_de4_15_1_,
        order1_.order_id as order_id1_16_2_,
        order1_.client_id as client_i2_16_2_,
        order1_.company_id as company_3_16_2_,
        order1_.delivery_id as delivery4_16_2_,
        order1_.discount as discount5_16_2_,
        order1_.order_date as order_da6_16_2_,
        order1_.order_name as order_na7_16_2_,
        order1_.signature as signatur8_16_2_,
        order1_.order_status as order_st9_16_2_,
        order1_.payment_method_id as payment10_16_2_,
        order1_.user_id as user_id11_16_2_
    from
        NOTES notes0_
    left outer join
        ORDERS order1_
            on notes0_.order_id=order1_.order_id
    where
        notes0_.order_detail_id=?

I haven't been able to come up with a solution to get everything I need in just one query.

Body:
After inserting:

2 Note entities

2 OrderDetail entities (each containing the 2 Note entities)

1 Order entity (containing the 2 OrderDetail entities, and the 2 Note entities)

Using the following annotations in the Order entity:

@OneToMany(mappedBy = "order", fetch = FetchType.EAGER)
@Fetch(FetchMode.JOIN)
private Set<OrderDetail> orderDetails = new HashSet<>();

@OneToMany(mappedBy = "order", fetch = FetchType.EAGER)
@Fetch(FetchMode.JOIN)
private Set<Note> notes;

Generates the following query:

Hibernate:
    select
        this_.order_id as order_id1_3_4_,
        this_.user_id as user_id2_3_4_,
        notes2_.order_id as order_id2_0_6_,
        notes2_.note_id as note_id1_0_6_,
        notes2_.note_id as note_id1_0_0_,
        notes2_.order_id as order_id2_0_0_,
        notes2_.order_detail_id as order_de3_0_0_,
        orderdetai3_.order_detail_id as order_de1_1_1_,
        orderdetai3_.order_id as order_id2_1_1_,
        order4_.order_id as order_id1_3_2_,
        order4_.user_id as user_id2_3_2_,
        ordersizes5_.order_detail_id as order_de2_2_7_,
        ordersizes5_.order_size_id as order_si1_2_7_,
        ordersizes5_.order_size_id as order_si1_2_3_,
        ordersizes5_.order_detail_id as order_de2_2_3_
    from
        orders this_
    left outer join
        notes notes2_
            on this_.order_id=notes2_.order_id
    left outer join
        order_details orderdetai3_
            on notes2_.order_detail_id=orderdetai3_.order_detail_id
    left outer join
        orders order4_
            on orderdetai3_.order_id=order4_.order_id
    left outer join
        order_sizes ordersizes5_
            on orderdetai3_.order_detail_id=ordersizes5_.order_detail_id
    where
        this_.user_id=?
Hibernate:
    select
        orderdetai0_.order_id as order_id2_1_0_,
        orderdetai0_.order_detail_id as order_de1_1_0_,
        orderdetai0_.order_detail_id as order_de1_1_1_,
        orderdetai0_.order_id as order_id2_1_1_
    from
        order_details orderdetai0_
    where
        orderdetai0_.order_id=?

If however you are still facing difficulties fetching the data as one query, I would suggest using QueryDSL [1], with examples and maven setup details here [2].

LE:

An example of how your query would be created in QueryDSL is:

public List<Order> findByUserQueryDsl(Long userId) {
    System.out.println("Finding by User ID query dsl");

    EntityManager em = this.entityManagerFactory.createEntityManager();

    return new JPAQuery<>(em, HQLTemplates.DEFAULT)
            .select(QOrder.order)
            .from(QOrder.order)
            .leftJoin(QOrder.order.notes).fetchJoin()
            .leftJoin(QOrder.order.orderDetails, QOrderDetail.orderDetail).fetchJoin()
            .leftJoin(QOrderDetail.orderDetail.notes).fetchJoin()
            .where(QOrder.order.userId.eq(userId))
            .fetch();
}

Which would generate the following query:

select
    order0_.order_id as order_id1_3_0_,
    notes1_.note_id as note_id1_0_1_,
    orderdetai2_.order_detail_id as order_de1_1_2_,
    notes3_.note_id as note_id1_0_3_,
    order0_.user_id as user_id2_3_0_,
    notes1_.order_id as order_id2_0_1_,
    notes1_.order_detail_id as order_de3_0_1_,
    notes1_.order_id as order_id2_0_0__,
    notes1_.note_id as note_id1_0_0__,
    orderdetai2_.order_id as order_id2_1_2_,
    orderdetai2_.order_id as order_id2_1_1__,
    orderdetai2_.order_detail_id as order_de1_1_1__,
    notes3_.order_id as order_id2_0_3_,
    notes3_.order_detail_id as order_de3_0_3_,
    notes3_.order_detail_id as order_de3_0_2__,
    notes3_.note_id as note_id1_0_2__
from
    orders order0_
left outer join
    notes notes1_
        on order0_.order_id=notes1_.order_id
left outer join
    order_details orderdetai2_
        on order0_.order_id=orderdetai2_.order_id
left outer join
    notes notes3_
        on orderdetai2_.order_detail_id=notes3_.order_detail_id
where
    order0_.user_id=?

[1] http://www.querydsl.com/

[2] http://www.querydsl.com/static/querydsl/4.1.4/reference/html/ch02s02.html


问:
alfresco and ldap configuration
I am currently configuring alfresco to use ldap server  for authentication.
I followed the offecial documentation and i updated alfresco-global.properties file but it dosen't work.
i am using alfresco 5.2 and this is my alfresco-global.properties file and the ldap hiarchy.

```<code>###############################
## Common Alfresco Properties #
###############################

dir.root=C:/ALFRES~1/alf_data

alfresco.context=alfresco
alfresco.host=127.0.0.1
alfresco.port=8080
alfresco.protocol=http

share.context=share
share.host=127.0.0.1
share.port=8080
share.protocol=http

### database connection properties ###
db.driver=org.postgresql.Driver
db.username=alfresco
db.password=admin
db.name=alfresco
db.url=jdbc:postgresql://localhost:5432/${db.name}
# Note: your database must also be able to accept at least this many connections.  Please see your database documentation for instructions on how to configure this.
db.pool.max=275
db.pool.validate.query=SELECT 1

# The server mode. Set value here
# UNKNOWN | TEST | BACKUP | PRODUCTION
system.serverMode=UNKNOWN

### FTP Server Configuration ###
ftp.port=21

### RMI registry port for JMX ###
alfresco.rmi.services.port=50500

### External executable locations ###
ooo.exe=C:/ALFRES~1/LIBREO~1/App/libreoffice/program/soffice.exe
ooo.enabled=true
ooo.port=8100
img.root=C:\\alfresco-community\\imagemagick
img.coders=${img.root}\\modules\\coders
img.config=${img.root}
img.gslib=${img.root}\\lib
img.exe=${img.root}\\convert.exe

jodconverter.enabled=false
jodconverter.officeHome=C:/ALFRES~1/LIBREO~1/App/libreoffice
jodconverter.portNumbers=8100

### Initial admin password ###
alfresco_user_store.adminpassword=209c6174da490caeb422f3fa5a7ae634

### E-mail site invitation setting ###
notification.email.siteinvite=false

### License location ###
dir.license.external=C:/ALFRES~1

### Solr indexing ###
index.subsystem.name=solr4
dir.keystore=${dir.root}/keystore
solr.host=localhost
solr.port.ssl=8443

### Allow extended ResultSet processing
security.anyDenyDenies=false

### Smart Folders Config Properties ###
smart.folders.enabled=false

### Remote JMX (Default: disabled) ###
alfresco.jmx.connector.enabled=false

### Remote JMX (Default: disabled) ###
alfresco.jmx.connector.enabled=false

authentication.chain=alfinst:alfrescoNtlm,ldap1:ldap

ntlm.authentication.sso.enabled=false

ldap.authentication.allowGuestLogin=false
ldap.authentication.userNameFormat=%s
ldap.authentication.java.naming.provider.url=ldap://localhost:10389
ldap.authentication.defaultAdministratorUserNames=Administrator,alfresco
ldap.synchronization.java.naming.security.principal=admin
ldap.synchronization.java.naming.security.credentials=secret
ldap.synchronization.groupSearchBase=ou=groups,o=mojo
ldap.synchronization.userSearchBase=ou=users,o=mojo
</code>```

My Log

```<code>mars 30, 2017 4:05:46 PM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFOS: Loaded APR based Apache Tomcat Native library 1.1.32 using APR version 1.5.1.
mars 30, 2017 4:05:46 PM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFOS: APR capabilities: IPv6 [true], sendfile [true], accept filters [false], random [true].
mars 30, 2017 4:05:47 PM org.apache.catalina.core.AprLifecycleListener initializeSSL
INFOS: OpenSSL successfully initialized (OpenSSL 1.0.1j 15 Oct 2014)
mars 30, 2017 4:05:47 PM org.apache.coyote.AbstractProtocol init
INFOS: Initializing ProtocolHandler ["http-apr-8080"]
mars 30, 2017 4:05:47 PM org.apache.coyote.AbstractProtocol init
INFOS: Initializing ProtocolHandler ["ajp-apr-8009"]
mars 30, 2017 4:05:47 PM org.apache.coyote.AbstractProtocol init
INFOS: Initializing ProtocolHandler ["http-bio-8443"]
mars 30, 2017 4:05:50 PM org.apache.catalina.startup.Catalina load
INFOS: Initialization processed in 5988 ms
mars 30, 2017 4:05:50 PM org.apache.catalina.core.StandardService startInternal
INFOS: Démarrage du service Catalina
mars 30, 2017 4:05:50 PM org.apache.catalina.core.StandardEngine startInternal
INFOS: Starting Servlet Engine: Apache Tomcat/7.0.x
mars 30, 2017 4:05:50 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFOS: Déploiement du descripteur de configuration C:\alfresco-community\tomcat\conf\Catalina\localhost\alfresco.xml
mars 30, 2017 4:07:38 PM org.apache.catalina.core.StandardContext startInternal
GRAVE: Error listenerStart
mars 30, 2017 4:07:38 PM org.apache.catalina.core.StandardContext startInternal
GRAVE: Erreur de démarrage du contexte [/alfresco] suite aux erreurs précédentes
mars 30, 2017 4:07:38 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFOS: Deployment of configuration descriptor C:\alfresco-community\tomcat\conf\Catalina\localhost\alfresco.xml has finished in 108 389 ms
mars 30, 2017 4:07:38 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFOS: Déploiement du descripteur de configuration C:\alfresco-community\tomcat\conf\Catalina\localhost\share.xml
mars 30, 2017 4:09:05 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFOS: Deployment of configuration descriptor C:\alfresco-community\tomcat\conf\Catalina\localhost\share.xml has finished in 86 895 ms
mars 30, 2017 4:09:05 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFOS: Déploiement du descripteur de configuration C:\alfresco-community\tomcat\conf\Catalina\localhost\solr4.xml
mars 30, 2017 4:09:05 PM org.apache.catalina.startup.SetContextPropertiesRule begin
AVERTISSEMENT: [SetContextPropertiesRule]{Context} Setting property 'debug' to '0' did not find a matching property.
mars 30, 2017 4:09:40 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFOS: Deployment of configuration descriptor C:\alfresco-community\tomcat\conf\Catalina\localhost\solr4.xml has finished in 34 391 ms
mars 30, 2017 4:09:40 PM org.apache.catalina.startup.HostConfig deployWAR
INFOS: Déploiement de l'archive C:\alfresco-community\tomcat\webapps\ROOT.war de l'application web
mars 30, 2017 4:09:40 PM org.apache.catalina.startup.SetContextPropertiesRule begin
AVERTISSEMENT: [SetContextPropertiesRule]{Context} Setting property 'debug' to '100' did not find a matching property.
mars 30, 2017 4:09:40 PM org.apache.catalina.startup.HostConfig deployWAR
INFOS: Deployment of web application archive C:\alfresco-community\tomcat\webapps\ROOT.war has finished in 547 ms
mars 30, 2017 4:09:40 PM org.apache.catalina.startup.HostConfig deployWAR
INFOS: Déploiement de l'archive C:\alfresco-community\tomcat\webapps\_vti_bin.war de l'application web
mars 30, 2017 4:09:41 PM org.apache.catalina.startup.HostConfig deployWAR
INFOS: Deployment of web application archive C:\alfresco-community\tomcat\webapps\_vti_bin.war has finished in 711 ms
mars 30, 2017 4:09:41 PM org.apache.catalina.startup.HostConfig deployDirectory
INFOS: Déploiement du répertoire C:\alfresco-community\tomcat\webapps\host-manager de l'application web
mars 30, 2017 4:09:41 PM org.apache.catalina.startup.HostConfig deployDirectory
INFOS: Deployment of web application directory C:\alfresco-community\tomcat\webapps\host-manager has finished in 285 ms
mars 30, 2017 4:09:41 PM org.apache.catalina.startup.HostConfig deployDirectory
INFOS: Déploiement du répertoire C:\alfresco-community\tomcat\webapps\manager de l'application web
mars 30, 2017 4:09:41 PM org.apache.catalina.startup.HostConfig deployDirectory
INFOS: Deployment of web application directory C:\alfresco-community\tomcat\webapps\manager has finished in 244 ms
mars 30, 2017 4:09:41 PM org.apache.coyote.AbstractProtocol start
INFOS: Starting ProtocolHandler ["http-apr-8080"]
mars 30, 2017 4:09:41 PM org.apache.coyote.AbstractProtocol start
INFOS: Starting ProtocolHandler ["ajp-apr-8009"]
mars 30, 2017 4:09:41 PM org.apache.coyote.AbstractProtocol start
INFOS: Starting ProtocolHandler ["http-bio-8443"]
mars 30, 2017 4:09:41 PM org.apache.catalina.startup.Catalina start
INFOS: Server startup in 231821 ms
mars 30, 2017 4:11:26 PM org.apache.coyote.AbstractProtocol pause
INFOS: Pausing ProtocolHandler ["http-apr-8080"]
mars 30, 2017 4:11:26 PM org.apache.coyote.AbstractProtocol pause
INFOS: Pausing ProtocolHandler ["ajp-apr-8009"]
mars 30, 2017 4:11:26 PM org.apache.coyote.AbstractProtocol pause
INFOS: Pausing ProtocolHandler ["http-bio-8443"]
mars 30, 2017 4:11:26 PM org.apache.catalina.core.StandardService stopInternal
INFOS: Arrêt du service Catalina
mars 30, 2017 4:11:57 PM org.apache.coyote.AbstractProtocol stop
INFOS: Stopping ProtocolHandler ["http-apr-8080"]
mars 30, 2017 4:11:57 PM org.apache.coyote.AbstractProtocol stop
INFOS: Stopping ProtocolHandler ["ajp-apr-8009"]
mars 30, 2017 4:11:57 PM org.apache.coyote.AbstractProtocol stop
INFOS: Stopping ProtocolHandler ["http-bio-8443"]
mars 30, 2017 4:12:34 PM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFOS: Loaded APR based Apache Tomcat Native library 1.1.32 using APR version 1.5.1.
mars 30, 2017 4:12:34 PM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFOS: APR capabilities: IPv6 [true], sendfile [true], accept filters [false], random [true].
mars 30, 2017 4:12:35 PM org.apache.catalina.core.AprLifecycleListener initializeSSL
INFOS: OpenSSL successfully initialized (OpenSSL 1.0.1j 15 Oct 2014)
mars 30, 2017 4:12:35 PM org.apache.coyote.AbstractProtocol init
INFOS: Initializing ProtocolHandler ["http-apr-8080"]
mars 30, 2017 4:12:35 PM org.apache.coyote.AbstractProtocol init
INFOS: Initializing ProtocolHandler ["ajp-apr-8009"]
mars 30, 2017 4:12:35 PM org.apache.coyote.AbstractProtocol init
INFOS: Initializing ProtocolHandler ["http-bio-8443"]
mars 30, 2017 4:12:37 PM org.apache.catalina.startup.Catalina load
INFOS: Initialization processed in 4101 ms
mars 30, 2017 4:12:37 PM org.apache.catalina.core.StandardService startInternal
INFOS: Démarrage du service Catalina
mars 30, 2017 4:12:37 PM org.apache.catalina.core.StandardEngine startInternal
INFOS: Starting Servlet Engine: Apache Tomcat/7.0.x
mars 30, 2017 4:12:37 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFOS: Déploiement du descripteur de configuration C:\alfresco-community\tomcat\conf\Catalina\localhost\alfresco.xml
mars 30, 2017 4:15:22 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFOS: Deployment of configuration descriptor C:\alfresco-community\tomcat\conf\Catalina\localhost\alfresco.xml has finished in 164 795 ms
mars 30, 2017 4:15:22 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFOS: Déploiement du descripteur de configuration C:\alfresco-community\tomcat\conf\Catalina\localhost\share.xml
mars 30, 2017 4:15:56 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFOS: Deployment of configuration descriptor C:\alfresco-community\tomcat\conf\Catalina\localhost\share.xml has finished in 34 374 ms
mars 30, 2017 4:15:56 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFOS: Déploiement du descripteur de configuration C:\alfresco-community\tomcat\conf\Catalina\localhost\solr4.xml
mars 30, 2017 4:15:56 PM org.apache.catalina.startup.SetContextPropertiesRule begin
AVERTISSEMENT: [SetContextPropertiesRule]{Context} Setting property 'debug' to '0' did not find a matching property.
mars 30, 2017 4:16:25 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFOS: Deployment of configuration descriptor C:\alfresco-community\tomcat\conf\Catalina\localhost\solr4.xml has finished in 28 614 ms
mars 30, 2017 4:16:25 PM org.apache.catalina.startup.HostConfig deployWAR
INFOS: Déploiement de l'archive C:\alfresco-community\tomcat\webapps\ROOT.war de l'application web
mars 30, 2017 4:16:25 PM org.apache.catalina.startup.SetContextPropertiesRule begin
AVERTISSEMENT: [SetContextPropertiesRule]{Context} Setting property 'debug' to '100' did not find a matching property.
mars 30, 2017 4:16:25 PM org.apache.catalina.startup.HostConfig deployWAR
INFOS: Deployment of web application archive C:\alfresco-community\tomcat\webapps\ROOT.war has finished in 479 ms
mars 30, 2017 4:16:25 PM org.apache.catalina.startup.HostConfig deployWAR
INFOS: Déploiement de l'archive C:\alfresco-community\tomcat\webapps\_vti_bin.war de l'application web
mars 30, 2017 4:16:26 PM org.apache.catalina.startup.HostConfig deployWAR
INFOS: Deployment of web application archive C:\alfresco-community\tomcat\webapps\_vti_bin.war has finished in 619 ms
mars 30, 2017 4:16:26 PM org.apache.catalina.startup.HostConfig deployDirectory
INFOS: Déploiement du répertoire C:\alfresco-community\tomcat\webapps\host-manager de l'application web
mars 30, 2017 4:16:26 PM org.apache.catalina.startup.HostConfig deployDirectory
INFOS: Deployment of web application directory C:\alfresco-community\tomcat\webapps\host-manager has finished in 337 ms
mars 30, 2017 4:16:26 PM org.apache.catalina.startup.HostConfig deployDirectory
INFOS: Déploiement du répertoire C:\alfresco-community\tomcat\webapps\manager de l'application web
mars 30, 2017 4:16:27 PM org.apache.catalina.startup.HostConfig deployDirectory
INFOS: Deployment of web application directory C:\alfresco-community\tomcat\webapps\manager has finished in 260 ms
mars 30, 2017 4:16:27 PM org.apache.coyote.AbstractProtocol start
INFOS: Starting ProtocolHandler ["http-apr-8080"]
mars 30, 2017 4:16:27 PM org.apache.coyote.AbstractProtocol start
INFOS: Starting ProtocolHandler ["ajp-apr-8009"]
mars 30, 2017 4:16:27 PM org.apache.coyote.AbstractProtocol start
INFOS: Starting ProtocolHandler ["http-bio-8443"]
mars 30, 2017 4:16:27 PM org.apache.catalina.startup.Catalina start
INFOS: Server startup in 229832 ms
</code>```

答: Take a look at this, you need to create ldap properties file inside this path tomcat/shared/classes/alfresco/extension/subsystems/Authentication/ldap/ldap1

Title: alfresco and ldap configuration

Body:
I am currently configuring alfresco to use ldap server  for authentication.
I followed the offecial documentation and i updated alfresco-global.properties file but it dosen't work.
i am using alfresco 5.2 and this is my alfresco-global.properties file and the ldap hiarchy.

###############################
## Common Alfresco Properties #
###############################

dir.root=C:/ALFRES~1/alf_data

alfresco.context=alfresco
alfresco.host=127.0.0.1
alfresco.port=8080
alfresco.protocol=http

share.context=share
share.host=127.0.0.1
share.port=8080
share.protocol=http

### database connection properties ###
db.driver=org.postgresql.Driver
db.username=alfresco
db.password=admin
db.name=alfresco
db.url=jdbc:postgresql://localhost:5432/${db.name}
# Note: your database must also be able to accept at least this many connections.  Please see your database documentation for instructions on how to configure this.
db.pool.max=275
db.pool.validate.query=SELECT 1

# The server mode. Set value here
# UNKNOWN | TEST | BACKUP | PRODUCTION
system.serverMode=UNKNOWN

### FTP Server Configuration ###
ftp.port=21

### RMI registry port for JMX ###
alfresco.rmi.services.port=50500

### External executable locations ###
ooo.exe=C:/ALFRES~1/LIBREO~1/App/libreoffice/program/soffice.exe
ooo.enabled=true
ooo.port=8100
img.root=C:\\alfresco-community\\imagemagick
img.coders=${img.root}\\modules\\coders
img.config=${img.root}
img.gslib=${img.root}\\lib
img.exe=${img.root}\\convert.exe

jodconverter.enabled=false
jodconverter.officeHome=C:/ALFRES~1/LIBREO~1/App/libreoffice
jodconverter.portNumbers=8100

### Initial admin password ###
alfresco_user_store.adminpassword=209c6174da490caeb422f3fa5a7ae634

### E-mail site invitation setting ###
notification.email.siteinvite=false

### License location ###
dir.license.external=C:/ALFRES~1

### Solr indexing ###
index.subsystem.name=solr4
dir.keystore=${dir.root}/keystore
solr.host=localhost
solr.port.ssl=8443

### Allow extended ResultSet processing
security.anyDenyDenies=false

### Smart Folders Config Properties ###
smart.folders.enabled=false

### Remote JMX (Default: disabled) ###
alfresco.jmx.connector.enabled=false

### Remote JMX (Default: disabled) ###
alfresco.jmx.connector.enabled=false

authentication.chain=alfinst:alfrescoNtlm,ldap1:ldap

ntlm.authentication.sso.enabled=false

ldap.authentication.allowGuestLogin=false
ldap.authentication.userNameFormat=%s
ldap.authentication.java.naming.provider.url=ldap://localhost:10389
ldap.authentication.defaultAdministratorUserNames=Administrator,alfresco
ldap.synchronization.java.naming.security.principal=admin
ldap.synchronization.java.naming.security.credentials=secret
ldap.synchronization.groupSearchBase=ou=groups,o=mojo
ldap.synchronization.userSearchBase=ou=users,o=mojo

My Log

mars 30, 2017 4:05:46 PM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFOS: Loaded APR based Apache Tomcat Native library 1.1.32 using APR version 1.5.1.
mars 30, 2017 4:05:46 PM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFOS: APR capabilities: IPv6 [true], sendfile [true], accept filters [false], random [true].
mars 30, 2017 4:05:47 PM org.apache.catalina.core.AprLifecycleListener initializeSSL
INFOS: OpenSSL successfully initialized (OpenSSL 1.0.1j 15 Oct 2014)
mars 30, 2017 4:05:47 PM org.apache.coyote.AbstractProtocol init
INFOS: Initializing ProtocolHandler ["http-apr-8080"]
mars 30, 2017 4:05:47 PM org.apache.coyote.AbstractProtocol init
INFOS: Initializing ProtocolHandler ["ajp-apr-8009"]
mars 30, 2017 4:05:47 PM org.apache.coyote.AbstractProtocol init
INFOS: Initializing ProtocolHandler ["http-bio-8443"]
mars 30, 2017 4:05:50 PM org.apache.catalina.startup.Catalina load
INFOS: Initialization processed in 5988 ms
mars 30, 2017 4:05:50 PM org.apache.catalina.core.StandardService startInternal
INFOS: Démarrage du service Catalina
mars 30, 2017 4:05:50 PM org.apache.catalina.core.StandardEngine startInternal
INFOS: Starting Servlet Engine: Apache Tomcat/7.0.x
mars 30, 2017 4:05:50 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFOS: Déploiement du descripteur de configuration C:\alfresco-community\tomcat\conf\Catalina\localhost\alfresco.xml
mars 30, 2017 4:07:38 PM org.apache.catalina.core.StandardContext startInternal
GRAVE: Error listenerStart
mars 30, 2017 4:07:38 PM org.apache.catalina.core.StandardContext startInternal
GRAVE: Erreur de démarrage du contexte [/alfresco] suite aux erreurs précédentes
mars 30, 2017 4:07:38 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFOS: Deployment of configuration descriptor C:\alfresco-community\tomcat\conf\Catalina\localhost\alfresco.xml has finished in 108 389 ms
mars 30, 2017 4:07:38 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFOS: Déploiement du descripteur de configuration C:\alfresco-community\tomcat\conf\Catalina\localhost\share.xml
mars 30, 2017 4:09:05 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFOS: Deployment of configuration descriptor C:\alfresco-community\tomcat\conf\Catalina\localhost\share.xml has finished in 86 895 ms
mars 30, 2017 4:09:05 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFOS: Déploiement du descripteur de configuration C:\alfresco-community\tomcat\conf\Catalina\localhost\solr4.xml
mars 30, 2017 4:09:05 PM org.apache.catalina.startup.SetContextPropertiesRule begin
AVERTISSEMENT: [SetContextPropertiesRule]{Context} Setting property 'debug' to '0' did not find a matching property.
mars 30, 2017 4:09:40 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFOS: Deployment of configuration descriptor C:\alfresco-community\tomcat\conf\Catalina\localhost\solr4.xml has finished in 34 391 ms
mars 30, 2017 4:09:40 PM org.apache.catalina.startup.HostConfig deployWAR
INFOS: Déploiement de l'archive C:\alfresco-community\tomcat\webapps\ROOT.war de l'application web
mars 30, 2017 4:09:40 PM org.apache.catalina.startup.SetContextPropertiesRule begin
AVERTISSEMENT: [SetContextPropertiesRule]{Context} Setting property 'debug' to '100' did not find a matching property.
mars 30, 2017 4:09:40 PM org.apache.catalina.startup.HostConfig deployWAR
INFOS: Deployment of web application archive C:\alfresco-community\tomcat\webapps\ROOT.war has finished in 547 ms
mars 30, 2017 4:09:40 PM org.apache.catalina.startup.HostConfig deployWAR
INFOS: Déploiement de l'archive C:\alfresco-community\tomcat\webapps\_vti_bin.war de l'application web
mars 30, 2017 4:09:41 PM org.apache.catalina.startup.HostConfig deployWAR
INFOS: Deployment of web application archive C:\alfresco-community\tomcat\webapps\_vti_bin.war has finished in 711 ms
mars 30, 2017 4:09:41 PM org.apache.catalina.startup.HostConfig deployDirectory
INFOS: Déploiement du répertoire C:\alfresco-community\tomcat\webapps\host-manager de l'application web
mars 30, 2017 4:09:41 PM org.apache.catalina.startup.HostConfig deployDirectory
INFOS: Deployment of web application directory C:\alfresco-community\tomcat\webapps\host-manager has finished in 285 ms
mars 30, 2017 4:09:41 PM org.apache.catalina.startup.HostConfig deployDirectory
INFOS: Déploiement du répertoire C:\alfresco-community\tomcat\webapps\manager de l'application web
mars 30, 2017 4:09:41 PM org.apache.catalina.startup.HostConfig deployDirectory
INFOS: Deployment of web application directory C:\alfresco-community\tomcat\webapps\manager has finished in 244 ms
mars 30, 2017 4:09:41 PM org.apache.coyote.AbstractProtocol start
INFOS: Starting ProtocolHandler ["http-apr-8080"]
mars 30, 2017 4:09:41 PM org.apache.coyote.AbstractProtocol start
INFOS: Starting ProtocolHandler ["ajp-apr-8009"]
mars 30, 2017 4:09:41 PM org.apache.coyote.AbstractProtocol start
INFOS: Starting ProtocolHandler ["http-bio-8443"]
mars 30, 2017 4:09:41 PM org.apache.catalina.startup.Catalina start
INFOS: Server startup in 231821 ms
mars 30, 2017 4:11:26 PM org.apache.coyote.AbstractProtocol pause
INFOS: Pausing ProtocolHandler ["http-apr-8080"]
mars 30, 2017 4:11:26 PM org.apache.coyote.AbstractProtocol pause
INFOS: Pausing ProtocolHandler ["ajp-apr-8009"]
mars 30, 2017 4:11:26 PM org.apache.coyote.AbstractProtocol pause
INFOS: Pausing ProtocolHandler ["http-bio-8443"]
mars 30, 2017 4:11:26 PM org.apache.catalina.core.StandardService stopInternal
INFOS: Arrêt du service Catalina
mars 30, 2017 4:11:57 PM org.apache.coyote.AbstractProtocol stop
INFOS: Stopping ProtocolHandler ["http-apr-8080"]
mars 30, 2017 4:11:57 PM org.apache.coyote.AbstractProtocol stop
INFOS: Stopping ProtocolHandler ["ajp-apr-8009"]
mars 30, 2017 4:11:57 PM org.apache.coyote.AbstractProtocol stop
INFOS: Stopping ProtocolHandler ["http-bio-8443"]
mars 30, 2017 4:12:34 PM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFOS: Loaded APR based Apache Tomcat Native library 1.1.32 using APR version 1.5.1.
mars 30, 2017 4:12:34 PM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFOS: APR capabilities: IPv6 [true], sendfile [true], accept filters [false], random [true].
mars 30, 2017 4:12:35 PM org.apache.catalina.core.AprLifecycleListener initializeSSL
INFOS: OpenSSL successfully initialized (OpenSSL 1.0.1j 15 Oct 2014)
mars 30, 2017 4:12:35 PM org.apache.coyote.AbstractProtocol init
INFOS: Initializing ProtocolHandler ["http-apr-8080"]
mars 30, 2017 4:12:35 PM org.apache.coyote.AbstractProtocol init
INFOS: Initializing ProtocolHandler ["ajp-apr-8009"]
mars 30, 2017 4:12:35 PM org.apache.coyote.AbstractProtocol init
INFOS: Initializing ProtocolHandler ["http-bio-8443"]
mars 30, 2017 4:12:37 PM org.apache.catalina.startup.Catalina load
INFOS: Initialization processed in 4101 ms
mars 30, 2017 4:12:37 PM org.apache.catalina.core.StandardService startInternal
INFOS: Démarrage du service Catalina
mars 30, 2017 4:12:37 PM org.apache.catalina.core.StandardEngine startInternal
INFOS: Starting Servlet Engine: Apache Tomcat/7.0.x
mars 30, 2017 4:12:37 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFOS: Déploiement du descripteur de configuration C:\alfresco-community\tomcat\conf\Catalina\localhost\alfresco.xml
mars 30, 2017 4:15:22 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFOS: Deployment of configuration descriptor C:\alfresco-community\tomcat\conf\Catalina\localhost\alfresco.xml has finished in 164 795 ms
mars 30, 2017 4:15:22 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFOS: Déploiement du descripteur de configuration C:\alfresco-community\tomcat\conf\Catalina\localhost\share.xml
mars 30, 2017 4:15:56 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFOS: Deployment of configuration descriptor C:\alfresco-community\tomcat\conf\Catalina\localhost\share.xml has finished in 34 374 ms
mars 30, 2017 4:15:56 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFOS: Déploiement du descripteur de configuration C:\alfresco-community\tomcat\conf\Catalina\localhost\solr4.xml
mars 30, 2017 4:15:56 PM org.apache.catalina.startup.SetContextPropertiesRule begin
AVERTISSEMENT: [SetContextPropertiesRule]{Context} Setting property 'debug' to '0' did not find a matching property.
mars 30, 2017 4:16:25 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFOS: Deployment of configuration descriptor C:\alfresco-community\tomcat\conf\Catalina\localhost\solr4.xml has finished in 28 614 ms
mars 30, 2017 4:16:25 PM org.apache.catalina.startup.HostConfig deployWAR
INFOS: Déploiement de l'archive C:\alfresco-community\tomcat\webapps\ROOT.war de l'application web
mars 30, 2017 4:16:25 PM org.apache.catalina.startup.SetContextPropertiesRule begin
AVERTISSEMENT: [SetContextPropertiesRule]{Context} Setting property 'debug' to '100' did not find a matching property.
mars 30, 2017 4:16:25 PM org.apache.catalina.startup.HostConfig deployWAR
INFOS: Deployment of web application archive C:\alfresco-community\tomcat\webapps\ROOT.war has finished in 479 ms
mars 30, 2017 4:16:25 PM org.apache.catalina.startup.HostConfig deployWAR
INFOS: Déploiement de l'archive C:\alfresco-community\tomcat\webapps\_vti_bin.war de l'application web
mars 30, 2017 4:16:26 PM org.apache.catalina.startup.HostConfig deployWAR
INFOS: Deployment of web application archive C:\alfresco-community\tomcat\webapps\_vti_bin.war has finished in 619 ms
mars 30, 2017 4:16:26 PM org.apache.catalina.startup.HostConfig deployDirectory
INFOS: Déploiement du répertoire C:\alfresco-community\tomcat\webapps\host-manager de l'application web
mars 30, 2017 4:16:26 PM org.apache.catalina.startup.HostConfig deployDirectory
INFOS: Deployment of web application directory C:\alfresco-community\tomcat\webapps\host-manager has finished in 337 ms
mars 30, 2017 4:16:26 PM org.apache.catalina.startup.HostConfig deployDirectory
INFOS: Déploiement du répertoire C:\alfresco-community\tomcat\webapps\manager de l'application web
mars 30, 2017 4:16:27 PM org.apache.catalina.startup.HostConfig deployDirectory
INFOS: Deployment of web application directory C:\alfresco-community\tomcat\webapps\manager has finished in 260 ms
mars 30, 2017 4:16:27 PM org.apache.coyote.AbstractProtocol start
INFOS: Starting ProtocolHandler ["http-apr-8080"]
mars 30, 2017 4:16:27 PM org.apache.coyote.AbstractProtocol start
INFOS: Starting ProtocolHandler ["ajp-apr-8009"]
mars 30, 2017 4:16:27 PM org.apache.coyote.AbstractProtocol start
INFOS: Starting ProtocolHandler ["http-bio-8443"]
mars 30, 2017 4:16:27 PM org.apache.catalina.startup.Catalina start
INFOS: Server startup in 229832 ms


答:
Declare as global variable .And adding prompt before if condition .And the number was an a string output.use parseInt() to convert as a integer.
if you need a float use with parseFloat()

console.log("Calculator program");
console.log("1. Add numbers");
console.log("2. Subtract numbers");
console.log("3. Multiply numbers");
console.log("4. Divide numbers");
var number1=0;
var number2=0
var choice =0;
choice = parseInt(prompt ("What is your choice?"));

number1 = parseInt(prompt("Type in a number"));
number2 = parseInt(prompt("Type in another number"));
if (choice == 1)
{
  console.log(number1 + number2);
}
if (choice == 2)
{
  console.log(number1 - number2);
}
if (choice == 3)
{
  console.log(number1 * number2);
}
if (choice == 4)
{
  console.log(number1 / number2);
}```

Title: JavaScript unexpected NaN?


问:
LaplacesDemon: when should I sum prior density?
I am migrating from JAGS to LaplacesDemon and trying to rewrite some of my codes. I have read the LaplacesDemon Tutorial and LaplacesDemon Examples vignettes and am a bit confused about some of examples in the vignettes.

In the simple example in LaplacesDemon Tutorial (p.5), the model is written as:

```<code>Model <- function(parm, Data)
{beta <- parm[Data$pos.beta]
 sigma <- interval(parm[Data$pos.sigma], 1e-100, Inf)
 parm[Data$pos.sigma] <- sigma
 beta.prior <- dnormv(beta, 0, 1000, log=TRUE)
 sigma.prior <- dhalfcauchy(sigma, 25, log=TRUE)
 mu <- tcrossprod(beta, Data$X)
 LL <- sum(dnorm(Data$y, mu, sigma, log=TRUE))
 LP <- LL + sum(beta.prior) + sigma.prior
 Modelout <- list(LP=LP, Dev=-2*LL, Monitor=LP,
 yhat=rnorm(length(mu), mu, sigma), parm=parm)
 return(Modelout)}
</code>```

Here, the beta.prior was summed up for LP as there are more than one beta parameters.

But I found in the more advanced examples in the LaplacesDemon Example vignette, it doesn't seem to always follow the rule. Such as in example 87 (p.162):

```<code>Model <- function(parm, Data)
{### Log-Prior
 beta.prior <- sum(dnormv(beta[,1], 0, 1000, log=TRUE), dnorm(beta[,-1], beta[,-Data$T], matrix(tau, Data$K, Data$T-1), log=TRUE))
 zeta.prior <- dmvn(zeta, rep(0,Data$S), Sigma[ , , 1], log=TRUE)
 phi.prior <- sum(dhalfnorm(phi[1], sqrt(1000), log=TRUE), dtrunc(phi[-1], "norm", a=0, b=Inf, mean=phi[-Data$T], sd=sigma[2], log=TRUE))
 ### Log-Posterior
 LP <- LL + beta.prior + zeta.prior + sum(phi.prior) + sum(kappa.prior) + sum(lambda.prior) + sigma.prior + tau.prior
 Modelout <- list(LP=LP, Dev=-2*LL, Monitor=LP, yhat=rnorm(prod(dim(mu)), mu, sigma[1]), parm=parm)
 return(Modelout)}
</code>```

(Put only part of the codes owing to the length of the example codes)

Here, zeta is more than one but wasn't summed in either the Log-Prior or Log-Posterior part, beta is more than one and was summed in Log-Prior and phi is also more than one parameters but it was summed in both Log-Prior and Log-Posterior parts.

And in the next example on p.167, it seems to be different again.

I was wondering in what scenario we should sum the prior density? Many thanks!

答: Have you tried running the code line by line? You would learn that there is nothing to sum since dmvn is the density function of multivariate normal distribution and it returns a single value -- probability density of observing vector zeta. The reason for all the sums is that to obtain probability of observing two independent events together we multiply their marginal probabilities (or sum their logs). So we multiply the probabilities of observing all the priors together to obtain their joint distribution.

OwnerDisplayName: CYH

Body:
I am migrating from JAGS to LaplacesDemon and trying to rewrite some of my codes. I have read the LaplacesDemon Tutorial and LaplacesDemon Examples vignettes and am a bit confused about some of examples in the vignettes.

In the simple example in LaplacesDemon Tutorial (p.5), the model is written as:

Model <- function(parm, Data)
{beta <- parm[Data$pos.beta]
 sigma <- interval(parm[Data$pos.sigma], 1e-100, Inf)
 parm[Data$pos.sigma] <- sigma
 beta.prior <- dnormv(beta, 0, 1000, log=TRUE)
 sigma.prior <- dhalfcauchy(sigma, 25, log=TRUE)
 mu <- tcrossprod(beta, Data$X)
 LL <- sum(dnorm(Data$y, mu, sigma, log=TRUE))
 LP <- LL + sum(beta.prior) + sigma.prior
 Modelout <- list(LP=LP, Dev=-2*LL, Monitor=LP,
 yhat=rnorm(length(mu), mu, sigma), parm=parm)
 return(Modelout)}

Here, the beta.prior was summed up for LP as there are more than one beta parameters.

But I found in the more advanced examples in the LaplacesDemon Example vignette, it doesn't seem to always follow the rule. Such as in example 87 (p.162):

Model <- function(parm, Data)
{### Log-Prior
 beta.prior <- sum(dnormv(beta[,1], 0, 1000, log=TRUE), dnorm(beta[,-1], beta[,-Data$T], matrix(tau, Data$K, Data$T-1), log=TRUE))
 zeta.prior <- dmvn(zeta, rep(0,Data$S), Sigma[ , , 1], log=TRUE)
 phi.prior <- sum(dhalfnorm(phi[1], sqrt(1000), log=TRUE), dtrunc(phi[-1], "norm", a=0, b=Inf, mean=phi[-Data$T], sd=sigma[2], log=TRUE))
 ### Log-Posterior
 LP <- LL + beta.prior + zeta.prior + sum(phi.prior) + sum(kappa.prior) + sum(lambda.prior) + sigma.prior + tau.prior
 Modelout <- list(LP=LP, Dev=-2*LL, Monitor=LP, yhat=rnorm(prod(dim(mu)), mu, sigma[1]), parm=parm)
 return(Modelout)}

(Put only part of the codes owing to the length of the example codes)

Here, zeta is more than one but wasn't summed in either the Log-Prior or Log-Posterior part, beta is more than one and was summed in Log-Prior and phi is also more than one parameters but it was summed in both Log-Prior and Log-Posterior parts.

And in the next example on p.167, it seems to be different again.

I was wondering in what scenario we should sum the prior density? Many thanks!

OwnerDisplayName: Tim


问:
How to get Xpath for the following?
I have a xml file like following

```<code><topic>
    <title>Abstract
    </title>
    <body>
        <p>
            abstract data
        </p>
    </body>
</topic>
<topic>
    <title>Keywords</title>
    <body>
        <p>
            keywords data
        </p>
    </body>
</topic>
</code>```

I have to check if title is "Keywords" than show the
text in
.
can anyone help me to get the exact xpath for this?
Thanks in advance

答:
```<code>//title[text()="Keywords"]/body/p
</code>```

for text only

```<code>//title[text()="Keywords"]/body/p/text()
</code>```

please avoid double slash "//" and following, it will  travel all the P tag

Title: How to get Xpath for the following?

Body:
I have a xml file like following

<topic>
    <title>Abstract
    </title>

            abstract data

</topic>
<topic>
    <title>Keywords</title>

            keywords data

</topic>

I have to check if title is "Keywords" than show the
text in
.
can anyone help me to get the exact xpath for this?
Thanks in advance

Body:
//title[text()="Keywords"]/body/p

for text only

//title[text()="Keywords"]/body/p/text()

please avoid double slash "//" and following, it will  travel all the P tag


问:
Issue with description from php to csv
I use php to generate a csv file like this:

```<code><?php
function myfunction() {
    header('Content-Encoding: UTF-8');
    header('Content-Type: text/csv; charset=UTF-8');
    header('Content-Disposition: attachment; filename=filename.csv');

    $output = fopen('php://output', 'w');
    fputs( $output, "\xEF\xBB\xBF" );

    foreach (rows as $row) {
      $description=$this->FixDescription($row['Description']);
      $id = $row['id'];
      $myrow .= $id . ',' . $description ."\n";
}

      fputcsv($output, mb_convert_encoding($myrow, 'UCS-2LE', 'UTF-8'));
      fclose($output);
}
   public function FixDescription($descr){
    $d = html_entity_decode($descr, ENT_QUOTES, 'UTF-8');
    $d = htmlspecialchars_decode($d);
    $d = str_replace(' ', ' ', $d);
    $d = strip_tags($d);
    $d = str_replace('&','_',$d);
    return $d;
  }
?>
</code>```

When i download the generated file i get some rows correctly but for some rows description breaks and leaves blank rows and then prints and generally create a mess in my csv file. Any ideas of how not to break the content inside description field?

答:
You should replace

```<code>$myrow .= $id . ',' . $description ."\n";
</code>```

with

```<code>fputcsv($output, array($id,$description);
</code>```

You wouldn't need these lines anymore

```<code>fputs( $output, "\xEF\xBB\xBF" );
fputcsv($output, mb_convert_encoding($myrow, 'UCS-2LE', 'UTF-8'));
</code>```

Title: Issue with description from php to csv

Body:
I use php to generate a csv file like this:

<?php
function myfunction() {
    header('Content-Encoding: UTF-8');
    header('Content-Type: text/csv; charset=UTF-8');
    header('Content-Disposition: attachment; filename=filename.csv');

    $output = fopen('php://output', 'w');
    fputs( $output, "\xEF\xBB\xBF" );

    foreach (rows as $row) {
      $description=$this->FixDescription($row['Description']);
      $id = $row['id'];
      $myrow .= $id . ',' . $description ."\n";
}

      fputcsv($output, mb_convert_encoding($myrow, 'UCS-2LE', 'UTF-8'));
      fclose($output);
}
   public function FixDescription($descr){
    $d = html_entity_decode($descr, ENT_QUOTES, 'UTF-8');
    $d = htmlspecialchars_decode($d);
    $d = str_replace(' ', ' ', $d);
    $d = strip_tags($d);
    $d = str_replace('&','_',$d);
    return $d;
  }
?>

When i download the generated file i get some rows correctly but for some rows description breaks and leaves blank rows and then prints and generally create a mess in my csv file. Any ideas of how not to break the content inside description field?

Body:
You should replace

$myrow .= $id . ',' . $description ."\n";

with

fputcsv($output, array($id,$description);

You wouldn't need these lines anymore

fputs( $output, "\xEF\xBB\xBF" );
fputcsv($output, mb_convert_encoding($myrow, 'UCS-2LE', 'UTF-8'));


问:
C# DateTimePicker DataBinding Parse event not working
I have a datetimepicker that I am binding with nullable Date/Time column in dataset. I applied Format event successfully for null and not null object value. But, when I uncheck dtp control it does not get set to null in the dataset.
This is my code:

```<code>dtpBirthdate.DataBindings.Add(new Binding("Value", bsStaff, "birthDate", true));
dtpBirthdate.DataBindings["Value"].Format += new ConvertEventHandler(dtpFormat);
dtpBirthdate.DataBindings["Value"].Parse += new ConvertEventHandler(dtpParse);
</code>```

Format and Parse events:

```<code>private void dtpFormat(object sender, ConvertEventArgs e)
{
      Binding b = sender as Binding;
      if(b != null)
      {
           DateTimePicker dtp = (b.Control as DateTimePicker);
           if(dtp != null)
           {
                if (e.Value == null || e.Value == DBNull.Value)
                {
                    dtp.Checked = false;
                    dtp.CustomFormat = " ";
                    e.Value = false;
                }
                else
                {
                    dtp.Checked = true;
                    dtp.CustomFormat = "dd-MMM-yyyy";
                    dtp.Value = (DateTime) e.Value;
                }
            }
        }
    }

    private void dtpParse(object sender, ConvertEventArgs e)
    {
        Binding b = sender as Binding;

        if (b != null)
        {
            DateTimePicker dtp = (b.Control as DateTimePicker);
            if (dtp != null)
            {
                if (dtp.Checked == false)
                {
                    e.Value = DBNull.Value;
                }
                else
                {
                    e.Value = dtp.Value;
                }
            }
        }
   }
</code>```

After debugging, I found that it goes to infinite loop between parse and format events. What is wrong with my code?

Edit: There is also a datagridview binded to bsStaff bindingsource.

答: You are casting "Binding b = sender as Binding" before the null check. check if the sender is null before casting and you should be fine.</p>

Body:
I have a datetimepicker that I am binding with nullable Date/Time column in dataset. I applied Format event successfully for null and not null object value. But, when I uncheck dtp control it does not get set to null in the dataset.
This is my code:

dtpBirthdate.DataBindings.Add(new Binding("Value", bsStaff, "birthDate", true));
dtpBirthdate.DataBindings["Value"].Format += new ConvertEventHandler(dtpFormat);
dtpBirthdate.DataBindings["Value"].Parse += new ConvertEventHandler(dtpParse);

Format and Parse events:

private void dtpFormat(object sender, ConvertEventArgs e)
{
      Binding b = sender as Binding;
      if(b != null)
      {
           DateTimePicker dtp = (b.Control as DateTimePicker);
           if(dtp != null)
           {
                if (e.Value == null || e.Value == DBNull.Value)
                {
                    dtp.Checked = false;
                    dtp.CustomFormat = " ";
                    e.Value = false;
                }
                else
                {
                    dtp.Checked = true;
                    dtp.CustomFormat = "dd-MMM-yyyy";
                    dtp.Value = (DateTime) e.Value;
                }
            }
        }
    }

    private void dtpParse(object sender, ConvertEventArgs e)
    {
        Binding b = sender as Binding;

        if (b != null)
        {
            DateTimePicker dtp = (b.Control as DateTimePicker);
            if (dtp != null)
            {
                if (dtp.Checked == false)
                {
                    e.Value = DBNull.Value;
                }
                else
                {
                    e.Value = dtp.Value;
                }
            }
        }
   }

After debugging, I found that it goes to infinite loop between parse and format events. What is wrong with my code?

Edit: There is also a datagridview binded to bsStaff bindingsource.


问:
Transparently assign value to a custom numeric type
I'd like to create a custom numeric type. Basically a float whose value gets processed by my custom class after an assignment.
I have seen examples that explain how to create the class and read it as a common type (int/float/...).
Yet there's no example about how to make the value assignment as transparent as for a float variable.

What I have seen so far is something like:

```<code>a = MyCustomFloat( 20. )
print(a) # prints "20"
</code>```

What I am looking for is:

```<code>a = MyCustomFloat()
a = 20. # assign new value ; "a" is still an instance of MyCustomFloat
print(a) # prints "20"
</code>```

Is this possible at all?

If yes, how?

答:
It is not possible to override this behaviour at variable level, but can be achieved using descriptors if you're willing to define a as attribute to a class.

```<code>class MyCustomClass:
    def __init__(self, val):
        self.val = val

    def __get__(self, instance, kls=None):
        return self

    def __repr__(self):
        return repr(self.val)

    def __set__(self, instance, val):
        if not isinstance(val, (int, float)):
            raise TypeError('Only objects of type int and float can be assigned')
        self.val = val  # This can be self.val = MyCustomClass(val) as well.

class NameSpace:
    a = MyCustomClass(20.)
</code>```

Demo:

```<code>>>> namespace = NameSpace()

>>> namespace.a
20.0

>>> type(namespace.a)
<class '__main__.MyCustomClass'>

>>> namespace.a = 12

>>> type(namespace.a)
<class '__main__.MyCustomClass'>

>>> namespace.a
12

>>> namespace.a = '1234'
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-40-6aced1b81d6b> in <module>()
----> 1 namespace.a = '1234'
...
TypeError: Only objects of type int and float can be assigned
</code>```

At variable level the only option you have is to have some static checks using mypy(As Chris mentioned it as well). This won't prevent such assignments at run time but can point out such assignments when you run the static code analyzer before deploying code.

Body:
I'd like to create a custom numeric type. Basically a float whose value gets processed by my custom class after an assignment.
I have seen examples that explain how to create the class and read it as a common type (int/float/...).
Yet there's no example about how to make the value assignment as transparent as for a float variable.

What I have seen so far is something like:

a = MyCustomFloat( 20. )
print(a) # prints "20"

What I am looking for is:

a = MyCustomFloat()
a = 20. # assign new value ; "a" is still an instance of MyCustomFloat
print(a) # prints "20"

Is this possible at all?

If yes, how?

Body:
It is not possible to override this behaviour at variable level, but can be achieved using descriptors if you're willing to define a as attribute to a class.

class MyCustomClass:
    def __init__(self, val):
        self.val = val

    def __get__(self, instance, kls=None):
        return self

    def __repr__(self):
        return repr(self.val)

    def __set__(self, instance, val):
        if not isinstance(val, (int, float)):
            raise TypeError('Only objects of type int and float can be assigned')
        self.val = val  # This can be self.val = MyCustomClass(val) as well.

class NameSpace:
    a = MyCustomClass(20.)

Demo:

>>> namespace = NameSpace()

>>> namespace.a
20.0

>>> type(namespace.a)
<class '__main__.MyCustomClass'>

>>> namespace.a = 12

>>> type(namespace.a)
<class '__main__.MyCustomClass'>

>>> namespace.a
12

>>> namespace.a = '1234'
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-40-6aced1b81d6b> in <module>()
----> 1 namespace.a = '1234'
...
TypeError: Only objects of type int and float can be assigned

At variable level the only option you have is to have some static checks using mypy(As Chris mentioned it as well). This won't prevent such assignments at run time but can point out such assignments when you run the static code analyzer before deploying code.


问:
How to make a span with glyphicon as a hyperlink?
I have some form with glyphicon question mark for field inline tooltip on right:

```<code><div class="form-group required">
    <label for="username" class="col-sm-2 control-label">User Name:</label>
    <div class="col-sm-3 tooltip-box">
        <input id="username" type="text" class="form-control" placeholder="username"/>
        <div class="row tooltip-block"><a href="#" data-toggle="popover" data-trigger="hover" data-placement="auto right" data-content="Test tooltip.">
            <span class="glyphicon glyphicon-question-sign"></span></a>
        </div>
    </div>
</div>
</code>```

In full screen it looks as I need:

But on mobile devices or small screens it works only with hovering some very small area within my glyphicon mark and the tooltip overlays it:

Also when I inspect the corresponding a element in Chrome's developer tools, it points to some area outside the span element:

Here is the fiddle: https://jsfiddle.net/r2cm9c9u/

How is it possible to make the whole span with glyphicon as a hyperlink for tooltip?

答:
You can do it with pure css.

If you have:

```<code><div class="col-sm-3 tooltip-box">
        <input id="username" type="text" class="form-control" placeholder="username"/>
        <div class="row tooltip-block"><a href="#" data-toggle="popover" data-trigger="hover" data-placement="auto right" data-content="Test tooltip.">
            <span class="glyphicon glyphicon-question-sign"></span></a>
        </div>
    </div>
</code>```

You don't need 'a' first of all. What you can do with CSS is:

```<code>.tooltip-block span {
    display: none;
}

.tooltip-block:hover + span {
    display: block;
}
</code>```

Whats gonna happen is, when you hover over .tooltip-block following span element will display block. Definitely don't need javascript for a thing like this.

Then if you want that tooltip to be clickable you can use javascript for that.

```<code><div class="col-sm-3 tooltip-box">
            <input id="username" type="text" class="form-control" placeholder="username"/>
            <div class="row tooltip-block" onclick="doSomething()"><a href="#" data-toggle="popover" data-trigger="hover" data-placement="auto right" data-content="Test tooltip.">
                <span class="glyphicon glyphicon-question-sign"></span></a>
            </div>
        </div>
</code>```

Body:
I have some form with glyphicon question mark for field inline tooltip on right:

    User Name:

        <input id="username" type="text" class="form-control" placeholder="username"/>

In full screen it looks as I need:

But on mobile devices or small screens it works only with hovering some very small area within my glyphicon mark and the tooltip overlays it:

Also when I inspect the corresponding a element in Chrome's developer tools, it points to some area outside the span element:

Here is the fiddle: https://jsfiddle.net/r2cm9c9u/

How is it possible to make the whole span with glyphicon as a hyperlink for tooltip?

Body:
You can do it with pure css.

If you have:

<div class="col-sm-3 tooltip-box">
        <input id="username" type="text" class="form-control" placeholder="username"/>
        <div class="row tooltip-block"><a href="#" data-toggle="popover" data-trigger="hover" data-placement="auto right" data-content="Test tooltip.">
            <span class="glyphicon glyphicon-question-sign"></span></a>
        </div>
    </div>

You don't need 'a' first of all. What you can do with CSS is:

.tooltip-block span {
    display: none;
}

.tooltip-block:hover + span {
    display: block;
}

Whats gonna happen is, when you hover over .tooltip-block following span element will display block. Definitely don't need javascript for a thing like this.

Then if you want that tooltip to be clickable you can use javascript for that.

<div class="col-sm-3 tooltip-box">
            <input id="username" type="text" class="form-control" placeholder="username"/>
            <div class="row tooltip-block" onclick="doSomething()"><a href="#" data-toggle="popover" data-trigger="hover" data-placement="auto right" data-content="Test tooltip.">
                <span class="glyphicon glyphicon-question-sign"></span></a>
            </div>
        </div>