问:
(NodeJs) Command line arguments to PhantomJs child process along with script args
I have the following code that works:

```<code>var Path = require('path')
var Phantomjs = require('phantomjs2')
var phantomjsPath = Phantomjs.path
var childArgs = [
      Path.join(__dirname, 'phantomjs-worker.js'),
      'http://...some login url...',
      3000, //login timeout
      'http://...some address to render as image...',
      5000, //address timeout
      '...output image file path...',
      1000, //page width
      1000, //page height
      1234 //some id
    ]
var child = Proc.spawn(phantomjsPath, childArgs, { cwd: process.cwd() })
</code>```

Inside phantom-worker.js:

```<code>var argsOffset = 0;
var login = system.args[argsOffset + 1];
var logintimeout = system.args[argsOffset + 2];
var address = system.args[argsOffset + 3];
var addresstimeout = system.args[argsOffset + 4];
var output = system.args[argsOffset + 5];
var pageWidth = parseInt(system.args[argsOffset + 6]);
var pageHeight = parseInt(system.args[argsOffset + 7]);
var pageId = system.args[argsOffset + 8];
...
</code>```

I need to be able to pass in

```<code>--ignore-ssl-errors=true --ssl-protocol=tlsv1
</code>```

as well.

I tried adding these as the first 2 arguments but it doesn't work. It starts looking for the output image file path for some reason and obviously fails.

Is there any way to pass in these command line arguments along with the script and its child arguments?

答:
The following works as expected. The error was not in this part of the code. Rather, the phantom process was exiting due to memory issues causing the rendered image file to be not created.

```<code>var Path = require('path')
var Phantomjs = require('phantomjs2')
var phantomjsPath = Phantomjs.path
var childArgs = [
      '--ignore-ssl-errors=true',
      '--ssl-protocol=any',
      '--web-security=false',
      Path.join(__dirname, 'phantomjs-worker.js'),
      'http://...some login url...',
      3000, //login timeout
      'http://...some address to render as image...',
      5000, //address timeout
      '...output image file path...',
      1000, //page width
      1000, //page height
      1234 //some id
    ]
var child = Proc.spawn(phantomjsPath, childArgs, { cwd: process.cwd() })
</code>```

Worker:

```<code>var webpage = require('webpage'),
    system = require('system');

var login = system.args[1];
var logintimeout = system.args[2];
var address = system.args[3];
var addresstimeout = system.args[4];
var output = system.args[5];
var pageWidth = parseInt(system.args[6]);
var pageHeight = parseInt(system.args[7]);
var pageId = system.args[8];
</code>```

Body:
I have the following code that works:

var Path = require('path')
var Phantomjs = require('phantomjs2')
var phantomjsPath = Phantomjs.path
var childArgs = [
      Path.join(__dirname, 'phantomjs-worker.js'),
      'http://...some login url...',
      3000, //login timeout
      'http://...some address to render as image...',
      5000, //address timeout
      '...output image file path...',
      1000, //page width
      1000, //page height
      1234 //some id
    ]
var child = Proc.spawn(phantomjsPath, childArgs, { cwd: process.cwd() })

Inside phantom-worker.js:

var argsOffset = 0;
var login = system.args[argsOffset + 1];
var logintimeout = system.args[argsOffset + 2];
var address = system.args[argsOffset + 3];
var addresstimeout = system.args[argsOffset + 4];
var output = system.args[argsOffset + 5];
var pageWidth = parseInt(system.args[argsOffset + 6]);
var pageHeight = parseInt(system.args[argsOffset + 7]);
var pageId = system.args[argsOffset + 8];
...

I need to be able to pass in

--ignore-ssl-errors=true --ssl-protocol=tlsv1

as well.

I tried adding these as the first 2 arguments but it doesn't work. It starts looking for the output image file path for some reason and obviously fails.

Is there any way to pass in these command line arguments along with the script and its child arguments?

Body:
The following works as expected. The error was not in this part of the code. Rather, the phantom process was exiting due to memory issues causing the rendered image file to be not created.

var Path = require('path')
var Phantomjs = require('phantomjs2')
var phantomjsPath = Phantomjs.path
var childArgs = [
      '--ignore-ssl-errors=true',
      '--ssl-protocol=any',
      '--web-security=false',
      Path.join(__dirname, 'phantomjs-worker.js'),
      'http://...some login url...',
      3000, //login timeout
      'http://...some address to render as image...',
      5000, //address timeout
      '...output image file path...',
      1000, //page width
      1000, //page height
      1234 //some id
    ]
var child = Proc.spawn(phantomjsPath, childArgs, { cwd: process.cwd() })

Worker:

var webpage = require('webpage'),
    system = require('system');

var login = system.args[1];
var logintimeout = system.args[2];
var address = system.args[3];
var addresstimeout = system.args[4];
var output = system.args[5];
var pageWidth = parseInt(system.args[6]);
var pageHeight = parseInt(system.args[7]);
var pageId = system.args[8];


来源: stackexchange

问:
Vba Access error 91
I try to run this code

Public Sub Production_UpdateStatus(ByVal lngProductionId As Long, _
                                   ByVal NewProductionStatus As eProductionStatus)
Dim oDb As DAO.Database
Dim oRst As DAO.Recordset
Dim StrSql As String
Dim strProductionStatus As String

On Error GoTo Err_Infos

GetCurrentProductionStatusString NewProductionStatus, strProductionStatus

Set oDb = CurrentDb

'Mise a jour du staut de production
StrSql = "UPDATE tProduction SET tProduction.Statut= '" & strProductionStatus & "'" _
           & " WHERE (tProduction.IdProduction=" & lngProductionId & ");"
oDb.Execute StrSql

'Fermeture des connexions
oRst.Close
oDb.Close
Set oDb = Nothing
Set oRst = Nothing

Exit_currentSub:
    Exit Sub

Err_Infos:
    MsgBox "Erreur #" & Err.Number & " : " & Err.Description
    Resume Exit_currentSub

End Sub
```

<p>This code work but give me error 91. </p>

<blockquote>
  <p>Object variable or With block variable not set</p>
</blockquote>

<p>It generate the following SQL query : </p>

<pre class="lang-sql prettyprint-override"><code>UPDATE tProduction SET tProduction.Statut= 'Nouvelle' WHERE (tProduction.IdProduction=2);
</code>```

When I test direct query, I do not have any error. Could you help me to eliminate this error ?

Thanks

答:
You are closing a recordset object, oRst, that was never initialized with Set. Because you run an action query you do not need a recordset and it may have lingered from prior code versions.

On that same note, because you are passing literal values to an SQL query, consider parameterizing with DAO QueryDef parameters that avoids concatenation and quote enclosures:

Dim oDb As DAO.Database, qdef As DAO.QueryDef
Dim StrSql As String, strProductionStatus As String

GetCurrentProductionStatusString NewProductionStatus, strProductionStatus

Set oDb = CurrentDb

StrSql = "PARAMETERS strProductionStatusParam Text(255), lngProductionIdParam Long;" _
           & " UPDATE tProduction SET tProduction.Statut = [strProductionStatusParam]" _
           & " WHERE (tProduction.IdProduction = [lngProductionIdParam]);"

Set qdef = oDb.CreateQueryDef("", StrSql)

qdef!strProductionStatusParam = strProductionStatus
qdef!lngProductionIdParam = lngProductionId

qdef.Execute dbFailOnError

Set qdef = Nothing
Set oDb = Nothing
```

ContentLicense: CC BY-SA 3.0

Title: Vba Access error 91

Body:
I try to run this code

Public Sub Production_UpdateStatus(ByVal lngProductionId As Long, _
                                   ByVal NewProductionStatus As eProductionStatus)
Dim oDb As DAO.Database
Dim oRst As DAO.Recordset
Dim StrSql As String
Dim strProductionStatus As String

On Error GoTo Err_Infos

GetCurrentProductionStatusString NewProductionStatus, strProductionStatus

Set oDb = CurrentDb

'Mise a jour du staut de production
StrSql = "UPDATE tProduction SET tProduction.Statut= '" & strProductionStatus & "'" _
           & " WHERE (tProduction.IdProduction=" & lngProductionId & ");"
oDb.Execute StrSql

'Fermeture des connexions
oRst.Close
oDb.Close
Set oDb = Nothing
Set oRst = Nothing

Exit_currentSub:
    Exit Sub

Err_Infos:
    MsgBox "Erreur #" & Err.Number & " : " & Err.Description
    Resume Exit_currentSub

End Sub

This code work but give me error 91.

Object variable or With block variable not set

It generate the following SQL query :

UPDATE tProduction SET tProduction.Statut= 'Nouvelle' WHERE (tProduction.IdProduction=2);

When I test direct query, I do not have any error. Could you help me to eliminate this error ?

Thanks


问:
Running script on both local and remote machines?
In my Python code, I have something similar to the following:

```<code>data = load_data()

results = model.train(data)

show_graph(results)
</code>```

Here, load_data() loads some data from my local machine, and show_graph(results) shows a graph on my local machine. However, model.train(data) needs to be executed on a remote machine, because it requires specialist hardware. I only want to run this one function on the remote machine, not the entire script.

I have a user account on this remote machine, and can login using, for example, ssh user@remote.ip.address.

But how can I tell my script to run a certain function on this remote machine?

答: You need some kind of RPC stack (although I'm kind of certain that something can be made by using celery and a little tweaking). A good option (as good as any other) is to implement a server using grpc, it will also allow you to use different languages for the client and the server.

Body:
In my Python code, I have something similar to the following:

data = load_data()

results = model.train(data)

show_graph(results)

Here, load_data() loads some data from my local machine, and show_graph(results) shows a graph on my local machine. However, model.train(data) needs to be executed on a remote machine, because it requires specialist hardware. I only want to run this one function on the remote machine, not the entire script.

I have a user account on this remote machine, and can login using, for example, ssh user@remote.ip.address.

But how can I tell my script to run a certain function on this remote machine?


问:
Tracking mouse input events
Currently using SendInput(MOUSEEVENTF_MOVE) to simulate mouse movements.
SendInput adds a new mouse event to the thread input queue before being processed.

Is it possible to track/check if an specific event has actually been processed?

Tracking WM_MOUSEMOVE in WndProc is no option since it is possible for the user to issue non-simulated mouse movements at the same time.

答:
Is it possible to track/check if an specific event has actually been processed?

In general: No.

SendInput adds a new mouse event to the thread input queue before being processed.

Well, no. SendInput places input events into the hardware input queue, where they get picked up by the raw input thread, and dispatched to the respective threads' input queues.

Tracking WM_MOUSEMOVE in WndProc is no option since it is possible for the user to issue non-simulated mouse movements at the same time.

Correct. You can, however, install a low-level mouse hook, where you can identify injected input1. Injected input has one of the LLMHF_INJECTED or LLMHF_LOWER_IL_INJECTED flags set in the MSLLHOOKSTRUCT structure's flags member.

A brittle solution that allows you to identify injected input in your application's window procedure's mouse message handlers is to pass a specific dwExtraInfo value through the MOUSEINPUT structure. This value can be queried in the message handler by calling GetMessageExtraInfo. It is unreliable, though, because the system uses those values, too. There is no range of values an application can use, that is guaranteed to not collide with values used by the system.

1 The low-level mouse hook runs, after input events are dequeued from the hardware input queue. The events have not been processed by applications or even placed into the respective threads' input queues at that point.

Title: Tracking mouse input events


问:
R: Is there a way to fread data.table from file where some (irregular) lines are skipped?
Here's the sample data file called 'log.txt' (in reality the file contains many more lines, of course):

```<code>148     87      40
148     80      47
126     65      49
-
127     57      53
134     64      52
-
136     72      51
128     72      49
</code>```

Is there a way in R/data.table, to read all lines from there?

If we run dt <- fread("log.txt"), we get error:

```<code>Error in fread("log.txt") :
   Expected sep (' ') but new line, EOF (or other non printing character) ends field 0 when detecting types from point 0: -
</code>```

On the other hand, if we remove all "-" and our file ("log1.txt") looks like this:

```<code>148     87      40
148     80      47
126     65      49

127     57      53
134     64      52

136     72      51
128     72      49
</code>```

then, when we run  dt <- fread("log1.txt"), it reads only the first three lines, with warning:

```<code>  Warning message:
  In fread("log1.txt") :
     Stopped reading at empty line 4 but text exists afterwards (discarded): 127     57      53
</code>```

答:
Thanks to Frank,
Solution:

Step 1: Make lines that should be skipped blank (with external editor), then

Step 2: Run fread(text, blank.lines.skip=TRUE)

Body:
Here's the sample data file called 'log.txt' (in reality the file contains many more lines, of course):

148     87      40
148     80      47
126     65      49
-
127     57      53
134     64      52
-
136     72      51
128     72      49

Is there a way in R/data.table, to read all lines from there?

If we run dt <- fread("log.txt"), we get error:

Error in fread("log.txt") :
   Expected sep (' ') but new line, EOF (or other non printing character) ends field 0 when detecting types from point 0: -

On the other hand, if we remove all "-" and our file ("log1.txt") looks like this:

148     87      40
148     80      47
126     65      49

127     57      53
134     64      52

136     72      51
128     72      49

then, when we run  dt <- fread("log1.txt"), it reads only the first three lines, with warning:

  Warning message:
  In fread("log1.txt") :
     Stopped reading at empty line 4 but text exists afterwards (discarded): 127     57      53


问:
Convert C & submodule included objective-C project (linphone) as a framework or static library?
I want to merge two projects.

First project

Written in objective C and swift 2.3

Pod dependencies

Have different Targets

Submodules dependencies

Second project

https://github.com/BelledonneCommunications/linphone

Written in Objective C

dependency on linphone SDK written in C

Submodules dependencies

How can I convert Second project(linphone) as a framework?

EDIT 1

I have integrated linphone project(second project) including the C
  written linphone SDK and Rectified all compile time errors. and now i
  am able to run the project. But what I will do for Submodules dependencies?

EDIT 2

As per now, succeed login with our own SIP server account. Right
  now my issue is

```<code>LinphoneManager
 - (void)createLinphoneCore
 - theLinphoneCore = linphone_core_new_with_config(&linphonec_vtable, _configDb, (__bridge void *)(self));
</code>```

theLinphoneCore is NULL, why?

NOTE: Still i didnt integrate submodules, but i can do audio & video call everything works fine.

答:
The only sane way to build a complete liblinphone SDK is through the appropriate client repository, e.g. linphone-iphone or linphone-android. As you have discovered, it is possible to build as a framework or static library using:

./prepare.py -c && ./prepare.py -DENABLE_STATIC_ONLY=ON && make && make zipsdk

Set DENABLE_STATIC_ONLY=ON for libs, and =OFF for a framework:

Be aware: as of June 2017, the framework configuration is still under development. It builds and runs in the simulator and on actual hardware, but the resulting app binary can't be submitted to Apple because the sub-frameworks aren't configured correctly. If you don't need to submit (not even TestFlight!) for 2-6 months maybe they will finish up soon.

If you need a functional product sooner, use the static lib configuration. The only tricky part is getting everything set up in your project/workspace.

Do a full clean and build using prepare.py as above

Extract the sdk zip file into your own project directory as liblinphone-sdk

Add the libraries in liblinphone-sdk/apple-darwin/lib to XCode's Linked Frameworks and Libraries section under General. Click +, select "Add Other", navigate to the libs directory. Don't forget to include any in liblinphone-sdk/apple-darwin/lib/mediastreamer/plugins

You may need to add a Build Setting for Header Search Path  $(SRCROOT)/liblinphone-sdk/apple-darwin/include

You may need to add a Build Setting for Library Search Path $(PROJECT_DIR)/liblinphone-sdk/apple-darwin/lib

The XCode project for linphone-iPhone is a good place to discover other tweaks you may need to make.

Setting up your workspace will probably require trial and error. Xcode is not great with the errors but you should be able to use the Report Navigator view to see complete build logs and error messages. If you have an undefined symbol for example, you can try grep -ri SYMBOLNAME liblinphone-sdk to figure out what library might be missing.

Regarding your EDIT 2 question, you need all the submodules or it won't work. ortp, belle-sip, mediastreamer, srtp, mbedtls, they are all essential. Only the mediastreamer plugin codecs are (somewhat) optional.

Body:
I want to merge two projects.

First project

Written in objective C and swift 2.3

Pod dependencies

Have different Targets

Submodules dependencies

Second project

https://github.com/BelledonneCommunications/linphone

Written in Objective C

dependency on linphone SDK written in C

Submodules dependencies

How can I convert Second project(linphone) as a framework?

EDIT 1

I have integrated linphone project(second project) including the C
  written linphone SDK and Rectified all compile time errors. and now i
  am able to run the project. But what I will do for Submodules dependencies?

EDIT 2

As per now, succeed login with our own SIP server account. Right
  now my issue is

LinphoneManager
 - (void)createLinphoneCore
 - theLinphoneCore = linphone_core_new_with_config(&linphonec_vtable, _configDb, (__bridge void *)(self));

theLinphoneCore is NULL, why?

NOTE: Still i didnt integrate submodules, but i can do audio & video call everything works fine.


问:
jekyll dependency error while read form _post
I'm new in Jekyll and I was working fine in my gh-pages Jekyll Project. But when I trying to do post loop from the _posts directory then the following error happened. And I try to resolve this by gem install redcarpet  and gem install rough but it installs rough successfully. And give an error when trying to install redcarpet.

The Error is:

And when I use gem install carpet it gives me the following error:

My _posts directory looks like:

My Operating system is:  Windows 10 64 bit

答: Try removing the markdown: redcarpet entry in your _config.yml file. It is no longer supported by Jekyll—and isn’t necessary any more.


问:
Understanding the use of curly braces and "OJ" in a SQL query
A previous employee at my office constructed a php script that uses curly braces in the a SQL query.  I understand that it would normally work for things like encapsulating array variables, but this query doesn't have any PHP variables in the string.  Can someone clarify what the table being generated in the FROM section of the query is actually requiring the curly braces for, and what the OJ stands for?

```<code>SELECT
  DISTINCT ra.folder_id,
  pd.id,
  f.name,
  pd.descriptor_text
FROM
  {
    OJ permission_descriptors pd
    LEFT JOIN permission_descriptor_users pdu
    ON pdu.descriptor_id = pd.id
  }
  role_allocations ra,
  folders f
WHERE
  pdu.descriptor_id IS NULL AND
  pd.id = ra.permission_descriptor_id AND
  pd.id != 1
  ra.folder_id = f.id
ORDER BY
  ra.folder_id
</code>```

答:
You can remove the "{ ok" and "}" and the SQL will work as before, just not in ODBC.

```<code>escaped_table_reference:
    table_reference
  | { OJ table_reference }
</code>```

The { OJ ... } syntax shown in the join syntax description exists only
  for compatibility with ODBC. The curly braces in the syntax should be
  written literally; they are not metasyntax as used elsewhere in syntax
  descriptions.

SELECT left_tbl.*
      FROM { OJ left_tbl LEFT OUTER JOIN right_tbl ON left_tbl.id = right_tbl.id }
      WHERE right_tbl.id IS NULL;

You can use other types of joins within { OJ ... }, such as INNER JOIN
  or RIGHT OUTER JOIN. This helps with compatibility with some
  third-party applications, but is not official ODBC syntax.

Ref

Body:
A previous employee at my office constructed a php script that uses curly braces in the a SQL query.  I understand that it would normally work for things like encapsulating array variables, but this query doesn't have any PHP variables in the string.  Can someone clarify what the table being generated in the FROM section of the query is actually requiring the curly braces for, and what the OJ stands for?

SELECT
  DISTINCT ra.folder_id,
  pd.id,
  f.name,
  pd.descriptor_text
FROM
  {
    OJ permission_descriptors pd
    LEFT JOIN permission_descriptor_users pdu
    ON pdu.descriptor_id = pd.id
  }
  role_allocations ra,
  folders f
WHERE
  pdu.descriptor_id IS NULL AND
  pd.id = ra.permission_descriptor_id AND
  pd.id != 1
  ra.folder_id = f.id
ORDER BY
  ra.folder_id

Body:
You can remove the "{ ok" and "}" and the SQL will work as before, just not in ODBC.

escaped_table_reference:
    table_reference
  | { OJ table_reference }

The { OJ ... } syntax shown in the join syntax description exists only
  for compatibility with ODBC. The curly braces in the syntax should be
  written literally; they are not metasyntax as used elsewhere in syntax
  descriptions.

SELECT left_tbl.*
      FROM { OJ left_tbl LEFT OUTER JOIN right_tbl ON left_tbl.id = right_tbl.id }
      WHERE right_tbl.id IS NULL;

You can use other types of joins within { OJ ... }, such as INNER JOIN
  or RIGHT OUTER JOIN. This helps with compatibility with some
  third-party applications, but is not official ODBC syntax.

Ref


问:
Javascript Date Returning NaN undefined NaN
I am pulling modified dates from a SharePoint library and using the below to convert it:

```<code>    function convertSPDate(d) {
    // split apart the date and time
    var xDate = d.split("")[0];
    var xTime = d.split(" ")[1];

    // split apart the hour, minute, & second
    var xTimeParts = xTime.split(":");
    var xHour = xTimeParts[0];
    var xMin = xTimeParts[1];

    // split apart the year, month, & day
    var xDateParts = xDate.split("-");
    var xMonth = xDateParts[1]-1;
    var xDay = xDateParts[2];
    var xYear = xDateParts[0];

    var dDate = new Date(xYear, xMonth, xDay, xHour, xMin);
    return dDate;
}
</code>```

And then formatting it using:

```<code>function getformattedDate(d){
var month = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "October", "Nov" , "Dec"];
var getConvertedDate = d;
return formattedDate =  getConvertedDate.getDate() +" "+month[getConvertedDate.getMonth()] +" "+getConvertedDate.getFullYear();
}
</code>```

I'm then trying to display this date on a page for different items using:

```<code>var getDate = getformattedDate(convertSPDate(getFilteredItems[i].modified));
</code>```

However this is just returning NaN undefined NaN - any help at all would be much appreciated!

答:
Thanks to @trincot - was a very simple solution and one I completely overlooked!

The first split was wrong and simply needed a space...

Thanks all

Body:
I am pulling modified dates from a SharePoint library and using the below to convert it:

    function convertSPDate(d) {
    // split apart the date and time
    var xDate = d.split("")[0];
    var xTime = d.split(" ")[1];

    // split apart the hour, minute, & second
    var xTimeParts = xTime.split(":");
    var xHour = xTimeParts[0];
    var xMin = xTimeParts[1];

    // split apart the year, month, & day
    var xDateParts = xDate.split("-");
    var xMonth = xDateParts[1]-1;
    var xDay = xDateParts[2];
    var xYear = xDateParts[0];

    var dDate = new Date(xYear, xMonth, xDay, xHour, xMin);
    return dDate;
}

And then formatting it using:

function getformattedDate(d){
var month = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "October", "Nov" , "Dec"];
var getConvertedDate = d;
return formattedDate =  getConvertedDate.getDate() +" "+month[getConvertedDate.getMonth()] +" "+getConvertedDate.getFullYear();
}

I'm then trying to display this date on a page for different items using:

var getDate = getformattedDate(convertSPDate(getFilteredItems[i].modified));

However this is just returning NaN undefined NaN - any help at all would be much appreciated!


问:
How to extract all span's on a page using iMacros?
```<code><span class="Fcontainer"><a href="http://www.codechef.com" rel="noopener nofollow" target="_blank" onclick="return MN.openUrl(this);" class="external_link" data-qt-tooltip="codechef.com" data-tooltip="attached">Programming Competition,Programming Contest,Online Computer Programming</a></span>
<span class="Fcontainer"><a href="http://www.hackerrank.com" rel="noopener nofollow" target="_blank" onclick="return MN.openUrl(this);" class="external_link" data-qt-tooltip="hackerrank.com">HackerRank</a></span>
</code>```

A number of span's with same class is there a webpage.

I am using

```<code>TAG POS={{!LOOP}} TYPE=SPAN ATTR=CLASS:Fcontainer* EXTRACT=TXT
SET !VAR4 {{!EXTRACT}}
</code>```

But I am only to save 1 entry to my csv file column, that is only "Programming Competition,Programming Contest,Online Computer Programming"

How do I save all the span's with same class to csv file, with multiple columns?

答:
If you want the data in the different columns in the same row instead of multiple rows and same column, you will have to implement Javascript code.

Get all of the data in an array and then save the array in the CSV.

In the CSV, The array data will be in one cell. So you will have to select the cell and split text on basis of comma. This will get the extracted data in the same row but different column.

Body:
Programming Competition,Programming Contest,Online Computer Programming
HackerRank

A number of span's with same class is there a webpage.

I am using

TAG POS={{!LOOP}} TYPE=SPAN ATTR=CLASS:Fcontainer* EXTRACT=TXT
SET !VAR4 {{!EXTRACT}}

But I am only to save 1 entry to my csv file column, that is only "Programming Competition,Programming Contest,Online Computer Programming"

How do I save all the span's with same class to csv file, with multiple columns?


问:
How to filter $ value on php
i want to filter value

example:
112 to be 01:12

from script

```<code>$duration = get_post_meta( $post->ID, 'TMDB_Runtime', true );
if ( ! empty( $duration ) ) {
echo '<div class="gmr-duration-item" property="duration">' . $duration . __( ' <a class="fa fa-clock-o" aria-hidden="true"></a>','movies' ) . '</div>';
</code>```

I've tried using substr and str_replace and put it into function.php

```<code><?php
$text = '$duration';
$text = substr($text, 0, 3);
echo $text =str_replace("1","01:", $text);
?>
</code>```

But always display parse error.

答:
There are two problems I am noticing in this code snippet:

```<code><?php
$text = '$duration';
$text = substr($text, 0, 3);
echo $text =str_replace("1","01:", $text);
?>
</code>```

First:
echo $text =str_replace("1","01:", $text); is incorrect syntax. You can't assign a function to a function. Split it into two lines.

```<code>$text = str_replace("1","01:", $text);
echo $text;
</code>```

Second:
$text = '$duration'; is not setting $text to 112. It is setting it to the literal string $duration. Single-quotes in PHP do not evaluate variables, that is what double-quotes do. So, try this instead:

```<code>$text = "$duration";
</code>```

Title: How to filter $ value on php

Body:
i want to filter value

example:
112 to be 01:12

from script

$duration = get_post_meta( $post->ID, 'TMDB_Runtime', true );
if ( ! empty( $duration ) ) {
echo '
' . $duration . __( ' ','movies' ) . '
';

I've tried using substr and str_replace and put it into function.php

<?php
$text = '$duration';
$text = substr($text, 0, 3);
echo $text =str_replace("1","01:", $text);
?>

But always display parse error.

Body:
There are two problems I am noticing in this code snippet:

<?php
$text = '$duration';
$text = substr($text, 0, 3);
echo $text =str_replace("1","01:", $text);
?>

First:
echo $text =str_replace("1","01:", $text); is incorrect syntax. You can't assign a function to a function. Split it into two lines.

$text = str_replace("1","01:", $text);
echo $text;

Second:
$text = '$duration'; is not setting $text to 112. It is setting it to the literal string $duration. Single-quotes in PHP do not evaluate variables, that is what double-quotes do. So, try this instead:

$text = "$duration";


问:
How to watch object changes with rxjs 5
I would like to watch over an object, so all the subscribers will be informed for any changes of it.

I saw it already been asked before,
yet the answer is irrelevant since RXjs verion 5 do not include the ofObjectChanges in it's API anymore.

I've looked at some "hacks" like creating an observer which return a function:

```<code>let myObservable =  new Observable((observer) => {
  return (data) => {
    observer.next(data)
  }
})
//...
myObservable.subscribe()('someData')
</code>```

However, I'm sure there is more elegant way of doing it.
Any Ideas?

答:
The ES6 way of observing an object is with Proxies. You create a Proxy that wraps the original object and do your work on it. You can use it to create something similar to Observable.ofObjectChanges. Here a partial implementation (only set. You'd need to implement the other traps):

```<code>Observable.ofProxyChanges = (target) => {
  let subject = new Subject
  let proxy = new Proxy(target, {
    set(target, key, val) {
      let oldValue = target[key]
      target[key] = val
      subject.next({
        type: oldValue === undefined ? "add" : "change",
        object: target,
        name: key,
        oldValue: oldValue
      })
    }
  })
  return [proxy, subject.asObservable()]
}

let [obj, objChange$] = Observable.ofProxyChanges({})
objChange$.subscribe(console.log)

obj.bar = 1 // logs { type: "add", name: "bar", object: { bar: 1 } }
obj.foo = 2 // logs { type: "add", name: "foo", object: { bar: 1, foo: 2 } }
obj.foo = 3 // logs { type: "change", name: "foo", object: { bar: 1, foo: 3 }, oldValue: 2 }
</code>```

Title: How to watch object changes with rxjs 5

Body:
I would like to watch over an object, so all the subscribers will be informed for any changes of it.

I saw it already been asked before,
yet the answer is irrelevant since RXjs verion 5 do not include the ofObjectChanges in it's API anymore.

I've looked at some "hacks" like creating an observer which return a function:

let myObservable =  new Observable((observer) => {
  return (data) => {
    observer.next(data)
  }
})
//...
myObservable.subscribe()('someData')

However, I'm sure there is more elegant way of doing it.
Any Ideas?

Body:
The ES6 way of observing an object is with Proxies. You create a Proxy that wraps the original object and do your work on it. You can use it to create something similar to Observable.ofObjectChanges. Here a partial implementation (only set. You'd need to implement the other traps):

Observable.ofProxyChanges = (target) => {
  let subject = new Subject
  let proxy = new Proxy(target, {
    set(target, key, val) {
      let oldValue = target[key]
      target[key] = val
      subject.next({
        type: oldValue === undefined ? "add" : "change",
        object: target,
        name: key,
        oldValue: oldValue
      })
    }
  })
  return [proxy, subject.asObservable()]
}

let [obj, objChange$] = Observable.ofProxyChanges({})
objChange$.subscribe(console.log)

obj.bar = 1 // logs { type: "add", name: "bar", object: { bar: 1 } }
obj.foo = 2 // logs { type: "add", name: "foo", object: { bar: 1, foo: 2 } }
obj.foo = 3 // logs { type: "change", name: "foo", object: { bar: 1, foo: 3 }, oldValue: 2 }


问:
Take from a list only the element i just clicked and use it
i have a list and when someone clicks on an li element then with $.ajax()  i fetch the specific data it wants.

for ie :

```<code><li id="test1">test 1 </li>
<li id="test2">test 2 </li>
<li id="test3">test 3 </li>
...
<li id="testN">test N </li>
</code>```

So the ajax part is for test 1 :

```<code>$('#test1').click(function() {

 $.ajax({
  url: 'fetch.php',
  type: 'POST',
  data: { temp : 'test1'},
  success: function(data) {
    $('#test1').append(data);
  }
});
</code>```

and the same for 2,3,4...N

But the problem is it comes too much of code..ok its just copy paste but can i do it another way? meaning when i click test1 element jQuery finds out what element i clicked and runs for it...

Sorry my bad english
thanks

答:
You could put a class="test" to all your LIs and select the class using $(".test") or assign a unique ID to the UL
 and select only LIs in that UL $("#tests li")

ContentLicense: CC BY-SA 2.5

Body:
i have a list and when someone clicks on an li element then with $.ajax()  i fetch the specific data it wants.

for ie :

test 1

test 2

test 3

...

test N

So the ajax part is for test 1 :

$('#test1').click(function() {

 $.ajax({
  url: 'fetch.php',
  type: 'POST',
  data: { temp : 'test1'},
  success: function(data) {
    $('#test1').append(data);
  }
});

and the same for 2,3,4...N

But the problem is it comes too much of code..ok its just copy paste but can i do it another way? meaning when i click test1 element jQuery finds out what element i clicked and runs for it...

Sorry my bad english
thanks

Body: You could put a class="test" to all your LIs and select the class using $(".test") or assign a unique ID to the UL <ul id="tests"> and select only LIs in that UL $("#tests li")


问:
ValueError when importing a praw script
can someone help me?

Let me explain myself better.
I have this folder structure:

```<code>praw-test
    jobs
        __init__.py
        redisJob.py
    main.py
</code>```

and if I run directly python jobs\redisJob.py it works just fine.

But, if I try to import the file redisJob.py in main.py it gives me this error:

```<code>File ".\main.py", line 13, in <module>
    from jobs.redisJob import DailyJob
  File "D:\git\praw-test\jobs\redisJob.py", line 5, in <module>
    import praw
  File "D:\git\praw-test\env\lib\site-packages\praw\__init__.py", line 14, in <module>
    from .reddit import Reddit  # NOQA
  File "D:\git\praw-test\env\lib\site-packages\praw\reddit.py", line 5, in <module>
    from update_checker import update_check
  File "D:\git\praw-test\env\lib\site-packages\update_checker.py", line 11, in <module>
    import requests
  File "D:\git\praw-test\env\lib\site-packages\requests\__init__.py", line 53, in <module>
    major, minor, patch = urllib3_version
ValueError: not enough values to unpack (expected 3, got 1)
</code>```

Just to make sure, the import command is

```<code>from jobs.redisJob import DailyJob
</code>```

Did I do something wrong?

Update
I found a workaround.
I just need to import urllib3 in my main.py then assigning the correct version.

```<code>import urllib3
urllib3.__version__ = '1.21.1'
from jobs.redisJob import DailyJob
</code>```

These three lines have to be on top of my script.

答:
It appears that you're importing under a different environment.  Different launch techniques can spawn different processes and shells; this could lead to the environment variable having a value other than expected.

I don't know enough SDE details to give you a definitive solution, but I can certainly recommend a simple debugging line.  Just before the problem line, insert

```<code>print urllib3_version
</code>```

See what you get for the value in each launch method.  I expect that there's some implementation detail, such as the values being concatenated somehow, or having some missing.

You can work around this with a check:

```<code>if len(urllib3_version) == 3:
    major, minor, patch = urllib3_version
else:
    # This will depend on what you see in the single value
</code>```

You may need to split a string, supply defaults for missing values, or some other adaptation.

Title: ValueError when importing a praw script

Body:
can someone help me?

Let me explain myself better.
I have this folder structure:

praw-test
    jobs
        __init__.py
        redisJob.py
    main.py

and if I run directly python jobs\redisJob.py it works just fine.

But, if I try to import the file redisJob.py in main.py it gives me this error:

File ".\main.py", line 13, in <module>
    from jobs.redisJob import DailyJob
  File "D:\git\praw-test\jobs\redisJob.py", line 5, in <module>
    import praw
  File "D:\git\praw-test\env\lib\site-packages\praw\__init__.py", line 14, in <module>
    from .reddit import Reddit  # NOQA
  File "D:\git\praw-test\env\lib\site-packages\praw\reddit.py", line 5, in <module>
    from update_checker import update_check
  File "D:\git\praw-test\env\lib\site-packages\update_checker.py", line 11, in <module>
    import requests
  File "D:\git\praw-test\env\lib\site-packages\requests\__init__.py", line 53, in <module>
    major, minor, patch = urllib3_version
ValueError: not enough values to unpack (expected 3, got 1)

Just to make sure, the import command is

from jobs.redisJob import DailyJob

Did I do something wrong?

Update
I found a workaround.
I just need to import urllib3 in my main.py then assigning the correct version.

import urllib3
urllib3.__version__ = '1.21.1'
from jobs.redisJob import DailyJob

These three lines have to be on top of my script.

Body:
It appears that you're importing under a different environment.  Different launch techniques can spawn different processes and shells; this could lead to the environment variable having a value other than expected.

I don't know enough SDE details to give you a definitive solution, but I can certainly recommend a simple debugging line.  Just before the problem line, insert

print urllib3_version

See what you get for the value in each launch method.  I expect that there's some implementation detail, such as the values being concatenated somehow, or having some missing.

You can work around this with a check:

if len(urllib3_version) == 3:
    major, minor, patch = urllib3_version
else:
    # This will depend on what you see in the single value

You may need to split a string, supply defaults for missing values, or some other adaptation.


问:
Google assistant "No module named googles...."
Whenever I run this command

```<code>py -m googlesamples.assistant.auth_helpers -client-secrets <secrete-location>
</code>```

I get an error saying:

```<code>C:\Users\chand\AppData\Local\Programs\Python\Python36\python.exe:
  No module named googlesamples.assistant.auth_helpers
</code>```

I'm not sure what the issue is as it worked on a different device with the same steps.

答:
I got this error when I didn't enter the voice shell

```<code>. /home/pi/bin/voice-recognizer-shell.sh
</code>```

then rerun

```<code>(env) pi@raspberrypi:~/voice-recognizer-raspi $ ./src/main.py
</code>```

Body:
Whenever I run this command

py -m googlesamples.assistant.auth_helpers -client-secrets <secrete-location>

I get an error saying:

C:\Users\chand\AppData\Local\Programs\Python\Python36\python.exe:
  No module named googlesamples.assistant.auth_helpers

I'm not sure what the issue is as it worked on a different device with the same steps.

Body:
I got this error when I didn't enter the voice shell

. /home/pi/bin/voice-recognizer-shell.sh

then rerun

(env) pi@raspberrypi:~/voice-recognizer-raspi $ ./src/main.py


问:
What database tests should I write so that refactoring database is easy
Are there any guidelines on writing database tests so that you can refactor database "without fear" while doing evolutionary database design?

What aspects of database should be put to test while developing it? Any example would be great..

答: I write tests that call my dal code and after I check if the inserts/updates/deletes actually occurred, so called state tests. These are pr definition not Units test but rather integration tests, but they have actually helped me many times doing database changes. Over the time I have more and better tests and even bigger database changes go rather seamlessly.</p>

OwnerDisplayName: StackUnderflow

LastEditorDisplayName: StackUnderflow

OwnerDisplayName: TT


问:
Invalid memory access of location 0x0 in native call by using JNI (on Mac)
I have two eclipse plugins calling one native framework indirectly: plugin A load libA.jnilib, plug B load libB.jnilib, then both libA.jnilib and libB.jnilib dynamically
load the same framework and call the functions in it.

pluginA or pluginB can work well separately but when they are running at the same time, pluginB will crash at framework call with the error - "Invalid memory access of location 0x0 " .(in native codes, I can find the function pointer resolve from the framework is not NULL, but failed once call it) We need the two plugin work together but we have no rights to change the codes of pluginA since it is legacy codes. So my question is technically is there any ways I could make the pluginB call the framework successfully?

答: You could maybe copy the library file to another name and use that one in B.</p>


问:
Update function not called on button click
My Update function does not get called after clicking a button (which should send a message).

Here's the code that should trigger the function with the onClick event:

```<code>[ input [ type_ "submit", onClick TopicSelected, value (getTopic topic) ] []
</code>```

Here's the Update function:

```<code>update : Msg -> Model -> Model
update msg model =
    case msg of
        TopicSelected ->
            { model
                | articles = []
                , podcasts = []
                , videos = []
            }

view model =
    div []
        [ table []
            [ tr [] [ td [] [ b [] [ text "Videos" ] ] ]
            , div [] <| contentUI model.videos
            , tr [] [ td [] [ b [] [ text "Podcasts" ] ] ]
            , div [] <| contentUI model.podcasts
            , tr [] [ td [] [ b [] [ text "Articles" ] ] ]
            , div [] <| contentUI model.articles
            ]
        ]
</code>```

Here's the entire function that routes then onClick event:

```<code>topicTocheckbox : Topic -> Html Msg
topicTocheckbox topic =
    div []
        [ input [ type_ "submit", onClick TopicSelected, value (getTopic topic) ] []
        , label [] [ text <| getTopic topic ]
        ]
</code>```

The code can be found on GitHub.

答:
Looking at your code, you're trying to use the nested "component" of Contributor.elm in Home.elm, but you aren't wiring things up in the parent (Home) update function.

This is a broad and controversial topic in the Elm community. The typical recommendation is to try to avoid nesting like this unless absolutely necessary.

If you absolutely need to nest in this way, then your code will be sprinkled with variations of update cases like this:

type ParentMsg
    = ...
    | ChildMsg Child.Msg

type alias ParentModel =
    { ...
    , child : Child.Model
    }

case msg of
    ChildMsg childMsg ->
        let (childModel, childCmd) = Child.update childMsg model.child
        in { model | child = childModel } ! [ Cmd.map ChildMsg childCmd ]
```

At every layer nesting, you'll need to wire up child state and passing child Msg and Cmds back and forth.

Compounded on that is the fact that in your code, you're dealing with a list of Contributors, which means you'll also need to pass around an index so that you know which contributor in the list you're editing (here is a minimal example of updating model array elements).

The good news is that Elm makes refactoring a breeze!

Body:
My Update function does not get called after clicking a button (which should send a message).

Here's the code that should trigger the function with the onClick event:

[ input [ type_ "submit", onClick TopicSelected, value (getTopic topic) ] []

Here's the Update function:

update : Msg -> Model -> Model
update msg model =
    case msg of
        TopicSelected ->
            { model
                | articles = []
                , podcasts = []
                , videos = []
            }

view model =
    div []
        [ table []
            [ tr [] [ td [] [ b [] [ text "Videos" ] ] ]
            , div [] <| contentUI model.videos
            , tr [] [ td [] [ b [] [ text "Podcasts" ] ] ]
            , div [] <| contentUI model.podcasts
            , tr [] [ td [] [ b [] [ text "Articles" ] ] ]
            , div [] <| contentUI model.articles
            ]
        ]

Here's the entire function that routes then onClick event:

topicTocheckbox : Topic -> Html Msg
topicTocheckbox topic =
    div []
        [ input [ type_ "submit", onClick TopicSelected, value (getTopic topic) ] []
        , label [] [ text <| getTopic topic ]
        ]

The code can be found on GitHub.

Body:
Looking at your code, you're trying to use the nested "component" of Contributor.elm in Home.elm, but you aren't wiring things up in the parent (Home) update function.

This is a broad and controversial topic in the Elm community. The typical recommendation is to try to avoid nesting like this unless absolutely necessary.

If you absolutely need to nest in this way, then your code will be sprinkled with variations of update cases like this:

type ParentMsg
    = ...
    | ChildMsg Child.Msg

type alias ParentModel =
    { ...
    , child : Child.Model
    }

case msg of
    ChildMsg childMsg ->
        let (childModel, childCmd) = Child.update childMsg model.child
        in { model | child = childModel } ! [ Cmd.map ChildMsg childCmd ]

At every layer nesting, you'll need to wire up child state and passing child Msg and Cmds back and forth.

Compounded on that is the fact that in your code, you're dealing with a list of Contributors, which means you'll also need to pass around an index so that you know which contributor in the list you're editing (here is a minimal example of updating model array elements).

The good news is that Elm makes refactoring a breeze!


问:
Hibernate criteria with EmbeddedId
I have my Entity:

```<code>@Entity
@Table(name="performances")
@AssociationOverrides({
    @AssociationOverride(name="id.player", joinColumns=@JoinColumn(name="player_id")),
    @AssociationOverride(name="id.season", joinColumns=@JoinColumn(name="season_id"))
})
public class Performance extends AbstractEntity<PerformanceID> {

    private static final long serialVersionUID = 1L;

    @EmbeddedId
    @Getter @Setter
    private PerformanceID id;
    @Getter @Setter
    private int goals;

    public Player getPlayer(){
        return id.getPlayer();
    }

    public Season getSeason(){
        return id.getSeason();
    }
</code>```

and:

```<code>@Embeddable
public class PerformanceID implements Serializable {

    private static final long serialVersionUID = 1L;

    @ManyToOne(fetch=FetchType.LAZY, targetEntity=Player.class)
    @JoinColumn(name="player_id")
    @Getter @Setter
    private Player player;
    @ManyToOne(fetch=FetchType.LAZY, targetEntity=Season.class)
    @JoinColumn(name="season_id")
    @Getter @Setter
    private Season season;
</code>```

How to select Performance records where Players have name 'Claudio' ? In HQL it simply works:

```<code>Query query = getSession().createQuery("from Performance where id.player.name = 'Claudio'");
return query.list();
</code>```

But I need to do it by Criteria API. Following code will fail:

```<code>Criteria criteria = getSession().createCriteria(Performance.class);
criteria.add(Restrictions.ilike("id.player.name", "Claudio"));
return criteria.list();
</code>```

org.hibernate.QueryException: could not resolve property:
  id.player.name of:
  pl.andrzejcichon.criterionlazydatamodel.entities.Performance  at
  org.hibernate.persister.entity.AbstractPropertyMapping.propertyException(AbstractPropertyMapping.java:83)
    at
  org.hibernate.persister.entity.AbstractPropertyMapping.toColumns(AbstractPropertyMapping.java:98)
    at
  org.hibernate.persister.entity.BasicEntityPropertyMapping.toColumns(BasicEntityPropertyMapping.java:61)
    at
  org.hibernate.persister.entity.AbstractEntityPersister.toColumns(AbstractEntityPersister.java:1912)
    at
  org.hibernate.loader.criteria.CriteriaQueryTranslator.getColumns(CriteriaQueryTranslator.java:523)
    at
  org.hibernate.loader.criteria.CriteriaQueryTranslator.findColumns(CriteriaQueryTranslator.java:538)
    at
  org.hibernate.criterion.LikeExpression.toSqlString(LikeExpression.java:80)
    at
  org.hibernate.loader.criteria.CriteriaQueryTranslator.getWhereCondition(CriteriaQueryTranslator.java:419)
    at
  org.hibernate.loader.criteria.CriteriaJoinWalker.(CriteriaJoinWalker.java:123)
    at
  org.hibernate.loader.criteria.CriteriaJoinWalker.(CriteriaJoinWalker.java:92)
    at
  org.hibernate.loader.criteria.CriteriaLoader.(CriteriaLoader.java:93)
    at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1599)   at
  org.hibernate.internal.CriteriaImpl.list(CriteriaImpl.java:374)   at
  pl.andrzejcichon.criterionlazydatamodel.repository.impl.PerformanceDatabaseRepository.customList(PerformanceDatabaseRepository.java:29)
    at
  pl.andrzejcichon.criterionlazydatamodel.repository.impl.PerformanceDatabaseRepositoryTest.test(PerformanceDatabaseRepositoryTest.java:24)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)  at
  sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)   at
  sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)   at
  java.lang.reflect.Method.invoke(Unknown Source)   at
  org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
    at
  org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at
  org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
    at
  org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
    at
  org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
    at
  org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
    at
  org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
    at
  org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
    at
  org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)  at
  org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)   at
  org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)     at
  org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)   at
  org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)  at
  org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at
  org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:300)    at
  org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
    at
  org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
    at
  org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at
  org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
    at
  org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at
  org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at
  org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

The other try:

```<code>Criteria criteria = createCriteria();
criteria.createAlias("id.player", "player");
criteria.add(Restrictions.ilike("player.name", "Claudio"));
return criteria.list();
</code>```

Will generate query:

Hibernate: select this_.player_id as player2_1_0_, this_.season_id as
  season3_1_0_, this_.goals as goals1_0_ from performances this_ where
  player1_.name ilike ?

But it will fail with SQLGrammarException : "Missing FROM clause for table player1_"

答:
Your mapping is incorrect. An EmbeddableId class should contain @Id (thus Serializable) values, not mappings or complex types. You should move your mappings to your entity class, and then only include their id's in the EmbbedableId class. See the following example (from the JPA 2.2 specification)

```<code>@Embeddable
public class DependentId {
    String name;
    long empPK;   // corresponds to PK type of Employee
}

@Entity
public class Dependent {
    @EmbeddedId DependentId id;

    // id attribute mapped by join column default
    @MapsId("empPK") // maps empPK attribute of embedded id
    @ManyToOne Employee emp;
}
</code>```

Title: Hibernate criteria with EmbeddedId

Body:
I have my Entity:

@Entity
@Table(name="performances")
@AssociationOverrides({
    @AssociationOverride(name="id.player", joinColumns=@JoinColumn(name="player_id")),
    @AssociationOverride(name="id.season", joinColumns=@JoinColumn(name="season_id"))
})
public class Performance extends AbstractEntity<PerformanceID> {

    private static final long serialVersionUID = 1L;

    @EmbeddedId
    @Getter @Setter
    private PerformanceID id;
    @Getter @Setter
    private int goals;

    public Player getPlayer(){
        return id.getPlayer();
    }

    public Season getSeason(){
        return id.getSeason();
    }

and:

@Embeddable
public class PerformanceID implements Serializable {

    private static final long serialVersionUID = 1L;

    @ManyToOne(fetch=FetchType.LAZY, targetEntity=Player.class)
    @JoinColumn(name="player_id")
    @Getter @Setter
    private Player player;
    @ManyToOne(fetch=FetchType.LAZY, targetEntity=Season.class)
    @JoinColumn(name="season_id")
    @Getter @Setter
    private Season season;

How to select Performance records where Players have name 'Claudio' ? In HQL it simply works:

Query query = getSession().createQuery("from Performance where id.player.name = 'Claudio'");
return query.list();

But I need to do it by Criteria API. Following code will fail:

Criteria criteria = getSession().createCriteria(Performance.class);
criteria.add(Restrictions.ilike("id.player.name", "Claudio"));
return criteria.list();

org.hibernate.QueryException: could not resolve property:
  id.player.name of:
  pl.andrzejcichon.criterionlazydatamodel.entities.Performance  at
  org.hibernate.persister.entity.AbstractPropertyMapping.propertyException(AbstractPropertyMapping.java:83)
    at
  org.hibernate.persister.entity.AbstractPropertyMapping.toColumns(AbstractPropertyMapping.java:98)
    at
  org.hibernate.persister.entity.BasicEntityPropertyMapping.toColumns(BasicEntityPropertyMapping.java:61)
    at
  org.hibernate.persister.entity.AbstractEntityPersister.toColumns(AbstractEntityPersister.java:1912)
    at
  org.hibernate.loader.criteria.CriteriaQueryTranslator.getColumns(CriteriaQueryTranslator.java:523)
    at
  org.hibernate.loader.criteria.CriteriaQueryTranslator.findColumns(CriteriaQueryTranslator.java:538)
    at
  org.hibernate.criterion.LikeExpression.toSqlString(LikeExpression.java:80)
    at
  org.hibernate.loader.criteria.CriteriaQueryTranslator.getWhereCondition(CriteriaQueryTranslator.java:419)
    at
  org.hibernate.loader.criteria.CriteriaJoinWalker.(CriteriaJoinWalker.java:123)
    at
  org.hibernate.loader.criteria.CriteriaJoinWalker.(CriteriaJoinWalker.java:92)
    at
  org.hibernate.loader.criteria.CriteriaLoader.(CriteriaLoader.java:93)
    at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1599)   at
  org.hibernate.internal.CriteriaImpl.list(CriteriaImpl.java:374)   at
  pl.andrzejcichon.criterionlazydatamodel.repository.impl.PerformanceDatabaseRepository.customList(PerformanceDatabaseRepository.java:29)
    at
  pl.andrzejcichon.criterionlazydatamodel.repository.impl.PerformanceDatabaseRepositoryTest.test(PerformanceDatabaseRepositoryTest.java:24)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)  at
  sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)   at
  sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)   at
  java.lang.reflect.Method.invoke(Unknown Source)   at
  org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
    at
  org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at
  org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
    at
  org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
    at
  org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
    at
  org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
    at
  org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
    at
  org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
    at
  org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)  at
  org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)   at
  org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)     at
  org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)   at
  org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)  at
  org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at
  org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:300)    at
  org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
    at
  org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
    at
  org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at
  org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
    at
  org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at
  org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at
  org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

The other try:

Criteria criteria = createCriteria();
criteria.createAlias("id.player", "player");
criteria.add(Restrictions.ilike("player.name", "Claudio"));
return criteria.list();

Will generate query:

Hibernate: select this_.player_id as player2_1_0_, this_.season_id as
  season3_1_0_, this_.goals as goals1_0_ from performances this_ where
  player1_.name ilike ?

But it will fail with SQLGrammarException : "Missing FROM clause for table player1_"

Body:
Your mapping is incorrect. An EmbeddableId class should contain @Id (thus Serializable) values, not mappings or complex types. You should move your mappings to your entity class, and then only include their id's in the EmbbedableId class. See the following example (from the JPA 2.2 specification)

@Embeddable
public class DependentId {
    String name;
    long empPK;   // corresponds to PK type of Employee
}

@Entity
public class Dependent {
    @EmbeddedId DependentId id;

    // id attribute mapped by join column default
    @MapsId("empPK") // maps empPK attribute of embedded id
    @ManyToOne Employee emp;
}


问:
seach in google via firefox's address bar - keyworld:URL does not exist
I'm used to search in google by typing keywords to my address bar. Now for some reason every word I'm typing is tried to interprete as a website. It is similar to google's "I'm feeling lucky" option, but with the difference that I can only type one word and only if it is writte correctly. Typing stackoverflow directed me to stackoverflow.com but rtackoverflow led to an error page.

In older versions we would enter about:config and change the value of keyword.URL.

I've already read that keyword.URL has no functionality anymore but this can be undone by installing FireFox - Addons like keyword.URL-HACK.
That did not work, because I don't have any keyword.URL in about:config!

答:
You don't need to install any addon for this.

You can turn on the web search in the address bar by changing a preference.
(Note: This preference does not affect smart keyword searches from the Location Bar)

In the address bar, type about:config and press Enter.

The about:config warning page (This might void your warranty!) may appear. Click I accept the risk! to continue to the about:config page.

In the Search field, type keyword.enabled.

Double-click the keyword.enabled preference to set its value to true.

By the way, the default value of keyword.enabled is true but I had accidentally changed it to false.

More details here


问:
How to create WPF/Silverlight module utilizing prism but also that can be embedded in non-prism applicationss
I want to have create a WPF or Silverlight module  which cannot only be utilised by Shell's bootstrapper, but also can be embedded in non-PRISM applications.

In short is there a way PRISM module can be intialised from module itself rather than initialsing from Shell?

Ulimate goal is to have WPF/Silverlight PRISM module, which can be initialsed by non-PRISM applications.

答:
It's a little more complicated than it appears at first glance, but it is doable.  I don't know if you are using Prism 4 yet, but if so, Microsoft actually provides guidance for this scenario:

http://msdn.microsoft.com/en-us/library/ff921109(v=PandP.40).aspx

There is a bit of project manipulation you need to do to get two projects running side-by-side.  There is a sample included with Prism v4 called "MultiTargeting" if you need to see a working sample.

Your question regarding to allowing a module to be initialized by itself, rather than having the orchestrating Shell / Bootstrapper is the wrong approach, however. Essentially what you would have would be two shells... one WPF and one Silverlight.  Take a look at the samples and see what you think.

Hope this helps.


问:
How to use python argparse with conditionally optional arguments?
Here is the current code.

```<code>import time
import collections
from modules import outputs
from modules import scrub
from modules import lookups

parser = argparse.ArgumentParser(description='AppMap Converter to Generate Asset Files from AppMapp Data')
parser.add_argument("operation", nargs='?', default="empty", help='The operation to perform')
parser.add_argument("input", nargs='?', default="empty", help='The input AppMapp File Path')
parser.add_argument("output", nargs='?', default="empty", help='The output Asset File Path')
args = parser.parse_args()

start = time.time()

if(args.operation == "Convert"):
    input_file_path = args.input
    output_file_path = args.output
    #DO LOTS OF STUFF
else:
    exit()
</code>```

The script is called sacsproc, so I run it from the command line as follows:

```<code>./sacsproc Convert input.csv output.csv
</code>```

This all works nicely, the problem is that I need more sacsproc commands which may have a totally different set of secondary parameters. i.e. one command might be:

```<code>./sacsproc Clean -rts input.csv output.csv err.csv
</code>```

Thus, I am trying to determine how one defines arguments that are conditional on the first argument? In my mind, I'm thinking about the zfs command line utilities that do what I am trying to do (e.g. zpool create mirror sdb sdc vs. zpool remove sda).

答:
use subparsers

```<code>subparsers = parser.add_subparsers(help="sub-command help")

group1 = subparsers.add_parser("something",help="do something")
group1.set_defaults(which="g1") # some default value (so you know which group was activated)
group1.add_argument("ARG",help='do something on ARG')

group2 = subparsers.add_parser("other",help="do something else")
group2.set_defaults(which="g2") # give some default value
group2.add_argument("ARG",help='do something else on ARG')
</code>```

ok ...

```<code>import argparse
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(help="sub-command help")
g1 = subparsers.add_parser("thing1",help="bind to a port and just echo back anything it gets ... with a prompt")
g1.set_defaults(which="g1")
g1.add_argument("input",help='the input file')
g1.add_argument("output",help='the output file')
g2 = subparsers.add_parser("thing2",help="create a bridge between two ports, this is useful for generating a logfile")
g2.set_defaults(which="g2")
g2.add_argument("input",help='thie input file')
g2.add_argument("output",help='the output file')
g2.add_argument("error",help="the err file")

def print_help(args):
    print "ARGS:",args
    try:
        parser.parse_args(args)
    except:
        print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n"

print_help(["-h"])
print_help(["thing1","-h"])
print_help(["thing2","-h"])
</code>```

Body:
Here is the current code.

import time
import collections
from modules import outputs
from modules import scrub
from modules import lookups

parser = argparse.ArgumentParser(description='AppMap Converter to Generate Asset Files from AppMapp Data')
parser.add_argument("operation", nargs='?', default="empty", help='The operation to perform')
parser.add_argument("input", nargs='?', default="empty", help='The input AppMapp File Path')
parser.add_argument("output", nargs='?', default="empty", help='The output Asset File Path')
args = parser.parse_args()

start = time.time()

if(args.operation == "Convert"):
    input_file_path = args.input
    output_file_path = args.output
    #DO LOTS OF STUFF
else:
    exit()

The script is called sacsproc, so I run it from the command line as follows:

./sacsproc Convert input.csv output.csv

This all works nicely, the problem is that I need more sacsproc commands which may have a totally different set of secondary parameters. i.e. one command might be:

./sacsproc Clean -rts input.csv output.csv err.csv

Thus, I am trying to determine how one defines arguments that are conditional on the first argument? In my mind, I'm thinking about the zfs command line utilities that do what I am trying to do (e.g. zpool create mirror sdb sdc vs. zpool remove sda).

Body:
use subparsers

subparsers = parser.add_subparsers(help="sub-command help")

group1 = subparsers.add_parser("something",help="do something")
group1.set_defaults(which="g1") # some default value (so you know which group was activated)
group1.add_argument("ARG",help='do something on ARG')

group2 = subparsers.add_parser("other",help="do something else")
group2.set_defaults(which="g2") # give some default value
group2.add_argument("ARG",help='do something else on ARG')

ok ...

import argparse
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(help="sub-command help")
g1 = subparsers.add_parser("thing1",help="bind to a port and just echo back anything it gets ... with a prompt")
g1.set_defaults(which="g1")
g1.add_argument("input",help='the input file')
g1.add_argument("output",help='the output file')
g2 = subparsers.add_parser("thing2",help="create a bridge between two ports, this is useful for generating a logfile")
g2.set_defaults(which="g2")
g2.add_argument("input",help='thie input file')
g2.add_argument("output",help='the output file')
g2.add_argument("error",help="the err file")

def print_help(args):
    print "ARGS:",args
    try:
        parser.parse_args(args)
    except:
        print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n"

print_help(["-h"])
print_help(["thing1","-h"])
print_help(["thing2","-h"])


问:
Git local repository for remote directory
I cannot find the answer to this anywhere. Is it possible to set up a local git repository for files on a webserver? I do not want to put the repo on the webserver because of a lack of space. </p>

答: Absolutely yes. The easiest way is to keep repository locally and just put code (only working directory) remotely using ftp/rsync. That's it. Your host do not need your repo.</p>


问:
While updating rows in a table taking long time after every sequence of update?
this is my table

```<code>CREATE TABLE `fa_nls_og` (
    `Incr_Dollar_YAG_pct_Chg` double(50,4) DEFAULT NULL,
    `Incr_U_YAG_pct_Chg` double(50,4) DEFAULT NULL,
    `Incr_U_YAG_Chg` double(50,4) DEFAULT NULL,
    `Incr_EQ_YAG_pct_Chg` double(50,4) DEFAULT NULL,
    `Incr_EQ_YAG_Chg` double(50,4) DEFAULT NULL,
    `Baseline_EQ_YAG_pct_Chg` double(50,4) DEFAULT NULL,
    `Baseline_EQ_YAG_Chg` double(50,4) DEFAULT NULL,
    `Baseline_Units_YAG_pct_Chg` double(50,4) DEFAULT NULL,
    `Baseline_Units_YAG_Chg` double(50,4) DEFAULT NULL,
    `Units_YAG_Period` double(50,4) DEFAULT NULL,
    `Units_YAG_pct_Chg` double(50,4) DEFAULT NULL,
    `Units_YAG_Chg` double(50,4) DEFAULT NULL,
    `PERIOD_YEAR` int(50) DEFAULT NULL,
    `CAT_NO` int(10) DEFAULT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8
    /*!50100 PARTITION BY RANGE (PERIOD_YEAR)
    SUBPARTITION BY KEY (CAT_NO) SUBPARTITIONS 12
   (PARTITION pytd VALUES LESS THAN (2) ENGINE = InnoDB,
    PARTITION p VALUES LESS THAN (200000) ENGINE = InnoDB,
    PARTITION p0 VALUES LESS THAN (201401) ENGINE = InnoDB,
    PARTITION p2 VALUES LESS THAN (201402) ENGINE = InnoDB,
    PARTITION p4 VALUES LESS THAN (201403) ENGINE = InnoDB,
    PARTITION p6 VALUES LESS THAN (201404) ENGINE = InnoDB,
    PARTITION p8 VALUES LESS THAN (201405) ENGINE = InnoDB,
    PARTITION p10 VALUES LESS THAN (201406) ENGINE = InnoDB,
    PARTITION p12 VALUES LESS THAN (201407) ENGINE = InnoDB,
    PARTITION p14 VALUES LESS THAN (201408) ENGINE = InnoDB,
    PARTITION p16 VALUES LESS THAN (201409) ENGINE = InnoDB,
    PARTITION p18 VALUES LESS THAN (201410) ENGINE = InnoDB,
    PARTITION p20 VALUES LESS THAN (201411) ENGINE = InnoDB,
    PARTITION p22 VALUES LESS THAN (201412) ENGINE = InnoDB,
    PARTITION p24 VALUES LESS THAN (201501) ENGINE = InnoDB,
    PARTITION p26 VALUES LESS THAN (201502) ENGINE = InnoDB,
    PARTITION p28 VALUES LESS THAN (201503) ENGINE = InnoDB,
    PARTITION p30 VALUES LESS THAN (201504) ENGINE = InnoDB,
    PARTITION p32 VALUES LESS THAN (201505) ENGINE = InnoDB,
    PARTITION p34 VALUES LESS THAN (201506) ENGINE = InnoDB,
    PARTITION p36 VALUES LESS THAN (201507) ENGINE = InnoDB,
    PARTITION p38 VALUES LESS THAN (201508) ENGINE = InnoDB,
    PARTITION p40 VALUES LESS THAN (201509) ENGINE = InnoDB,
    PARTITION p42 VALUES LESS THAN (201510) ENGINE = InnoDB,
    PARTITION p44 VALUES LESS THAN (201511) ENGINE = InnoDB,
    PARTITION p46 VALUES LESS THAN (201512) ENGINE = InnoDB,
    PARTITION p48 VALUES LESS THAN (201601) ENGINE = InnoDB,
    PARTITION p50 VALUES LESS THAN (201602) ENGINE = InnoDB,
    PARTITION p52 VALUES LESS THAN (201603) ENGINE = InnoDB,
    PARTITION p54 VALUES LESS THAN (201604) ENGINE = InnoDB,
    PARTITION p56 VALUES LESS THAN (201605) ENGINE = InnoDB,
    PARTITION p58 VALUES LESS THAN (201606) ENGINE = InnoDB,
    PARTITION p60 VALUES LESS THAN (201607) ENGINE = InnoDB,
    PARTITION p62 VALUES LESS THAN (201608) ENGINE = InnoDB,
    PARTITION p64 VALUES LESS THAN (201609) ENGINE = InnoDB,
    PARTITION p66 VALUES LESS THAN (201610) ENGINE = InnoDB,
    PARTITION p68 VALUES LESS THAN (201611) ENGINE = InnoDB,
    PARTITION p70 VALUES LESS THAN (201612) ENGINE = InnoDB,
    PARTITION p72 VALUES LESS THAN (201701) ENGINE = InnoDB,
    PARTITION p74 VALUES LESS THAN (201702) ENGINE = InnoDB,
    PARTITION p76 VALUES LESS THAN (201703) ENGINE = InnoDB,
    PARTITION p78 VALUES LESS THAN (201704) ENGINE = InnoDB,
    PARTITION p80 VALUES LESS THAN (201705) ENGINE = InnoDB,
    PARTITION p82 VALUES LESS THAN (201706) ENGINE = InnoDB,
    PARTITION p84 VALUES LESS THAN (201707) ENGINE = InnoDB,
    PARTITION p86 VALUES LESS THAN (201708) ENGINE = InnoDB,
    PARTITION p88 VALUES LESS THAN (201709) ENGINE = InnoDB,
    PARTITION p90 VALUES LESS THAN (201710) ENGINE = InnoDB,
    PARTITION p92 VALUES LESS THAN (201711) ENGINE = InnoDB,
    PARTITION p94 VALUES LESS THAN (201712) ENGINE = InnoDB,
    PARTITION p96 VALUES LESS THAN (201801) ENGINE = InnoDB,
    PARTITION p98 VALUES LESS THAN (201802) ENGINE = InnoDB,
    PARTITION p100 VALUES LESS THAN (201803) ENGINE = InnoDB,
    PARTITION p102 VALUES LESS THAN (201804) ENGINE = InnoDB,
    PARTITION p104 VALUES LESS THAN (201805) ENGINE = InnoDB,
    PARTITION p106 VALUES LESS THAN (201806) ENGINE = InnoDB,
    PARTITION p108 VALUES LESS THAN (201807) ENGINE = InnoDB,
    PARTITION p110 VALUES LESS THAN (201808) ENGINE = InnoDB,
    PARTITION p112 VALUES LESS THAN (201809) ENGINE = InnoDB,
    PARTITION p114 VALUES LESS THAN (201810) ENGINE = InnoDB,
    PARTITION p116 VALUES LESS THAN (201811) ENGINE = InnoDB,
    PARTITION p118 VALUES LESS THAN (201812) ENGINE = InnoDB,
    PARTITION p144 VALUES LESS THAN (201901) ENGINE = InnoDB,
    PARTITION p146 VALUES LESS THAN (201902) ENGINE = InnoDB,
    PARTITION p148 VALUES LESS THAN (201903) ENGINE = InnoDB,
    PARTITION p150 VALUES LESS THAN (201904) ENGINE = InnoDB,
    PARTITION p152 VALUES LESS THAN (201905) ENGINE = InnoDB,
    PARTITION p154 VALUES LESS THAN (201906) ENGINE = InnoDB,
    PARTITION p156 VALUES LESS THAN (201907) ENGINE = InnoDB,
    PARTITION p158 VALUES LESS THAN (201908) ENGINE = InnoDB,
    PARTITION p160 VALUES LESS THAN (201909) ENGINE = InnoDB,
    PARTITION p162 VALUES LESS THAN (201910) ENGINE = InnoDB,
    PARTITION p164 VALUES LESS THAN (201911) ENGINE = InnoDB,
    PARTITION p166 VALUES LESS THAN (201912) ENGINE = InnoDB,
    PARTITION p120 VALUES LESS THAN (202001) ENGINE = InnoDB,
    PARTITION p122 VALUES LESS THAN (202002) ENGINE = InnoDB,
    PARTITION p124 VALUES LESS THAN (202003) ENGINE = InnoDB,
    PARTITION p126 VALUES LESS THAN (202004) ENGINE = InnoDB,
    PARTITION p128 VALUES LESS THAN (202005) ENGINE = InnoDB,
    PARTITION p130 VALUES LESS THAN (202006) ENGINE = InnoDB,
    PARTITION p132 VALUES LESS THAN (202007) ENGINE = InnoDB,
    PARTITION p134 VALUES LESS THAN (202008) ENGINE = InnoDB,
    PARTITION p136 VALUES LESS THAN (202009) ENGINE = InnoDB,
    PARTITION p138 VALUES LESS THAN (202010) ENGINE = InnoDB,
    PARTITION p140 VALUES LESS THAN (202011) ENGINE = InnoDB,
    PARTITION p142 VALUES LESS THAN (202012) ENGINE = InnoDB
) */
</code>```

updates on one of the column where period year and catno

first update it takes 5 sec ,2nd time updating it takes 30 min , can anyone help it?

答:
Too many partitions.  After about 50, performance degrades.  (You have about 800!)

Don't pre-build partitions; it slows down operations.

SUBPARTITIONs have no performance benefit.

Don't use DOUBLE(m,n) it leads to extra rounding.  Either use plain DOUBLE (with 16 significant digits) or DECIMAL(m,n) with reasonable values for m and n.  DOUBLE (with or without (m,n)) takes 8 bytes; DECIMAL(50,4) takes about 25 bytes!

int(50) -- The (50) means nothing.  INT always takes 4 bytes.  Since it seems to be a YEAR, use that datatype (only 2 bytes).

Have a PRIMARY KEY

If that is your main query, have INDEX(period_year, catno).

After all of that, get rid of all partitioning -- it is not providing anything useful (based on what you have said so far).  The INDEX will give you the speed you are missing.  My other tips help in various other ways, some of them helping directly or indirectly (eg, small = faster) with speed.

Body:
this is my table

CREATE TABLE `fa_nls_og` (
    `Incr_Dollar_YAG_pct_Chg` double(50,4) DEFAULT NULL,
    `Incr_U_YAG_pct_Chg` double(50,4) DEFAULT NULL,
    `Incr_U_YAG_Chg` double(50,4) DEFAULT NULL,
    `Incr_EQ_YAG_pct_Chg` double(50,4) DEFAULT NULL,
    `Incr_EQ_YAG_Chg` double(50,4) DEFAULT NULL,
    `Baseline_EQ_YAG_pct_Chg` double(50,4) DEFAULT NULL,
    `Baseline_EQ_YAG_Chg` double(50,4) DEFAULT NULL,
    `Baseline_Units_YAG_pct_Chg` double(50,4) DEFAULT NULL,
    `Baseline_Units_YAG_Chg` double(50,4) DEFAULT NULL,
    `Units_YAG_Period` double(50,4) DEFAULT NULL,
    `Units_YAG_pct_Chg` double(50,4) DEFAULT NULL,
    `Units_YAG_Chg` double(50,4) DEFAULT NULL,
    `PERIOD_YEAR` int(50) DEFAULT NULL,
    `CAT_NO` int(10) DEFAULT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8
    /*!50100 PARTITION BY RANGE (PERIOD_YEAR)
    SUBPARTITION BY KEY (CAT_NO) SUBPARTITIONS 12
   (PARTITION pytd VALUES LESS THAN (2) ENGINE = InnoDB,
    PARTITION p VALUES LESS THAN (200000) ENGINE = InnoDB,
    PARTITION p0 VALUES LESS THAN (201401) ENGINE = InnoDB,
    PARTITION p2 VALUES LESS THAN (201402) ENGINE = InnoDB,
    PARTITION p4 VALUES LESS THAN (201403) ENGINE = InnoDB,
    PARTITION p6 VALUES LESS THAN (201404) ENGINE = InnoDB,
    PARTITION p8 VALUES LESS THAN (201405) ENGINE = InnoDB,
    PARTITION p10 VALUES LESS THAN (201406) ENGINE = InnoDB,
    PARTITION p12 VALUES LESS THAN (201407) ENGINE = InnoDB,
    PARTITION p14 VALUES LESS THAN (201408) ENGINE = InnoDB,
    PARTITION p16 VALUES LESS THAN (201409) ENGINE = InnoDB,
    PARTITION p18 VALUES LESS THAN (201410) ENGINE = InnoDB,
    PARTITION p20 VALUES LESS THAN (201411) ENGINE = InnoDB,
    PARTITION p22 VALUES LESS THAN (201412) ENGINE = InnoDB,
    PARTITION p24 VALUES LESS THAN (201501) ENGINE = InnoDB,
    PARTITION p26 VALUES LESS THAN (201502) ENGINE = InnoDB,
    PARTITION p28 VALUES LESS THAN (201503) ENGINE = InnoDB,
    PARTITION p30 VALUES LESS THAN (201504) ENGINE = InnoDB,
    PARTITION p32 VALUES LESS THAN (201505) ENGINE = InnoDB,
    PARTITION p34 VALUES LESS THAN (201506) ENGINE = InnoDB,
    PARTITION p36 VALUES LESS THAN (201507) ENGINE = InnoDB,
    PARTITION p38 VALUES LESS THAN (201508) ENGINE = InnoDB,
    PARTITION p40 VALUES LESS THAN (201509) ENGINE = InnoDB,
    PARTITION p42 VALUES LESS THAN (201510) ENGINE = InnoDB,
    PARTITION p44 VALUES LESS THAN (201511) ENGINE = InnoDB,
    PARTITION p46 VALUES LESS THAN (201512) ENGINE = InnoDB,
    PARTITION p48 VALUES LESS THAN (201601) ENGINE = InnoDB,
    PARTITION p50 VALUES LESS THAN (201602) ENGINE = InnoDB,
    PARTITION p52 VALUES LESS THAN (201603) ENGINE = InnoDB,
    PARTITION p54 VALUES LESS THAN (201604) ENGINE = InnoDB,
    PARTITION p56 VALUES LESS THAN (201605) ENGINE = InnoDB,
    PARTITION p58 VALUES LESS THAN (201606) ENGINE = InnoDB,
    PARTITION p60 VALUES LESS THAN (201607) ENGINE = InnoDB,
    PARTITION p62 VALUES LESS THAN (201608) ENGINE = InnoDB,
    PARTITION p64 VALUES LESS THAN (201609) ENGINE = InnoDB,
    PARTITION p66 VALUES LESS THAN (201610) ENGINE = InnoDB,
    PARTITION p68 VALUES LESS THAN (201611) ENGINE = InnoDB,
    PARTITION p70 VALUES LESS THAN (201612) ENGINE = InnoDB,
    PARTITION p72 VALUES LESS THAN (201701) ENGINE = InnoDB,
    PARTITION p74 VALUES LESS THAN (201702) ENGINE = InnoDB,
    PARTITION p76 VALUES LESS THAN (201703) ENGINE = InnoDB,
    PARTITION p78 VALUES LESS THAN (201704) ENGINE = InnoDB,
    PARTITION p80 VALUES LESS THAN (201705) ENGINE = InnoDB,
    PARTITION p82 VALUES LESS THAN (201706) ENGINE = InnoDB,
    PARTITION p84 VALUES LESS THAN (201707) ENGINE = InnoDB,
    PARTITION p86 VALUES LESS THAN (201708) ENGINE = InnoDB,
    PARTITION p88 VALUES LESS THAN (201709) ENGINE = InnoDB,
    PARTITION p90 VALUES LESS THAN (201710) ENGINE = InnoDB,
    PARTITION p92 VALUES LESS THAN (201711) ENGINE = InnoDB,
    PARTITION p94 VALUES LESS THAN (201712) ENGINE = InnoDB,
    PARTITION p96 VALUES LESS THAN (201801) ENGINE = InnoDB,
    PARTITION p98 VALUES LESS THAN (201802) ENGINE = InnoDB,
    PARTITION p100 VALUES LESS THAN (201803) ENGINE = InnoDB,
    PARTITION p102 VALUES LESS THAN (201804) ENGINE = InnoDB,
    PARTITION p104 VALUES LESS THAN (201805) ENGINE = InnoDB,
    PARTITION p106 VALUES LESS THAN (201806) ENGINE = InnoDB,
    PARTITION p108 VALUES LESS THAN (201807) ENGINE = InnoDB,
    PARTITION p110 VALUES LESS THAN (201808) ENGINE = InnoDB,
    PARTITION p112 VALUES LESS THAN (201809) ENGINE = InnoDB,
    PARTITION p114 VALUES LESS THAN (201810) ENGINE = InnoDB,
    PARTITION p116 VALUES LESS THAN (201811) ENGINE = InnoDB,
    PARTITION p118 VALUES LESS THAN (201812) ENGINE = InnoDB,
    PARTITION p144 VALUES LESS THAN (201901) ENGINE = InnoDB,
    PARTITION p146 VALUES LESS THAN (201902) ENGINE = InnoDB,
    PARTITION p148 VALUES LESS THAN (201903) ENGINE = InnoDB,
    PARTITION p150 VALUES LESS THAN (201904) ENGINE = InnoDB,
    PARTITION p152 VALUES LESS THAN (201905) ENGINE = InnoDB,
    PARTITION p154 VALUES LESS THAN (201906) ENGINE = InnoDB,
    PARTITION p156 VALUES LESS THAN (201907) ENGINE = InnoDB,
    PARTITION p158 VALUES LESS THAN (201908) ENGINE = InnoDB,
    PARTITION p160 VALUES LESS THAN (201909) ENGINE = InnoDB,
    PARTITION p162 VALUES LESS THAN (201910) ENGINE = InnoDB,
    PARTITION p164 VALUES LESS THAN (201911) ENGINE = InnoDB,
    PARTITION p166 VALUES LESS THAN (201912) ENGINE = InnoDB,
    PARTITION p120 VALUES LESS THAN (202001) ENGINE = InnoDB,
    PARTITION p122 VALUES LESS THAN (202002) ENGINE = InnoDB,
    PARTITION p124 VALUES LESS THAN (202003) ENGINE = InnoDB,
    PARTITION p126 VALUES LESS THAN (202004) ENGINE = InnoDB,
    PARTITION p128 VALUES LESS THAN (202005) ENGINE = InnoDB,
    PARTITION p130 VALUES LESS THAN (202006) ENGINE = InnoDB,
    PARTITION p132 VALUES LESS THAN (202007) ENGINE = InnoDB,
    PARTITION p134 VALUES LESS THAN (202008) ENGINE = InnoDB,
    PARTITION p136 VALUES LESS THAN (202009) ENGINE = InnoDB,
    PARTITION p138 VALUES LESS THAN (202010) ENGINE = InnoDB,
    PARTITION p140 VALUES LESS THAN (202011) ENGINE = InnoDB,
    PARTITION p142 VALUES LESS THAN (202012) ENGINE = InnoDB
) */

updates on one of the column where period year and catno

first update it takes 5 sec ,2nd time updating it takes 30 min , can anyone help it?


问:
C++ benchmarking, volatile
I'm trying to measure how long it takes to execute a function 'check()' using rdtsc as follows:

```<code>a = rdtsc();
check(pw);
b = rdtsc();

return (b-a);
</code>```

However, I am receiving very small time differences, which I think is due to my compiler (using G++, on windows) optimising the code. As 'check()' does not affect any other part of the program, I think the compiler is ignoring this call altogether.

I have read about using something called asm volatile to tell the compiler not to optimise a certain section of code, but I cannot figure out how to implement it.

Any help on this?

答:
1) You need run hundreds millions of iterations for receiving kinda avg. performance

2) DON'T benchmark such low-level  things, because it's almost not related to real world. Real task work billions CPU circles and single volatile can add just 0.000001% overhead... or may increase it by 100000%, if yours threads constantly accessing to  shared data. You may benchmark part of yours algorithm and then improve it, but not particular instructions.

Title: C++ benchmarking, volatile

Body:
I'm trying to measure how long it takes to execute a function 'check()' using rdtsc as follows:

a = rdtsc();
check(pw);
b = rdtsc();

return (b-a);

However, I am receiving very small time differences, which I think is due to my compiler (using G++, on windows) optimising the code. As 'check()' does not affect any other part of the program, I think the compiler is ignoring this call altogether.

I have read about using something called asm volatile to tell the compiler not to optimise a certain section of code, but I cannot figure out how to implement it.

Any help on this?


问:
String Fraction to Value in VBA
How can fraction as a string be converted to a numeric value?

```<code>strFrac = "3/2"
</code>```

Currently doing by splitting string to get numerator and denominator.

```<code>Dim x() As String
x = Split(strFrac, "/")
</code>```

Then using Val() and dividing.

```<code>v = Val(x(0)) / Val(x(1))
</code>```

result: v = 1.5

Is there a more direct approach?  Would be nice if something like Val("3/2") would work.

答:
Val doesn't really convert a string into a numeric. It stops reading a string when it encounters a non-numeric character, and returns a Double representing the numeric value extracted from the string.

That "works" for your purposes, but the CDbl conversion function would be more appropriate.

If you're in Excel, Scott's answer leverages Excel's computing engine to literally Evaluate the string, which is what you're looking for. A side-effect of that is that the string can now contain Excel functions and cell references, and the result will still get evaluated.

If the evaluation returns an error value (e.g. Evaluate("12/0")), then you'll run into type issues if you assign the result directly to a Double. Instead, assign the result to a Variant, and validate that it's not returning an error using the IsError function - that will spare you from run-time error 13 / "type mismatch".

If you're not in Excel, you can't do that - and you don't want to reference the Excel object model just for that either - so your solution is indeed the simplest.

Title: String Fraction to Value in VBA

Body:
How can fraction as a string be converted to a numeric value?

strFrac = "3/2"

Currently doing by splitting string to get numerator and denominator.

Dim x() As String
x = Split(strFrac, "/")

Then using Val() and dividing.

v = Val(x(0)) / Val(x(1))

result: v = 1.5

Is there a more direct approach?  Would be nice if something like Val("3/2") would work.


问:
type/value mismatch while declaring custom comparator in a class
I have a problem with the following class. I get error "Tree.cpp:12:56: error: type/value mismatch at argument 2 in template parameter list for ‘template class std::multiset’ // Tree.cpp:12:56: note:   expected a type, got ‘(Tree::compare < )’". I don't understand how I should pass the comparator type in the multiset declaration. Could you help me?</p>

```<code>#include <set>
#include <deque>
#include <iostream>
using namespace std;

template <typename T>
class Tree
{
    typedef typename std::multiset<Tree<T>*, typename Tree<T>::compare > NodeSet;

private:
    NodeSet children;
    T content;

public:
    struct compare
    {
        bool operator()( const Tree*& t1, const Tree*& t2 ) const
        {
            cout << "Comparing " << t1->GetContent() << " vs " << t2->GetContent() << endl;
            return t1->GetContent() < t2->GetContent();
        }
    };
    Tree& AppendNode( const T& node )
    {
        Tree* t = new Tree( node );
        AttachTree( t );
        return *t;
    }
    void Clear()
    {
        typename NodeSet::iterator it = children.begin();
        while( children.size() != 0 && children.end() != it )
        {

            children.erase( *it );
            delete *it;
            it++;
        }
    }
    Tree( const T& root )
    {
        content = root;
    }
    void AttachTree( Tree* t )
    {
        children.insert( t );
    }
    void Visit( std::deque<T>& exp ) const
    {
        exp.push_back( content );
        typename NodeSet::iterator it = children.begin();
        while( it != children.end() )
        {
            ( *it )->Visit( exp ); it++;
        }
    }
    Tree()
    {}
    Tree( Tree& c )
    {
        c.DeepCopyTo( this );
    }
    T& operator =( const Tree& b )
    {
        b.DeepCopyTo( this );
    }
    ~Tree()
    {
        cout << "in destructor for" << this << endl;
        Clear();
    }
    void DeepCopyTo( Tree* dest ) const
    {
        dest->content = content;
        typename NodeSet::iterator it = children.begin();
        while( it != children.end() )
        {
            Tree* t = new Tree();
            ( *it )->DeepCopyTo( t );
            dest->AttachTree( t );
            it++;
        }
    }
    void Print()
    {
        typename NodeSet::iterator it = children.begin();
        while( it != children.end() )
        {
            cout << *it << ",";
            it++;
        }
    }
};

int main()
{
    Tree<int> tree( 8 );
    tree.AppendNode( 5 );
}
</code>```

答:
You might want to change this line to

```<code>typedef
    typename std::multiset<Tree*, typename Tree::compare >
    NodeSet;
</code>```

Note that compare is a dependent name, so you need to use typename.

Also, you should consider moving the struct compare above this line, as this line references it.

Two more things to notice.

You might want to change compare to

```<code>struct compare {
    bool operator()(const Tree* t1, const Tree* t2) const {
    cout << "Comparing " <<t1->GetContent() <<" vs "<<t2->GetContent()<<endl;
        return t1->GetContent() < t2->GetContent();
    }
};
</code>```

unfortunately, GetContent doesn't seem defined anywhere in your code.

Body:
I have a problem with the following class. I get error "Tree.cpp:12:56: error: type/value mismatch at argument 2 in template parameter list for ‘template class std::multiset’ // Tree.cpp:12:56: note:   expected a type, got ‘(Tree::compare < )’". I don't understand how I should pass the comparator type in the multiset declaration. Could you help me?

#include <set>
#include <deque>
#include <iostream>
using namespace std;

template <typename T>
class Tree
{
    typedef typename std::multiset<Tree<T>*, typename Tree<T>::compare > NodeSet;

private:
    NodeSet children;
    T content;

public:
    struct compare
    {
        bool operator()( const Tree*& t1, const Tree*& t2 ) const
        {
            cout << "Comparing " << t1->GetContent() << " vs " << t2->GetContent() << endl;
            return t1->GetContent() < t2->GetContent();
        }
    };
    Tree& AppendNode( const T& node )
    {
        Tree* t = new Tree( node );
        AttachTree( t );
        return *t;
    }
    void Clear()
    {
        typename NodeSet::iterator it = children.begin();
        while( children.size() != 0 && children.end() != it )
        {

            children.erase( *it );
            delete *it;
            it++;
        }
    }
    Tree( const T& root )
    {
        content = root;
    }
    void AttachTree( Tree* t )
    {
        children.insert( t );
    }
    void Visit( std::deque<T>& exp ) const
    {
        exp.push_back( content );
        typename NodeSet::iterator it = children.begin();
        while( it != children.end() )
        {
            ( *it )->Visit( exp ); it++;
        }
    }
    Tree()
    {}
    Tree( Tree& c )
    {
        c.DeepCopyTo( this );
    }
    T& operator =( const Tree& b )
    {
        b.DeepCopyTo( this );
    }
    ~Tree()
    {
        cout << "in destructor for" << this << endl;
        Clear();
    }
    void DeepCopyTo( Tree* dest ) const
    {
        dest->content = content;
        typename NodeSet::iterator it = children.begin();
        while( it != children.end() )
        {
            Tree* t = new Tree();
            ( *it )->DeepCopyTo( t );
            dest->AttachTree( t );
            it++;
        }
    }
    void Print()
    {
        typename NodeSet::iterator it = children.begin();
        while( it != children.end() )
        {
            cout << *it << ",";
            it++;
        }
    }
};

int main()
{
    Tree<int> tree( 8 );
    tree.AppendNode( 5 );
}

Body:
You might want to change this line to

typedef
    typename std::multiset<Tree*, typename Tree::compare >
    NodeSet;

Note that compare is a dependent name, so you need to use typename.

Also, you should consider moving the struct compare above this line, as this line references it.

Two more things to notice.

You might want to change compare to

struct compare {
    bool operator()(const Tree* t1, const Tree* t2) const {
    cout << "Comparing " <<t1->GetContent() <<" vs "<<t2->GetContent()<<endl;
        return t1->GetContent() < t2->GetContent();
    }
};

unfortunately, GetContent doesn't seem defined anywhere in your code.


问:
Is adding async to a method signature a breaking change?
In addressing a question about how much to use async/await, i.e. "should all methods return Task?", the author of this answer, Matías Fidemraizer, claims that, even if your method currently only does synchronous stuff, it should still return a task so if you make it do async stuff later, "you can turn it into actual async operations without affecting the entire code base".  That makes sense, but if I'm actually awaiting something, I have to add async to the method signature.  So we're talking about going from:

```<code>public Task WhateverAsync()
{
    return Task.FromResult(true);
}
</code>```

to

```<code>public async Task WhateverAsync()
{
    return await AwaitableSomething();
}
</code>```

Is adding async to a method signature a breaking change?

答:
even if your method currently only does synchronous stuff, it should still return a task

I disagree. If your method is synchronous, then it should have a synchronous API. If your method is asynchronous, then it should have an asynchronous API.

However, I would agree that synchronous methods should have a Task-returning signature if they are defined in an interface / base class and there is a decent possibility that future implementations / overrides may want to use await.

Is adding async to a method signature a breaking change?

Just adding async? No, it is not. Consider the case of a Task-returning method defined in an interface: it may be implemented either with or without async.

However, there are some possible differences in semantics, as I describe on my blog. The most notable is that the exception handling is different. If you're not careful, a naive synchronous implementation could throw an exception directly, rather than returning a faulted task. As soon as you make that method async, the exception would be faulting a task, and no longer thrown directly.

So, it's really a question about possible changes in semantics. I would argue that the naive synchronous semantics were wrong, since the method had an asynchronous signature. E.g., the synchronous method has an asynchronous signature, so it is reasonable for callers to assume that it will catch exceptions and return a faulted task. So, if the synchronous implementations have these (easy-to-cause) bugs, then adding async would technically be a breaking change.

Body:
In addressing a question about how much to use async/await, i.e. "should all methods return Task?", the author of this answer, Matías Fidemraizer, claims that, even if your method currently only does synchronous stuff, it should still return a task so if you make it do async stuff later, "you can turn it into actual async operations without affecting the entire code base".  That makes sense, but if I'm actually awaiting something, I have to add async to the method signature.  So we're talking about going from:

public Task WhateverAsync()
{
    return Task.FromResult(true);
}

to

public async Task WhateverAsync()
{
    return await AwaitableSomething();
}

Is adding async to a method signature a breaking change?