问:
How to manage configuration for Webpack/Electron app?
I am using Webpack 2 and Electron to build nodejs application on Mac.

In my project in the root I have directory 'data' where I store configuration in a json like data/configurations/files.json (in practices there are different files with dynamic names)

After webpackaing though when I call: fs.readdirSync(remote.app.getAppPath()); to get files in the root I get only these packed: [ "default_app.js", "icon.png", "index.html", "main.js", "package.json", "renderer.js" ]

path.join(remote.app.getAppPath(), 'data/tests/groups.json'); called with FS ReadSync leads to an issue Error: ENOENT, data/tests/groups.json not found in /Users/myuser/myproject/node_modules/electron/dist/Electron.app/Contents/Resources/default_app.asar. So it seems that the whole data folder is not picked up by webpacker.

Webpack config is using json-loader and I did not find any documentation mentioning anything special about including specific files or jsons. Or do I have to reference json files in my code differently as they might be packed under main.js.

What is the best practice for Electron/Webpack for managing JSON config files? Am I doing something wrong when webpacking the project?

My project is based of https://github.com/SimulatedGREG/electron-vue using webpack/electron/vue

答:
I think the confusion, (if there is any), might come from the fact that webpack not only "packs", embeds, things, code, etc... but also process content with its plugins.

html plugin being a good example, as it simply generates an html file at build-time.

And how this relates to the config file issue?,
well depending on how you are "requiring" the "config" file, what plug-in you are using to process that content.

You could be embedding it, or simply loading it as text, from file system or http, or else...

In the case of a config file, that I guess you want it to be parsed at runtime,

otherwise it's just fancy hardcoding values that perhaps you could be better simply typing it in your source code as simple objects.

And again in that case I think webpack adds little to nothing to the runtime needs, as there is nothing to pre-pack to read at later use,

so I would possibly instead or "require"it,  i'll read it from the file system, with something like :

```<code>// read it parse it relative to appPath/cwd,
const config = JSON.parse(
    fs.readfileSync(
        path.join( app.getAppPath(), "config.json" ),
        "utf-8"
    ))
//note: look fs-extra, it does all that minus the app.path plus async
</code>```

and electron will read it from the file system , or if using Electron.require will read it from  asar|fileSystem (in that order if I remember correctly, I could be wrong),

Body:
I think the confusion, (if there is any), might come from the fact that webpack not only "packs", embeds, things, code, etc... but also process content with its plugins.

html plugin being a good example, as it simply generates an html file at build-time.

And how this relates to the config file issue?,
well depending on how you are "requiring" the "config" file, what plug-in you are using to process that content.

You could be embedding it, or simply loading it as text, from file system or http, or else...

In the case of a config file, that I guess you want it to be parsed at runtime,

otherwise it's just fancy hardcoding values that perhaps you could be better simply typing it in your source code as simple objects.

And again in that case I think webpack adds little to nothing to the runtime needs, as there is nothing to pre-pack to read at later use,

so I would possibly instead or "require"it,  i'll read it from the file system, with something like :

// read it parse it relative to appPath/cwd,
const config = JSON.parse(
    fs.readfileSync(
        path.join( app.getAppPath(), "config.json" ),
        "utf-8"
    ))
//note: look fs-extra, it does all that minus the app.path plus async

and electron will read it from the file system , or if using Electron.require will read it from  asar|fileSystem (in that order if I remember correctly, I could be wrong),


来源: stackexchange

问:
jekyll page build failure
I'm new to web development, so please bear with me.

I'm trying to create a website for a group project using Github Pages, and I have forked this repository. I've made several changes, and the website was up and running. Today I updated some images and the website wouldn't build anymore. I tried reverting to the previous commit, but it wouldn't build either. I read the troubleshooting page, to no avail. I don't have any idea of what to do anymore, please help.

the error:

The page build failed with the following error:

Page build failed. For more information, see help[dot]github.com/articles/troubleshooting-github-pages-build-failures.

For information on troubleshooting Jekyll see:

help[dot]github.com/articles/troubleshooting-jekyll-builds

If you have any questions you can contact us by replying to this email.

I'm using the web interface of github (not ideal, I know). the repository is here.

答:
If your problem is similar to mine you should've gotten an email similar to this.

<----------------------------------------------------------/>
The page build failed for the master branch with the following error:

unable to build page. Please try again later.

For information on troubleshooting Jekyll see:

https://help.github.com/articles/troubleshooting-jekyll-builds

If you have any questions you can contact us by replying to this email.
< ---------------------------------------------------------/>

While you can and should use the link provided by @cameronHurd - twitter.com/githubstatus/status/789452827269664769
and by @brunocuconato - https://status.github.com/ to see if there was an error during your build, you can also email support@github.com and they will be able to manually rebuild your site. Simply reply to the email you were sent and maybe include a link to your repo. I tried waiting until things were fixed and found this to be a much better solution. You can also reach out to GitHub on twitter but I'm not sure about the response speed on there.

ContentLicense: CC BY-SA 3.0

Title: jekyll page build failure


问:
Run bat file from different disk with java
Im trying to run a bat from C:/abc/def/coolBat.bat but my java workspace is in D:/

I've tried with :

```<code>String cmd = "cmd /c /start C:/abc/def/coolBat.bat";
Runtime.getRuntime().exec(cmd);
</code>```

But didn't work, so I tried this

```<code>String[] command = { "cmd.exe", "/C", "C:/abc/def/coolBat.bat" };
Runtime.getRuntime().exec(cmd);
</code>```

didnt work either. Tried this too

```<code>Executor exec = new DefaultExecutor();
exec.setWorkingDirectory(new File("C:/abc/def"));
CommandLine cl = new CommandLine("coolBat.bat");
int exitvalue = exec.execute(cl);
</code>```

Says it cant find the file.

Tried something like this too:

```<code>Runtime.getRuntime().exec("cmd cd /d C:/abc/def/ && coolBat.bat");
</code>```

And nothing. The weird thing is that this command:

```<code>cd /d C:/abc/def/ && coolBat.bat
</code>```

Works when i do it in cmd. Its worth saying that the bat file copies some files to another directory, all inside C:/

EDITED N°1

```<code>CD C:\abc\def\MN
copy almn + ctmn + bamn C:\abc\def\mn_sf.txt
CD C:\abc\def\ME
copy alme + ctme + bame  C:\abc\def\me_sf.txt
CD C:\abc\def\
if exist MN.txt del MN.txt
if exist ME.txt del ME.txt
if exist JUZ.txt del JUZ.txt
if exist FUNC.txt del FUNC.txt
if exist AHO.txt del AHO.txt
CD C:\
</code>```

答:
Allow MS Windows to use the associated application to run your batch file (or any other application):

Required Imports:

```<code>import java.awt.Desktop;
</code>```

Here is code you can try:

```<code>String filePath = "C:/abc/def/coolBat.bat";

if (Desktop.isDesktopSupported()) {
    try {
        File myFile = new File(filePath);
        Desktop.getDesktop().open(myFile);
    }
    catch (IOException | IllegalArgumentException ex) {
        System.err.println("Either there is no application found "
            + "which is associatd with\nthe file you want to work with or the "
            + "file doesn't exist!\n\n" + filePath);
    }
}
</code>```

Body:
Im trying to run a bat from C:/abc/def/coolBat.bat but my java workspace is in D:/

I've tried with :

String cmd = "cmd /c /start C:/abc/def/coolBat.bat";
Runtime.getRuntime().exec(cmd);

But didn't work, so I tried this

String[] command = { "cmd.exe", "/C", "C:/abc/def/coolBat.bat" };
Runtime.getRuntime().exec(cmd);

didnt work either. Tried this too

Executor exec = new DefaultExecutor();
exec.setWorkingDirectory(new File("C:/abc/def"));
CommandLine cl = new CommandLine("coolBat.bat");
int exitvalue = exec.execute(cl);

Says it cant find the file.

Tried something like this too:

Runtime.getRuntime().exec("cmd cd /d C:/abc/def/ && coolBat.bat");

And nothing. The weird thing is that this command:

cd /d C:/abc/def/ && coolBat.bat

Works when i do it in cmd. Its worth saying that the bat file copies some files to another directory, all inside C:/

EDITED N°1

CD C:\abc\def\MN
copy almn + ctmn + bamn C:\abc\def\mn_sf.txt
CD C:\abc\def\ME
copy alme + ctme + bame  C:\abc\def\me_sf.txt
CD C:\abc\def\
if exist MN.txt del MN.txt
if exist ME.txt del ME.txt
if exist JUZ.txt del JUZ.txt
if exist FUNC.txt del FUNC.txt
if exist AHO.txt del AHO.txt
CD C:\

Body:
Allow MS Windows to use the associated application to run your batch file (or any other application):

Required Imports:

import java.awt.Desktop;

Here is code you can try:

String filePath = "C:/abc/def/coolBat.bat";

if (Desktop.isDesktopSupported()) {
    try {
        File myFile = new File(filePath);
        Desktop.getDesktop().open(myFile);
    }
    catch (IOException | IllegalArgumentException ex) {
        System.err.println("Either there is no application found "
            + "which is associatd with\nthe file you want to work with or the "
            + "file doesn't exist!\n\n" + filePath);
    }
}


问:
How to use app.all to send req.path to a different domain?
In my current environment, this works:

```<code>router.get("/test", function(req,res,next){
    request({
        uri: 'http://my_virtual_machine:8080/rest/stuff/test',
    }).pipe(res)
})
</code>```

This works in that, when I send a request to http://localhost:3000/test I get the expected response from http://my_virtual_machine:8080/rest/stuff/test/. But, I'd rather not rewrite every single api.

Is there a way to simply pass req.path along to the VM?

I tried this:

```<code>router.all("*", function(req,res,next){
    request({
        uri: 'http://my_virtual_machine:8080/' + req.path,
    }).pipe(res)
})
</code>```

But when I request http://localhost:3000/test I get this error -

GET http://localhost:3000/test 404 (Not Found)

Also, I have to send all the HTTP commands (GET, POST, PUT, etc), that's why I'm using all, as it was my understanding that all "matches all HTTP verbs" [doc].

答:
I changed router.all to router.use, and removed the path parameter. This worked is what worked:

```<code>router.use(function(req,res,next){
    request({
        uri: 'http://my_virtual_machine:8080' + req.path,
    }).pipe(res)
})
</code>```

Thanks to @yBrodosky for his comment which led me in the right direction. After reading the docs for router.use I saw that when it has no path parameter, it applies to all urls. And since I am using this as strictly a conduit for VM access (in order to apply an access-control header), that is what I had to do.

Body:
In my current environment, this works:

router.get("/test", function(req,res,next){
    request({
        uri: 'http://my_virtual_machine:8080/rest/stuff/test',
    }).pipe(res)
})

This works in that, when I send a request to http://localhost:3000/test I get the expected response from http://my_virtual_machine:8080/rest/stuff/test/. But, I'd rather not rewrite every single api.

Is there a way to simply pass req.path along to the VM?

I tried this:

router.all("*", function(req,res,next){
    request({
        uri: 'http://my_virtual_machine:8080/' + req.path,
    }).pipe(res)
})

But when I request http://localhost:3000/test I get this error -

GET http://localhost:3000/test 404 (Not Found)

Also, I have to send all the HTTP commands (GET, POST, PUT, etc), that's why I'm using all, as it was my understanding that all "matches all HTTP verbs" [doc].

Body:
I changed router.all to router.use, and removed the path parameter. This worked is what worked:

router.use(function(req,res,next){
    request({
        uri: 'http://my_virtual_machine:8080' + req.path,
    }).pipe(res)
})

Thanks to @yBrodosky for his comment which led me in the right direction. After reading the docs for router.use I saw that when it has no path parameter, it applies to all urls. And since I am using this as strictly a conduit for VM access (in order to apply an access-control header), that is what I had to do.


问:
Best Opensource Online Task Management/Project manager?
Best Online Open source Project manager/Task Manager???</p>

答:
Been quite impressed by Redmine myself.
There are hosting providers.</p>

ContentLicense: CC BY-SA 2.5


问:
Use JavaScript to place cursor at end of text in text input element
What is the best way (and I presume simplest way) to place the cursor at the end of the text in a input text element via JavaScript - after focus has been set to the element?</p>

答:
If you set the value first and then set the focus, the cursor will always appear at the end.

```<code>$("#search-button").click(function (event) {
    event.preventDefault();
    $('#textbox').val('this');
    $("#textbox").focus();
    return false;
});
</code>```

Here is the fiddle to test
https://jsfiddle.net/5on50caf/1/

OwnerDisplayName: Peanut

Body:
If you set the value first and then set the focus, the cursor will always appear at the end.

$("#search-button").click(function (event) {
    event.preventDefault();
    $('#textbox').val('this');
    $("#textbox").focus();
    return false;
});

Here is the fiddle to test
https://jsfiddle.net/5on50caf/1/


问:
Job Scheduling Service
I want to have a listener or a service which runs when a user takes a photo or video. That service then goes and finds the URI of the image/video the user takes, and records information about it. Previously I used a BroadcastListener, listening for the intent ACTION_NEW_PICTURE. However, in https://developer.android.com/about/versions/nougat/android-7.0-changes.html they deprecated this and suggest to use a JobScheduler instead. I haven't found any simple examples of JobScheduler being implemented within Xamarin so if somebody could explain how they would work in my scenario that would be ideal. The condition that would need to be met for a job to be processed would be if the URI of the photo location changes, therefore I'm guessing there is a need for a content observer.

答:
A little late to the party, but I hate unanswered questions.

There's now an example on the Xamarin site of how to use the Job Scheduler:

https://developer.xamarin.com/samples/monodroid/android5.0/JobScheduler/

Title: Job Scheduling Service


问:
Encountering Kerberos and/or NTLM authentication failures in custom application packages written using the WISE packaging Installer
We are encountering Kerberos and/or NTLM authentication failures in custom application packages orinally designed for Windows 7 using the WISE packaging Installer.  On Windows 7 they work fine but they now fail on Windows 10.  They fail both during installations on Windows 10 using the Microsoft SCCM tool, and they fail specifically when using Kerberos authentication to an SMB Share on the network durign the installation process.  We can see inside the network trace that the client application fails over to NTLM from Kerberos durign the authentcation transaction.  We are unsure why.  We have a large scale Active Directory environment. Because the WISE package is comiled we cannot look into it.  On successful Windows 7 machines, it appears the computer requires access to the Share while the package is being executed and the loggged-in user must have read and execute access on the SMB Share.  We are able to access the same SMB Share using the Windows 7 system account but not when using the Windows 10 system account.  Very odd!  Is this a code issue inside the package?  This may be important:  The SMB share is using an DNS alias, not sure if this makes any difference.  The real name of the host is different.  When using the real name of the host instead of the alias the access issue appears to be resolved.

答:
The network share wouldn't happen to be hosted by a non-Windows server by any chance, would it?  If so, see if this article applies:

SMB file server share access is unsuccessful through DNS CNAME alias

Basically there was a change in the security model of Windows 10.  Windows 10 by default won't request a Kerberos ticket for a DNS alias, but Windows 7 will.  The SMB server is basically saying since you're not using my actual name (as shown by the service ticket), I won't allow the connection.  Create a new SPN using the name that the successful Windows 7 machines are connecting with, but in SPN form.  For example, if a Windows 7 is using something like this:

\servername.domain.com\sharename

..then find that name of the AD computer object representing the host and add a secondary SPN to that AD object like so:

HOST/servername.domain.com


问:
IntelliJ IDEA android scala application
I am trying to make an android app in IntelliJ IDEA using scala. I made an android module and a scala module. I'm just after a little hello world for starters.
I added the scala module as a dependency for the android module but when I builde the project("make project") or try to run the thing I get this error:

trouble writing output: format == null

Does anyone know what the problem is?

P.S. In netbeans I can't even add anything as a resource for an android project.

Could it be that this is not the way to do it, do I need to modify the main module's ant script or something? Any pointers are welcomed.

答: I've programmed some android with scala using intellij. However I chose not to use intellij for compilation. Instead I used sbt (http://code.google.com/p/simple-build-tool/) with sbt android plugin (https://github.com/jberkel/android-plugin) for building and sbt idea processor (https://github.com/mpeltonen/sbt-idea) to create project files for idea.</p>

Title: IntelliJ IDEA android scala application


问:
Using Angular "track by $ index" with pagination, filtering and sorting not working
I'm having a problem when trying to use the Smart Table with paging, filtering and searching in my table.

I was working with the table when converting a JSON that consumed a request to an object. In this case, I did:

```<code>$scope.estoque = JSON.parse(data.data);
</code>```

The problem came when I needed to include paging, sorting, and searching. Then using the Smart Table, which until then had been serving me in what I needed.

In case, to use the functionality of it, my table array can not be object as it was previously, it needs to be JSON. Which in the case has the format below:

```<code> $scope.estoqueJSON = data.data;

[
  {
    "EstoqueId": 553,
    "DescricaoEstoque": null,
    "NomeMaterial": "Cabo de Fibra Óptica 04FO Multimodo - Indoor / Outdoor - 62,5/125 Furukawa",
    "CodigoMaterial": "100",
    "Ni": "",
    "QtdMaterial": 3.0,
    "QtdMin": 0.0,
    "Unidade": "m",
    "MaterialId": 1
  }
]
</code>```

Following the tutorial in Smart Table documentation, I created the table below:

```<code><table st-table="estoqueStr" st-set-filter="myStrictFilter" class="table table-striped table-responsive">
                <thead style="text-align:center;">
                    <tr>
                        <th st-sort="CodigoMaterial" style="width:20px; font-weight:bold; text-align:center;">Código</th>
                        <th st-sort="Ni" style="width:20px; font-weight:bold; text-align:center;">Ni</th>
                        <th st-sort="NomeMaterial" style="width:20px; font-weight:bold; text-align:center;">Material</th>
                        <th st-sort="Unidade" style="width:20px; font-weight:bold; text-align:center;">UNI.</th>
                        <th st-sort="QtdMaterial" style="width:20px; font-weight:bold; text-align:center;">Qtd</th>
                        <th st-sort="QtdMin" style="width:20px; font-weight:bold; text-align:center;">Qtd Min.</th>
                    </tr>
                    <tr>
                        <th style="width:20px;">
                            <input style="text-align:center;" st-search="CodigoMaterial" placeholder="Código material" class="input-sm form-control" type="search" />
                        </th>
                        <th style="width:20px; text-align:center;">
                            <input style="text-align:center;" st-search="Ni" placeholder="Ni" class="input-sm form-control" type="search" />
                        </th>
                        <th style="width:auto; text-align:center;">
                            <input style="text-align:center;" st-search="NomeMaterial" placeholder="Nome material" class="input-sm form-control" type="search" />
                        </th>
                        <th style="width:10px; text-align:center;">
                            <input style="text-align:center;" st-search="Unidade" placeholder="Unidade" class="input-sm form-control" type="search" />
                        </th>
                        <th style="width:10px; text-align:center;">
                            <input style="text-align:center;" st-search="QtdMaterial" placeholder="Qtde atual" class="input-sm form-control" type="search" />
                        </th>
                        <th style="width:10px; text-align:center;">
                            <input style="text-align:center;" st-search="QtdMin" placeholder="Qtde mínima" class="input-sm form-control" type="search" />
                        </th>

                    </tr>
                </thead>
                <tbody id="" class="">
                    <tr ng-repeat="e in estoqueJSON | filter : paginate | orderBy:sortType:sortReverse | filter:searchField track by $index">
                        <td ng-repeat-start="item in e.value"></td>
                        <td style="text-align:center;">{{item.CodigoMaterial}}</td>
                        <td style="text-align:center;">{{item.Ni}}</td>
                        <td>{{item.NomeMaterial}}</td>
                        <td style="text-align:center;">{{item.Unidade}}</td>
                        <td style="text-align:right; color:black;">
                            <span e-form="tableform" editable-number="e.QtdMaterial" onbeforesave="checkQtdEstoque(e, $data)">{{item.QtdMaterial}}</span>
                        </td>
                        <td style="text-align-last:right; color:black;" ng-repeat-end>
                            <span editable-number="e.QtdMin" e-form="tableform" onbeforesave="checkQtdMin(e, $data)">{{item.QtdMin}}</span>
                        </td>

                    </tr>
                </tbody>
            </table>
</code>```

I do not know why it's not showing any bug in the console, and also does not display the JSON data in my table. Can anyone tell me what I'm doing wrong?

AngularJS: 1.3

UPDATE

Ero answer was right, I just need to convert again my array for object, and then use ng-repeat. I'm still with Smart Table erro for filter (what doesn't work for object array), but I think it's plugin error and I will check on the github forum.

答:
Since the objects have unique identifier property, EstoqueId, use that for tracking instead of $index:

```<code><tr ng-repeat="e in estoqueJSON | filter : paginate | orderBy:sortType:sortReverse | filter:searchField track by e.EstoqueId">
</code>```

From the Docs:

If you are working with objects that have a unique identifier property, you should track by this identifier instead of the object instance [or $index]. Should you reload your data later, ngRepeat will not have to rebuild the DOM elements for items it has already rendered, even if the JavaScript objects in the collection have been substituted for new ones. For large collections, this significantly improves rendering performance.

— AngularJS ng-repeat Directive API Reference - Tracking

Body:
I'm having a problem when trying to use the Smart Table with paging, filtering and searching in my table.

I was working with the table when converting a JSON that consumed a request to an object. In this case, I did:

$scope.estoque = JSON.parse(data.data);

The problem came when I needed to include paging, sorting, and searching. Then using the Smart Table, which until then had been serving me in what I needed.

In case, to use the functionality of it, my table array can not be object as it was previously, it needs to be JSON. Which in the case has the format below:

 $scope.estoqueJSON = data.data;

[
  {
    "EstoqueId": 553,
    "DescricaoEstoque": null,
    "NomeMaterial": "Cabo de Fibra Óptica 04FO Multimodo - Indoor / Outdoor - 62,5/125 Furukawa",
    "CodigoMaterial": "100",
    "Ni": "",
    "QtdMaterial": 3.0,
    "QtdMin": 0.0,
    "Unidade": "m",
    "MaterialId": 1
  }
]

Following the tutorial in Smart Table documentation, I created the table below:

                        Código
                        Ni
                        Material
                        UNI.
                        Qtd
                        Qtd Min.

                            <input style="text-align:center;" st-search="CodigoMaterial" placeholder="Código material" class="input-sm form-control" type="search" />

                            <input style="text-align:center;" st-search="Ni" placeholder="Ni" class="input-sm form-control" type="search" />

                            <input style="text-align:center;" st-search="NomeMaterial" placeholder="Nome material" class="input-sm form-control" type="search" />

                            <input style="text-align:center;" st-search="Unidade" placeholder="Unidade" class="input-sm form-control" type="search" />

                            <input style="text-align:center;" st-search="QtdMaterial" placeholder="Qtde atual" class="input-sm form-control" type="search" />

                            <input style="text-align:center;" st-search="QtdMin" placeholder="Qtde mínima" class="input-sm form-control" type="search" />

                        {{item.CodigoMaterial}}
                        {{item.Ni}}
                        {{item.NomeMaterial}}
                        {{item.Unidade}}

                            {{item.QtdMaterial}}

                            {{item.QtdMin}}

I do not know why it's not showing any bug in the console, and also does not display the JSON data in my table. Can anyone tell me what I'm doing wrong?

AngularJS: 1.3

UPDATE

Ero answer was right, I just need to convert again my array for object, and then use ng-repeat. I'm still with Smart Table erro for filter (what doesn't work for object array), but I think it's plugin error and I will check on the github forum.

Body:
Since the objects have unique identifier property, EstoqueId, use that for tracking instead of $index:

<tr ng-repeat="e in estoqueJSON | filter : paginate | orderBy:sortType:sortReverse | filter:searchField track by e.EstoqueId">

From the Docs:

If you are working with objects that have a unique identifier property, you should track by this identifier instead of the object instance [or $index]. Should you reload your data later, ngRepeat will not have to rebuild the DOM elements for items it has already rendered, even if the JavaScript objects in the collection have been substituted for new ones. For large collections, this significantly improves rendering performance.

— AngularJS ng-repeat Directive API Reference - Tracking


问:
Change mouse cursor when over certain components without affecting other cursor-setting code
I'm using an ancient precursor to the DevExpress QuantumGrid (MasterView) in Delphi XE2 and would like certain cells to effectively act as hyperlinks (change the mouse cursor from crDefault to crHandPoint when over them and trigger an action on click).

The configuration of the grid component is such that individual cells are not their own component, and I will need to find the cell from the mouse cursor coordinates and set the cursor from there.

I think I need to set a few events on my grid object to achieve this, but I'm a little uncomfortable about how these events will interact with code that sets the cursor to an hourglass when doing long-running operations (currently handled using IDisposible to set the cursor back to original when finished) and want to double-check whether there's a better way of doing this before I get started and then find a tonne of edge-cases that leave the mouse cursor in the wrong state.

I think I need to override:

omMouseMove - get XY co-ordinates and set the cursor to hand/arrow

onMouseDown - get XY co-ordinates and 'activate' hyperlink if present (possibly revert to arrow? The hyperlink will usually open a new window and the code called may change the cursor to an hourglass)

onMouseLeave - reset cursor to arrow (this event isn't actually exposed, so
think I'll need to handle messages manually)

This kind of functionality comes as default on a TButton, but I couldn't see in the VCL how it's achieved at first glance, and may be a feature of the underlying Windows control.

答:
This is a scenario I would prefer. The cursor is set from the WM_SETCURSOR message handler and backend work signalled by a flag. Link click is then handled from the MouseDown method override. Note that the cursor is changed only for this control (when the mouse cursor hovers the control). In pseudocode:

```<code>type
  THitCode =
  (
    hcHeader,
    hcGridCell,
    hcHyperLink { ← this is the extension }
  );

  THitInfo = record
    HitRow: Integer;
    HitCol: Integer;
    HitCode: THitCode;
  end;

  TMadeUpGrid = class(TGridAncestor)
  private
    FWorking: Boolean;
    procedure DoStartWork;
    procedure DoFinishWork;
    procedure UpdateCursor;
    procedure WMSetCursor(var Msg: TWMSetCursor); message WM_SETCURSOR;
  protected
    procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
  public
    function GetHitTest(X, Y: Integer): THitInfo; override;
  end;

implementation

procedure TMadeUpGrid.DoStartWork;
begin
  FWorking := True;
  UpdateCursor;
end;

procedure TMadeUpGrid.DoFinishWork;
begin
  FWorking := False;
  UpdateCursor;
end;

procedure TMadeUpGrid.UpdateCursor;
begin
  Perform(CM_CURSORCHANGED, 0, 0); { ← triggers WM_SETCURSOR handler if needed }
end;

procedure TMadeUpGrid.WMSetCursor(var Msg: TWMSetCursor);
var
  P: TPoint;
  HitInfo: THitInfo;
begin
  { the mouse is inside the control client rect, inherited call here should
    "default" to the Cursor property cursor type }
  if Msg.HitTest = HTCLIENT then
  begin
    GetCursorPos(P);
    P := ScreenToClient(P);
    HitInfo := GetHitTest(P.X, P.Y);
    { if the mouse is hovering a hyperlink or the grid backend is working }
    if FWorking or (HitInfo.HitCode = hcHyperLink) then
    begin
      { here you can setup the "temporary" cursor for the hyperlink, or
        for the working grid backend }
      if not FWorking then
        SetCursor(Screen.Cursors[crHandPoint])
      else
        SetCursor(Screen.Cursors[crHourGlass]);
      { tell the messaging system that this message has been handled }
      Msg.Result := 1;
    end
    else
      inherited;
  end
  else
    inherited;
end;

procedure TMadeUpGrid.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
  HitInfo: THitInfo;
begin
  if Button = mbLeft then
  begin
    HitInfo := GetHitTest(X, Y);
    { the left mouse button was pressed when hovering the hyperlink, so set
      the working flag, trigger the WM_SETCURSOR handler "manually" and do the
      navigation; when you finish the work, call DoFinishWork (from the main
      thread context) }
    if HitInfo.HitCode = hcHyperLink then
    begin
      DoStartWork;
      DoSomeNavigation(HitInfo.HitRow, HitInfo.HitCol);
    end;
  end;
end;

function TMadeUpGrid.GetHitTest(X, Y: Integer): THitInfo;
begin
  { fill the Result structure properly }
end;
</code>```

Body:
This is a scenario I would prefer. The cursor is set from the WM_SETCURSOR message handler and backend work signalled by a flag. Link click is then handled from the MouseDown method override. Note that the cursor is changed only for this control (when the mouse cursor hovers the control). In pseudocode:

type
  THitCode =
  (
    hcHeader,
    hcGridCell,
    hcHyperLink { ← this is the extension }
  );

  THitInfo = record
    HitRow: Integer;
    HitCol: Integer;
    HitCode: THitCode;
  end;

  TMadeUpGrid = class(TGridAncestor)
  private
    FWorking: Boolean;
    procedure DoStartWork;
    procedure DoFinishWork;
    procedure UpdateCursor;
    procedure WMSetCursor(var Msg: TWMSetCursor); message WM_SETCURSOR;
  protected
    procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
  public
    function GetHitTest(X, Y: Integer): THitInfo; override;
  end;

implementation

procedure TMadeUpGrid.DoStartWork;
begin
  FWorking := True;
  UpdateCursor;
end;

procedure TMadeUpGrid.DoFinishWork;
begin
  FWorking := False;
  UpdateCursor;
end;

procedure TMadeUpGrid.UpdateCursor;
begin
  Perform(CM_CURSORCHANGED, 0, 0); { ← triggers WM_SETCURSOR handler if needed }
end;

procedure TMadeUpGrid.WMSetCursor(var Msg: TWMSetCursor);
var
  P: TPoint;
  HitInfo: THitInfo;
begin
  { the mouse is inside the control client rect, inherited call here should
    "default" to the Cursor property cursor type }
  if Msg.HitTest = HTCLIENT then
  begin
    GetCursorPos(P);
    P := ScreenToClient(P);
    HitInfo := GetHitTest(P.X, P.Y);
    { if the mouse is hovering a hyperlink or the grid backend is working }
    if FWorking or (HitInfo.HitCode = hcHyperLink) then
    begin
      { here you can setup the "temporary" cursor for the hyperlink, or
        for the working grid backend }
      if not FWorking then
        SetCursor(Screen.Cursors[crHandPoint])
      else
        SetCursor(Screen.Cursors[crHourGlass]);
      { tell the messaging system that this message has been handled }
      Msg.Result := 1;
    end
    else
      inherited;
  end
  else
    inherited;
end;

procedure TMadeUpGrid.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
  HitInfo: THitInfo;
begin
  if Button = mbLeft then
  begin
    HitInfo := GetHitTest(X, Y);
    { the left mouse button was pressed when hovering the hyperlink, so set
      the working flag, trigger the WM_SETCURSOR handler "manually" and do the
      navigation; when you finish the work, call DoFinishWork (from the main
      thread context) }
    if HitInfo.HitCode = hcHyperLink then
    begin
      DoStartWork;
      DoSomeNavigation(HitInfo.HitRow, HitInfo.HitCol);
    end;
  end;
end;

function TMadeUpGrid.GetHitTest(X, Y: Integer): THitInfo;
begin
  { fill the Result structure properly }
end;


问:
Android: getting a c++ std::string up to JNIEXPORT gets unexpectedly cleared out
On an Android application, I'm trying to get a string from native code up to Java, but exactly at the JNIEXPORT level, the std::string gets wiped out of its contents.
Here's the code for all the three layers:

C++ code (original x-patform class):

```<code>std::string GTAInterface::GetConfigurationJSON()
{
    std::string m_cfgJSON = "a bare test";
    return m_cfgJSON;
}
</code>```

C++ wrapper code (since JNI on Android can only call static C++ functions... no words on this):

```<code>const char *gtaGateway::GetConfigurationJSON(int sysId)
{
    string ret = ((GTAInterface*)gtaSystemArray[sysId])->GetConfigurationJSON();
    return ret.c_str(); // here the "ret" string is still retaining the retrieved value
}
</code>```

An finally, the JNIEXPORT class:

```<code>JNIEXPORT jstring JNICALL
Java_com_gta_sdk_gtaGateway_GetConfigurationJSON(JNIEnv *env, jobject obj, jint sys)
{
    std::string cfgJson = gtaGateway::GetConfigurationJSON(sys);

    return env->NewStringUTF(cfgJson.c_str()); // here the debugger shows that "cfgJson" is "" (empty)??!!
}
</code>```

So, the code correctly gets executed throughout all the call chain, but for some reason I can't figure out why the "cfgJson" string @ the JNIEXPORT level gets cleared out!
Could someone please help out, since I have no other clue of what I could be doing wrong...

Many thanks!

答:
So, just caught the issue (thanks Andrew for inspiring): a through "heap chase" with a monitor and a load test got me to the corruption point (elsewhere in the application)... goods and bads of unmanaged :)

Therefore, just in case someone else needs it, the approach exposed in the question is perfectly working, as well as my initial attempt in passing std::string-s all the way up through the call chain 'till the jstring.

Body:
On an Android application, I'm trying to get a string from native code up to Java, but exactly at the JNIEXPORT level, the std::string gets wiped out of its contents.
Here's the code for all the three layers:

C++ code (original x-patform class):

std::string GTAInterface::GetConfigurationJSON()
{
    std::string m_cfgJSON = "a bare test";
    return m_cfgJSON;
}

C++ wrapper code (since JNI on Android can only call static C++ functions... no words on this):

const char *gtaGateway::GetConfigurationJSON(int sysId)
{
    string ret = ((GTAInterface*)gtaSystemArray[sysId])->GetConfigurationJSON();
    return ret.c_str(); // here the "ret" string is still retaining the retrieved value
}

An finally, the JNIEXPORT class:

JNIEXPORT jstring JNICALL
Java_com_gta_sdk_gtaGateway_GetConfigurationJSON(JNIEnv *env, jobject obj, jint sys)
{
    std::string cfgJson = gtaGateway::GetConfigurationJSON(sys);

    return env->NewStringUTF(cfgJson.c_str()); // here the debugger shows that "cfgJson" is "" (empty)??!!
}

So, the code correctly gets executed throughout all the call chain, but for some reason I can't figure out why the "cfgJson" string @ the JNIEXPORT level gets cleared out!
Could someone please help out, since I have no other clue of what I could be doing wrong...

Many thanks!


问:
NetBeans IDE - ClassNotFoundException: net.ucanaccess.jdbc.UcanaccessDriver
Trying to use UCanAccess to open an Access database with Java but it doesn't seem to be working. Here is the code:

```<code>import java.sql.*;

public class DbAccess2
{
public static void main(String[] args)
{
    try
    {
    Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");

 Connection conn=DriverManager.getConnection("jdbc:ucanaccess://c:/myDB.mdb");
        Statement s = conn.createStatement();
       System.out.println("OK");
    }
    catch(Exception ex)
    {
        ex.printStackTrace();
       // System.out.print("Not OK");
    }
}
}
</code>```

Here is the error I get:

```<code>java.lang.ClassNotFoundException: net.ucanaccess.jdbc.UcanaccessDriver
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:264)
    at DbAccess2.main(DbAccess2.java:10)
BUILD SUCCESSFUL (total time: 0 seconds)
</code>```

Here's what my file looks like (NetBeans)

答: You have the UCanAccess jar file and its dependencies in a folder named lib under "Libraries". Normally those jar files reside in "Libraries" itself, along with the JDK. It looks you unpacked a bunch of stuff and then tried to just add the folder, but that doesn't work: you need to add the actual jar files (not the folder they live in). See the NetBeans screenshot in this answer for an example.

Body:
Trying to use UCanAccess to open an Access database with Java but it doesn't seem to be working. Here is the code:

import java.sql.*;

public class DbAccess2
{
public static void main(String[] args)
{
    try
    {
    Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");

 Connection conn=DriverManager.getConnection("jdbc:ucanaccess://c:/myDB.mdb");
        Statement s = conn.createStatement();
       System.out.println("OK");
    }
    catch(Exception ex)
    {
        ex.printStackTrace();
       // System.out.print("Not OK");
    }
}
}

Here is the error I get:

java.lang.ClassNotFoundException: net.ucanaccess.jdbc.UcanaccessDriver
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:264)
    at DbAccess2.main(DbAccess2.java:10)
BUILD SUCCESSFUL (total time: 0 seconds)

Here's what my file looks like (NetBeans)


问:
Selecting an element's parent's previous sibling's child - traversing elements
I know the title is a bit possessive but I had no better way to word it correctly.

Generated HTML:

```<code><ul class="nav nav-tabs" id="orderResultTabs" role="tablist">
      <li class="nav-item">
            <a class="nav-link active" data-toggle="tab" href="#5423788082" role="tab" aria-controls="home" aria-expanded="false">5423788082</a>
      </li>
      <li class="nav-item active">
            <a class="nav-link active" data-toggle="tab" href="#5424163999" role="tab" aria-controls="home" aria-expanded="false">5424163999</a>
      </li>
</ul>
</code>```

I have a set of bootstrap tabs that get appended after an ajax call. However, after each call I'd like the previous tab to be set to inactive. Making the newest tab the focus. Essentially all previous a.nav-links should have their active class removed after each ajax call.

JS:

```<code>$("#orderResultTabs > li > a:last").parent().prevAll().siblings().find(".active").removeClass("active");
$("#orderResultTabs > li > a:last").addClass("active");
</code>```

Ajax:

```<code> $.ajax({
        type: "POST",
        url: "orders",
        data: "order_id=" + orderID + "&flag=" + flag,
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        success: function(data) {
            // var table = $("#orderOutput");
            var tabNav = $("#orderResultTabs");
            var tabContent = $('.tab-content');
            for (var i = data.length - 1; i >= 0; i--) {
                orderID = data[i].orders_id;
                orderLoop(i, data, tabNav, orderID, tabContent);
            }
            $('.loader').hide(); //hide loader
            $('.clear').show();
            $("#orderResultTabs > li > a:last").parent().prevAll().siblings().find(".active").removeClass("active");

            $("#orderResultTabs > li > a:last").addClass("active");
            $("input[type=orderID]").val("");
            $('#ordersOutput').show();

        },
        error: function(data) {
            alert('error');
            console.log(data);
        }
    });
</code>```

orderLoop()

```<code>function orderLoop(i, data, tabNav, orderID, tabContent) {
    tabNav.append("<li class='nav-item'><a class='nav-link active' data-toggle='tab' href=#" + data[i].orders_id + " role='tab' aria-controls='home' aria-expanded='false'>" + data[i].orders_id + "</a></li>");

    for (var j = data.length - 1; j >= 0; j--) {
        tabContent.append("<div class='tab-pane fade' id=" + data[j].orders_id + " role='tabpanel'><div class='tab'><div class='col'><table class='table table-sm table-responsive' id='orderOutput'></table><form role='form'><button id='viewOrderItems' value='NO ORDER ID' type='button' class='btn btn-primary btn-sm btn-block'>View Order Items</button></form></div></div></div>");
        var table = $(".tab-pane#" + data[j].orders_id + " > .tab > .col > table");
        table.append("<tr><th>ADDRESS ID</th><td>" + data[j].address+ "</td></tr>");
        table.append("<tr><th>CURRENCY</th><td>" + data[j].currency + "</td></tr>");
        table.append("<tr><th>MEMBER ID</th><td>" + data[j].member+ "</td></tr>");
        table.append("<tr><th>STORE ID</th><td>" + data[j].store+ "</td></tr>");
        table.append("<tr><th>TIMEPLACED</th><td>" + moment(data[j].timeplaced).format("MMMM D, YYYY @ h:mm A") + "</td></tr>");
        table.append("<tr><th>TOTAL ADJUSTMENT</th><td>$" + data[j].adjust+ "</td></tr>");
        table.append("<tr><th>TOTAL PRODUCT</th><td>$" + data[j].prod+ "</td></tr>");
        table.append("<tr><th>TOTAL SHIPPING</th><td>$" + data[j].totalshipping + "</td></tr>");
        table.append("<tr><th>TOTAL TAX</th><td>$" + data[j].tax+ "</td></tr>");
        table.append("<tr><th>TOTAL SHIPPING TAX</th><td>$" + data[j].shiptax+ "</td></tr>");
        table.append("<tr><th>TYPE</th><td>" + data[j].type + "</td></tr>");
        var button = $(".tab-pane#" + data[j].orders_id + " > .tab > .col > form > button");
        button.val(data[i].orders_id);
        $('.nav-tabs a:last').tab('show');

    }
}
</code>```

If anyone has ideas on how to do this, I'd love to hear from you.

After @varlogtim's suggestions:

```<code><ul class="nav nav-tabs" id="orderResultTabs" role="tablist">
      <li class="nav-item active">
            <a class="nav-link" data-toggle="tab" href="#5423788082" role="tab" aria-controls="home" aria-expanded="false">5423788082</a>
            </li>
      <li class="nav-item">
            <a class="nav-link active" data-toggle="tab" href="#5424163999" role="tab" aria-controls="home" aria-expanded="false">5424163999</a>
      </li>
</ul>
</code>```

When I click, the list item goes active, the tab content is shown, but the nav-link remains inactive. I've attempted to the following:

```<code>$(".nav-link").on("click", function() {
    $(this).addClass("active");
});
</code>```

After commenting: // $("#orderResultTabs > li:last").addClass("active");

Initial:

```<code><div id="ordersOutput">
      <div role="tabpanel">
            <ul class="nav nav-tabs" id="orderResultTabs" role="tablist">
            </ul>
            <div class="tab-content clearfix">
            </div>
      </div>
</div>
</code>```

First Run:

```<code><div id="ordersOutput" style="display: block;">
      <div role="tabpanel">
            <ul class="nav nav-tabs" id="orderResultTabs" role="tablist">
                  <li class="nav-item"><a class="nav-link **active**" data-toggle="tab" href="#5423788082" role="tab" aria-controls="home" aria-expanded="false">5423788082</a></li>
            </ul>
            <div class="tab-content clearfix">
                  <div class="tab-pane **active**" id="5423788082" role="tabpanel">
                        <div class="tab">
                              <div class="col">
                                    <table class="table table-sm table-responsive" id="orderOutput">
                                    </table>
                                    <form role="form">
                                    </form>
                              </div>
                        </div>
                  </div>
            </div>
      </div>
</div>
</code>```

Second Run:

```<code><div id="ordersOutput" style="display: block;">
      <div role="tabpanel">
            <ul class="nav nav-tabs" id="orderResultTabs" role="tablist">
                  <li class="nav-item"><a class="nav-link" data-toggle="tab" href="#idAlpha" role="tab" aria-controls="home" aria-expanded="false">idAlpha</a></li>
                  <li class="nav-item"><a class="nav-link **active**" data-toggle="tab" href="#idBeta" role="tab" aria-controls="home" aria-expanded="false">idBeta</a></li>
            </ul>
            <div class="tab-content clearfix">
                  <div class="tab-pane" id="idAlpha" role="tabpanel">
                        <div class="tab">
                              <div class="col">
                                    <table class="table table-sm table-responsive" id="orderOutput">
                                    </table>
                                    <form role="form" lpformnum="2">
                                    </form>
                              </div>
                        </div>
                  </div>
                  <div class="tab-pane **active**" id="idBeta" role="tabpanel">
                        <div class="tab">
                              <div class="col">
                                    <table class="table table-sm table-responsive" id="orderOutput">
                                    </table>
                                    <form role="form">
                                    </form>
                              </div>
                        </div>
                  </div>
            </div>
      </div>
</div>
</code>```

After Second Run - When I click the first tab:

Notice that even though I have activated/clicked the (.nav-link) for the first tab (#idAlpha), the (.nav-link) for the second tab (#idBeta) remains active. This should not be. I put a "**_**" around the active classes and the one designated with : _**active**_ is the issue.

```<code><div id="ordersOutput" style="display: block;">
      <div role="tabpanel">
            <ul class="nav nav-tabs" id="orderResultTabs" role="tablist">
                  <li class="nav-item **active**"><a class="nav-link" data-toggle="tab" href="#idAlpha" role="tab" aria-controls="home" aria-expanded="false">idAlpha</a></li>
                  <li class="nav-item"><a class="nav-link _**active**_" data-toggle="tab" href="#idBeta" role="tab" aria-controls="home" aria-expanded="false">idBeta</a></li>
            </ul>
            <div class="tab-content clearfix">
                  <div class="tab-pane **active**" id="idAlpha" role="tabpanel">
                        <div class="tab">
                              <div class="col">
                                    <table class="table table-sm table-responsive" id="orderOutput">
                                    </table>
                                    <form role="form" lpformnum="2">
                                    </form>
                              </div>
                        </div>
                  </div>
                  <div class="tab-pane" id="idBeta" role="tabpanel">
                        <div class="tab">
                              <div class="col">
                                    <table class="table table-sm table-responsive" id="orderOutput">
                                    </table>
                                    <form role="form" lpformnum="3">
                                    </form>
                              </div>
                        </div>
                  </div>
            </div>
      </div>
</div>
</code>```

The most recent tab should not remain active. Once it is outputted the tabs should return back to normal bootstrap functionality.

答:
So, the answer is to iterate over all the li > a items and remove the "active" classes, then set the active class on the last.

I noticed that both the li and the a have active flags, so that may be causing some confusion. My answer removes the active flag on both the li item and the a elements.

```<code>$.ajax({
    type: "POST",
    url: "orders",
    data: "order_id=" + orderID + "&flag=" + flag,
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    },
    success: function(data) {
        // var table = $("#orderOutput");
        var tabNav = $("#orderResultTabs");
        var tabContent = $('.tab-content');
        for (var i = data.length - 1; i >= 0; i--) {
            orderID = data[i].orders_id;
            orderLoop(i, data, tabNav, orderID, tabContent);
        }
        $('.loader').hide(); //hide loader
        $('.clear').show();

        // start fix
        $("#orderResultTabs > li").each(function() {
            $(this).removeClass("active");
            $(this).children("a").removeClass("active");
        });

        //$("#orderResultTabs > li:last").addClass("active");
        $("#orderResultTabs > li:last > a").addClass("active");
        // end fix

        $("input[type=orderID]").val("");
        $('#ordersOutput').show();

    },
    error: function(data) {
        alert('error');
        console.log(data);
    }
});
</code>```

Body:
I know the title is a bit possessive but I had no better way to word it correctly.

Generated HTML:

            5423788082

            5424163999

I have a set of bootstrap tabs that get appended after an ajax call. However, after each call I'd like the previous tab to be set to inactive. Making the newest tab the focus. Essentially all previous a.nav-links should have their active class removed after each ajax call.

JS:

$("#orderResultTabs > li > a:last").parent().prevAll().siblings().find(".active").removeClass("active");
$("#orderResultTabs > li > a:last").addClass("active");

Ajax:

 $.ajax({
        type: "POST",
        url: "orders",
        data: "order_id=" + orderID + "&flag=" + flag,
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        success: function(data) {
            // var table = $("#orderOutput");
            var tabNav = $("#orderResultTabs");
            var tabContent = $('.tab-content');
            for (var i = data.length - 1; i >= 0; i--) {
                orderID = data[i].orders_id;
                orderLoop(i, data, tabNav, orderID, tabContent);
            }
            $('.loader').hide(); //hide loader
            $('.clear').show();
            $("#orderResultTabs > li > a:last").parent().prevAll().siblings().find(".active").removeClass("active");

            $("#orderResultTabs > li > a:last").addClass("active");
            $("input[type=orderID]").val("");
            $('#ordersOutput').show();

        },
        error: function(data) {
            alert('error');
            console.log(data);
        }
    });

orderLoop()

function orderLoop(i, data, tabNav, orderID, tabContent) {
    tabNav.append("
" + data[i].orders_id + "
");

    for (var j = data.length - 1; j >= 0; j--) {
        tabContent.append("

<form role='form'><button id='viewOrderItems' value='NO ORDER ID' type='button' class='btn btn-primary btn-sm btn-block'>View Order Items</button></form>

");
        var table = $(".tab-pane#" + data[j].orders_id + " > .tab > .col > table");
        table.append("
ADDRESS ID	" + data[j].address+ "
");
        table.append("
CURRENCY	" + data[j].currency + "
");
        table.append("
MEMBER ID	" + data[j].member+ "
");
        table.append("
STORE ID	" + data[j].store+ "
");
        table.append("
TIMEPLACED	" + moment(data[j].timeplaced).format("MMMM D, YYYY @ h:mm A") + "
");
        table.append("
TOTAL ADJUSTMENT	$" + data[j].adjust+ "
");
        table.append("
TOTAL PRODUCT	$" + data[j].prod+ "
");
        table.append("
TOTAL SHIPPING	$" + data[j].totalshipping + "
");
        table.append("
TOTAL TAX	$" + data[j].tax+ "
");
        table.append("
TOTAL SHIPPING TAX	$" + data[j].shiptax+ "
");
        table.append("
TYPE	" + data[j].type + "
");
        var button = $(".tab-pane#" + data[j].orders_id + " > .tab > .col > form > button");
        button.val(data[i].orders_id);
        $('.nav-tabs a:last').tab('show');

    }
}

If anyone has ideas on how to do this, I'd love to hear from you.

After @varlogtim's suggestions:

            5423788082

            5424163999

When I click, the list item goes active, the tab content is shown, but the nav-link remains inactive. I've attempted to the following:

$(".nav-link").on("click", function() {
    $(this).addClass("active");
});

After commenting: // $("#orderResultTabs > li:last").addClass("active");

Initial:

First Run:

5423788082

                                    <form role="form">
                                    </form>

Second Run:

idAlpha

idBeta

                                    <form role="form" lpformnum="2">
                                    </form>

                                    <form role="form">
                                    </form>

After Second Run - When I click the first tab:

Notice that even though I have activated/clicked the (.nav-link) for the first tab (#idAlpha), the (.nav-link) for the second tab (#idBeta) remains active. This should not be. I put a "**_**" around the active classes and the one designated with : _**active**_ is the issue.

idAlpha

idBeta

                                    <form role="form" lpformnum="2">
                                    </form>

                                    <form role="form" lpformnum="3">
                                    </form>

The most recent tab should not remain active. Once it is outputted the tabs should return back to normal bootstrap functionality.

Body:
So, the answer is to iterate over all the li > a items and remove the "active" classes, then set the active class on the last.

I noticed that both the li and the a have active flags, so that may be causing some confusion. My answer removes the active flag on both the li item and the a elements.

$.ajax({
    type: "POST",
    url: "orders",
    data: "order_id=" + orderID + "&flag=" + flag,
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    },
    success: function(data) {
        // var table = $("#orderOutput");
        var tabNav = $("#orderResultTabs");
        var tabContent = $('.tab-content');
        for (var i = data.length - 1; i >= 0; i--) {
            orderID = data[i].orders_id;
            orderLoop(i, data, tabNav, orderID, tabContent);
        }
        $('.loader').hide(); //hide loader
        $('.clear').show();

        // start fix
        $("#orderResultTabs > li").each(function() {
            $(this).removeClass("active");
            $(this).children("a").removeClass("active");
        });

        //$("#orderResultTabs > li:last").addClass("active");
        $("#orderResultTabs > li:last > a").addClass("active");
        // end fix

        $("input[type=orderID]").val("");
        $('#ordersOutput').show();

    },
    error: function(data) {
        alert('error');
        console.log(data);
    }
});


问:
Can I use `keyof` in Typescript to statically describe the properties on this type that I want to return?
Imagine I have a query class and execute method like this:

```<code>class Query {
    name: string;
    sql: string;
}

function execute(query: Query): any{
    let retVal = {};
    retVal[query.name] = true;
    return retVal;
}

q = new Query();
q.name = "thisIsMyQueryName";
let result = execute(q); // Returns: {thisIsMyQueryName: true}
// `typeof result` is still `any` of course, but I'd like it to be:
// {thisIsMyQueryName: boolean}
</code>```

In this case, the object I'm returning has a shape based on the instance of the class that I passed into it. Obviously, since the "name" of the query can vary at runtime, there is nothing that I can tell the compiler so that it knows the returned object will have a property called "thisIsMyQueryName".

However, I thought there was perhaps something I could do to make this more statically analyzable. We have a lot of these "query" objects and we know their names when we instantiate them in code. I am experimenting with different incantations of key of and I have some things that are promising, but nothing I'm happy with.

Being able to do this would be ideal:

```<code>let q = {
   sql: "",
   queryName: {
       thisIsMyQueryName: ""
   }
}
let result = execute(q); // Returns: {thisIsMyQueryName: true}
// typeof result == {thisIsMyQueryName: boolean}
</code>```

Again, I realize what I just wrote is not possible, but I figure there has to be a way to describe these various instances in some way that the compiler will know that the return type has a property with the name keyof q.queryName

Any ideas?

答:
You can do this by making .queryName a type parameter and using keyof on that parameter:

```<code>class Query<TName> {
    queryName: TName
    sql: string;
}
type Result<TName> = {
    [P in keyof TName]: boolean
}

function execute<TName>(query: Query<TName>): Result<TName> {
    return { [Object.keys(query.queryName)[0]]: true };
}

const q = {
    sql: "",
    queryName: {
        thisIsMyQueryName: ""
    }
};

const result = execute(q);
const b = result.thisIsMyQueryName; // boolean
</code>```

Live demo.

However, you cannot provably implement the function.

Body:
Imagine I have a query class and execute method like this:

class Query {
    name: string;
    sql: string;
}

function execute(query: Query): any{
    let retVal = {};
    retVal[query.name] = true;
    return retVal;
}

q = new Query();
q.name = "thisIsMyQueryName";
let result = execute(q); // Returns: {thisIsMyQueryName: true}
// `typeof result` is still `any` of course, but I'd like it to be:
// {thisIsMyQueryName: boolean}

In this case, the object I'm returning has a shape based on the instance of the class that I passed into it. Obviously, since the "name" of the query can vary at runtime, there is nothing that I can tell the compiler so that it knows the returned object will have a property called "thisIsMyQueryName".

However, I thought there was perhaps something I could do to make this more statically analyzable. We have a lot of these "query" objects and we know their names when we instantiate them in code. I am experimenting with different incantations of key of and I have some things that are promising, but nothing I'm happy with.

Being able to do this would be ideal:

let q = {
   sql: "",
   queryName: {
       thisIsMyQueryName: ""
   }
}
let result = execute(q); // Returns: {thisIsMyQueryName: true}
// typeof result == {thisIsMyQueryName: boolean}

Again, I realize what I just wrote is not possible, but I figure there has to be a way to describe these various instances in some way that the compiler will know that the return type has a property with the name keyof q.queryName

Any ideas?

Body:
You can do this by making .queryName a type parameter and using keyof on that parameter:

class Query<TName> {
    queryName: TName
    sql: string;
}
type Result<TName> = {
    [P in keyof TName]: boolean
}

function execute<TName>(query: Query<TName>): Result<TName> {
    return { [Object.keys(query.queryName)[0]]: true };
}

const q = {
    sql: "",
    queryName: {
        thisIsMyQueryName: ""
    }
};

const result = execute(q);
const b = result.thisIsMyQueryName; // boolean

<a href="https://www.typescriptlang.org/play/index.html#src=class%20Query%3CTName%3E%20%7B%0D%0A%20%20%20%20queryName%3A%20TName%0D%0A%20%20%20%20sql%3A%20string%3B%0D%0A%7D%20%0D%0Atype%20Result%3CTName%3E%20%3D%20%7B%0D%0A%20%20%20%20%5BP%20in%20keyof%20TName%5D%3A%20boolean%0D%0A%7D%0D%0A%0D%0Afunction%20execute%3CTName%3E(query%3A%20Query%3CTName%3E)%3A%20Result%3CTName%3E%20%7B%0D%0A%20%20%20%20return%20%7B%20%5BObject.keys(query.queryName)%5B0%5D%5D%3A%20true%20%7D%3B%0D%0A%7D%0D%0A%0D%0Aconst%20q%20%3D%20%7B%0D%0A%20%20%20%20sql%3A%20%22%22%2C%0D%0A%20%20%20%20queryName%3A%20%7B%0D%0A%20%20%20%20%20%20%20%20thisIsMyQueryName%3A%20%22%22%0D%0A%20%20%20%20%7D%0D%0A%7D%3B%0D%0A%0D%0Aconst%20result%20%3D%20execute(q)%3B%0D%0Aconst%20b%20%3D%20result.thisIsMyQueryName%3B%20%2F%2F%20boolean" rel="nofollow noreferrer">Live demo.

However, you cannot provably implement the function.


问:
Equation in laravel where condition
I have table Item with the following fields(latitude,longitude) and I have a function which has as parameters (lat, lon, radius)

then I want to retrieve data which accept the equation (|lon-longitude|/|lat-latitude|)<= radius

I am using laravel 5.4 like the following:

```<code>public function calc($lon, $lat, $radius){
    $result = Item::where()->get();
}
</code>```

Any help how will the where condition be to do this equation!!

答:
Try this using the whereRaw</p>

```<code>public function calc($lon, $lat, $radius){
    $result = Item::whereRaw("abs($lon-longitude)/abs($lat-latitude) <= $radius")->get();
}
</code>```

Title: Equation in laravel where condition

Body:
I have table Item with the following fields(latitude,longitude) and I have a function which has as parameters (lat, lon, radius)

then I want to retrieve data which accept the equation (|lon-longitude|/|lat-latitude|)<= radius

I am using laravel 5.4 like the following:

public function calc($lon, $lat, $radius){
    $result = Item::where()->get();
}

Any help how will the where condition be to do this equation!!

Body:
Try this using the whereRaw

public function calc($lon, $lat, $radius){
    $result = Item::whereRaw("abs($lon-longitude)/abs($lat-latitude) <= $radius")->get();
}


问:
Insert element into array C
I have an array of numbers that has been sorted in before, so there's no need to sort it, I need to insert an given value, named it val, at a valid position in my array.

My program works for a given value that is smaller than the last one, but for the case where the value is bigger than the last one, my program just doesn't want to insert the value.

For example, for the array {1, 2, 3, 4, 6} and the value 5, the array should be {1, 2, 3, 4, 5, 6}, but for the value 7 my array is looking like {1, 2, 7, 4, 6, 0}.

```<code>#include <stdio.h>

void insert(int val, int *n, int v[])
{
    int index;
    index = n - 1;
    if (n == 0)
    {
        v[0] = val; // check if array is empty
        n = n + 1; // v[0] becomes the given value
    }              // increase size of array
    if (val > v[index])
    {
        v[index+1] = val; // given value is bigger than the last value in array
        n = n + 1; // increase size
    }
    else
    {
        while (index >= 0 && v[index] > val)
        {
            v[index+1] = v[index]; //shift items to the right
            index--;
        }

        v[index + 1] = val; //after moving elements to the right
        n = n + 1;   // i set the value to the valid position
    }
}

void display(int n, int v[])
{
    int i;
    for (i = 0;i < n; i++)
        printf("%d ", v[i]);
}

int main(void)
{
    int v[10] = { 12, 23, 34, 41, 69, 71, 81, 91, 100 };
    int n;
    n = 9; // size of array
    insert(101,n,v); // 101 is given value to insert
    display(n,v);
    return 0;
}
</code>```

答:
You have a couple of mistakes:

You are passing int instead of int * so you're not able to update array size

You are not correctly placing value in the array

This is how your code should look like:

```<code>#include <stdio.h>

void insert(int val, int *nPtr, int v[]);
void display(int n, int v[]);

int main(void) {
  int v[10] = {12, 23, 34, 41, 69, 71, 81, 91, 100};
  int n;
  n = 9;
  insert(101, &n, v);
  display(n, v);
  return 0;
}

void insert(int val, int *nPtr, int v[]) {
  int n = *nPtr;
  int i, j;
  int k = 0;

  for (i = 0; i < n + 1; i++)
    if (!k) {
      if (v[i] > val || i == n) {
        for (j = n - 1; j >= i; j--) {
          v[j + 1] = v[j];
        }

        v[i] = val;
        n++;

        k = 1;
      }
    }

  *nPtr = n;
}

void display(int n, int v[]) {
  int i;
  for (i = 0; i < n; i++)
    printf("%d ", v[i]);
  printf("\n");
}
</code>```

You can also try to insert number on the beginning, for example 0 and it will still work.

Title: Insert element into array C

Body:
I have an array of numbers that has been sorted in before, so there's no need to sort it, I need to insert an given value, named it val, at a valid position in my array.

My program works for a given value that is smaller than the last one, but for the case where the value is bigger than the last one, my program just doesn't want to insert the value.

For example, for the array {1, 2, 3, 4, 6} and the value 5, the array should be {1, 2, 3, 4, 5, 6}, but for the value 7 my array is looking like {1, 2, 7, 4, 6, 0}.

#include <stdio.h>

void insert(int val, int *n, int v[])
{
    int index;
    index = n - 1;
    if (n == 0)
    {
        v[0] = val; // check if array is empty
        n = n + 1; // v[0] becomes the given value
    }              // increase size of array
    if (val > v[index])
    {
        v[index+1] = val; // given value is bigger than the last value in array
        n = n + 1; // increase size
    }
    else
    {
        while (index >= 0 && v[index] > val)
        {
            v[index+1] = v[index]; //shift items to the right
            index--;
        }

        v[index + 1] = val; //after moving elements to the right
        n = n + 1;   // i set the value to the valid position
    }
}

void display(int n, int v[])
{
    int i;
    for (i = 0;i < n; i++)
        printf("%d ", v[i]);
}

int main(void)
{
    int v[10] = { 12, 23, 34, 41, 69, 71, 81, 91, 100 };
    int n;
    n = 9; // size of array
    insert(101,n,v); // 101 is given value to insert
    display(n,v);
    return 0;
}

Body:
You have a couple of mistakes:

You are passing int instead of int * so you're not able to update array size

You are not correctly placing value in the array

This is how your code should look like:

#include <stdio.h>

void insert(int val, int *nPtr, int v[]);
void display(int n, int v[]);

int main(void) {
  int v[10] = {12, 23, 34, 41, 69, 71, 81, 91, 100};
  int n;
  n = 9;
  insert(101, &n, v);
  display(n, v);
  return 0;
}

void insert(int val, int *nPtr, int v[]) {
  int n = *nPtr;
  int i, j;
  int k = 0;

  for (i = 0; i < n + 1; i++)
    if (!k) {
      if (v[i] > val || i == n) {
        for (j = n - 1; j >= i; j--) {
          v[j + 1] = v[j];
        }

        v[i] = val;
        n++;

        k = 1;
      }
    }

  *nPtr = n;
}

void display(int n, int v[]) {
  int i;
  for (i = 0; i < n; i++)
    printf("%d ", v[i]);
  printf("\n");
}

You can also try to insert number on the beginning, for example 0 and it will still work.


问:
Repeat state until it doesn't change / is stable
I'm trying to run a state transform repeatedly until the state doesn't change. I've searched Hoogle for

```<code>Eq s => State s () -> State s ()
</code>```

but found nothing that looks appropriate.

How can I run a state transform repeatedly until it doesn't change?

答:
You are computing the fix-point of your state transform.
But we can't use fix since we are in a monadic context.
So let's use a monadic fix-point combinator instead.
Enter mfix:

import Control.Monad (unless)
import Control.Monad.State (MonadState, StateT, get, put)
import Control.Monad.Fix (mfix)
import Control.Monad.IO.Class (liftIO)

untilStable :: MonadState s m => (s -> s -> Bool) -> m a -> m ()
untilStable p = mfix $ \f st -> p <$> get <* st <*> get >>= (`unless` f)
```

<p>I also took the liberty of generalizing your function to so that you can provide a user supplied binary predicate.</p>

<p>Using ghci <code>runState (untilStable (==) $ modify (+1)) 2</code> will never terminate.
But with:</p>

<pre class="lang-hs prettyprint-override"><code>comp :: StateT Int IO ()
comp = do
  s1 <- (+1) <$> get
  liftIO $ print s1
  let s2 = if s1 >= 3 then 3 else s1
  put s2
</code>```

You get:

> runStateT (untilStable (==) comp) 0
1
2
3
4
((),3)
```

<p>This <code>untilStable</code> can be generalized further into:</p>

<pre class="lang-hs prettyprint-override"><code>untilStable :: MonadState s m => (s -> s -> Bool) -> m a -> m a
untilStable p = mfix $ \f st -> do
  before <- get
  a <- st
  after  <- get
  if p before after then pure a else f
</code>```

Now we have freed up what types the computations can result in.

Fix you want to implement idempotently with fix, you can do it like so:

import Data.Function (fix)

idempotently :: Eq a => (a -> a) -> a -> a
idempotently = fix $ \i f a ->
  let a' = f a
  in if a' == a then a else i f a'
```

Body:
I'm trying to run a state transform repeatedly until the state doesn't change. I've searched Hoogle for

Eq s => State s () -> State s ()

but found nothing that looks appropriate.

How can I run a state transform repeatedly until it doesn't change?

Body:
You are computing the fix-point of your state transform.
But we can't use fix since we are in a monadic context.
So let's use a monadic fix-point combinator instead.
Enter mfix:

import Control.Monad (unless)
import Control.Monad.State (MonadState, StateT, get, put)
import Control.Monad.Fix (mfix)
import Control.Monad.IO.Class (liftIO)

untilStable :: MonadState s m => (s -> s -> Bool) -> m a -> m ()
untilStable p = mfix $ \f st -> p <$> get <* st <*> get >>= (`unless` f)

I also took the liberty of generalizing your function to so that you can provide a user supplied binary predicate.

Using ghci runState (untilStable (==) $ modify (+1)) 2 will never terminate.
But with:

comp :: StateT Int IO ()
comp = do
  s1 <- (+1) <$> get
  liftIO $ print s1
  let s2 = if s1 >= 3 then 3 else s1
  put s2

You get:

> runStateT (untilStable (==) comp) 0
1
2
3
4
((),3)

This untilStable can be generalized further into:

untilStable :: MonadState s m => (s -> s -> Bool) -> m a -> m a
untilStable p = mfix $ \f st -> do
  before <- get
  a <- st
  after  <- get
  if p before after then pure a else f

Now we have freed up what types the computations can result in.

Fix you want to implement idempotently with fix, you can do it like so:

import Data.Function (fix)

idempotently :: Eq a => (a -> a) -> a -> a
idempotently = fix $ \i f a ->
  let a' = f a
  in if a' == a then a else i f a'


问:
How can I get the current time in milliseconds?
How can I get the current time in milliseconds like I can in Java?

System.currentTimeMillis()
```

答:
Since Rust 1.8, you do not need to use a crate. Instead, you can use SystemTime and UNIX_EPOCH:

```<code>use std::time::{SystemTime, UNIX_EPOCH};

fn main() {
    let start = SystemTime::now();
    let since_the_epoch = start
        .duration_since(UNIX_EPOCH)
        .expect("Time went backwards");
    println!("{:?}", since_the_epoch);
}
</code>```

If you need exactly milliseconds, you can convert the Duration.

Rust 1.33

```<code>let in_ms = since_the_epoch.as_millis();
</code>```

Rust 1.27

```<code>let in_ms = since_the_epoch.as_secs() as u128 * 1000 +
            since_the_epoch.subsec_millis() as u128;
</code>```

Rust 1.8

```<code>let in_ms = since_the_epoch.as_secs() * 1000 +
            since_the_epoch.subsec_nanos() as u64 / 1_000_000;
</code>```

Body:
Since Rust 1.8, you do not need to use a crate. Instead, you can use SystemTime and UNIX_EPOCH:

use std::time::{SystemTime, UNIX_EPOCH};

fn main() {
    let start = SystemTime::now();
    let since_the_epoch = start
        .duration_since(UNIX_EPOCH)
        .expect("Time went backwards");
    println!("{:?}", since_the_epoch);
}

If you need exactly milliseconds, you can convert the Duration.

Rust 1.33

let in_ms = since_the_epoch.as_millis();

Rust 1.27

let in_ms = since_the_epoch.as_secs() as u128 * 1000 +
            since_the_epoch.subsec_millis() as u128;

Rust 1.8

let in_ms = since_the_epoch.as_secs() * 1000 +
            since_the_epoch.subsec_nanos() as u64 / 1_000_000;

ContentLicense: CC BY-SA 4.0


问:
Null Values in ProcedureCall
I try the following code:

```<code>    ProcedureCall call = ss.createStoredProcedureCall("servicos.CLASSIFIER_MAP");

    call.registerParameter( 1, String.class, ParameterMode.IN).bindValue(classifierString);
    call.registerParameter( 2, Long.class, ParameterMode.IN ).bindValue(totalRows);
</code>```

Sometimes the variable totalRows is null and an error appears

```<code>WARN:   SQL Error: 17041, SQLState: 99999
Error calling CallableStatement.getMoreResults
</code>```

It is possible to send null values into a ProcedureCall in hibernate?

答:
Currently there are 2 ways to achieve your objective :

Set the property param_null_passing to true in your hibernate configuration.

<property name="hibernate.proc.param_null_passing">true</property>
This is a global setting which will enable you to pass null values in to ProcedureCall throughout your application.

If you do not wish to apply the above setting globally, change your code to the following :

```<code>ProcedureCall call = ss.createStoredProcedureCall("servicos.CLASSIFIER_MAP");

call.registerParameter( 1, String.class, ParameterMode.IN).bindValue(classifierString);
call.registerParameter( 2, Long.class, ParameterMode.IN ).enablePassingNulls(true);

call.setParameter(2,  totalRows);
</code>```

From the Hibernate 5 documentation :

hibernate.proc.param_null_passing (default value is false) :

Global setting for whether null parameter bindings should be passed to database procedure/function calls as part of ProcedureCall handling. Implicitly Hibernate will not pass the null, the intention being to allow any default argument values to be applied.

This defines a global setting, which can then be controlled per parameter via org.hibernate.procedure.ParameterRegistration#enablePassingNulls(boolean)

Values are true (pass the NULLs) or false (do not pass the NULLs).

Title: Null Values in ProcedureCall

Body:
I try the following code:

    ProcedureCall call = ss.createStoredProcedureCall("servicos.CLASSIFIER_MAP");

    call.registerParameter( 1, String.class, ParameterMode.IN).bindValue(classifierString);
    call.registerParameter( 2, Long.class, ParameterMode.IN ).bindValue(totalRows);

Sometimes the variable totalRows is null and an error appears

WARN:   SQL Error: 17041, SQLState: 99999
Error calling CallableStatement.getMoreResults

It is possible to send null values into a ProcedureCall in hibernate?

Body:
Currently there are 2 ways to achieve your objective :

Set the property param_null_passing to true in your hibernate configuration.

<property name="hibernate.proc.param_null_passing">true</property>
This is a global setting which will enable you to pass null values in to ProcedureCall throughout your application.

If you do not wish to apply the above setting globally, change your code to the following :

ProcedureCall call = ss.createStoredProcedureCall("servicos.CLASSIFIER_MAP");

call.registerParameter( 1, String.class, ParameterMode.IN).bindValue(classifierString);
call.registerParameter( 2, Long.class, ParameterMode.IN ).enablePassingNulls(true);

call.setParameter(2,  totalRows);

From the Hibernate 5 documentation :

hibernate.proc.param_null_passing (default value is false) :

Global setting for whether null parameter bindings should be passed to database procedure/function calls as part of ProcedureCall handling. Implicitly Hibernate will not pass the null, the intention being to allow any default argument values to be applied.

This defines a global setting, which can then be controlled per parameter via org.hibernate.procedure.ParameterRegistration#enablePassingNulls(boolean)

Values are true (pass the NULLs) or false (do not pass the NULLs).


问:
recursive find for specific text for last n lines
I want to find some specific text in recursive way, I have read this very popular answer:

```<code>grep -rnw '/path/to/somewhere/' -e 'pattern'
</code>```

But it doesn't work to me due to I have files HUGE that can takes so long to find in the whole file, so I want just to search in the last N lines to improve the performance and time required to do the action, for instance:

答:
This code will print all files, after each filename matched string will be printed. You can play with parameters to make exactly what you want. For example if you move -print to the end, then only matched files will be printed (but after matched strings)

```<code>find /path/to/somewhere/ -type f -print -exec bash -c "cat -n {} | tail | grep -we pattern" \;
</code>```

Body:
I want to find some specific text in recursive way, I have read this very popular answer:

grep -rnw '/path/to/somewhere/' -e 'pattern'

But it doesn't work to me due to I have files HUGE that can takes so long to find in the whole file, so I want just to search in the last N lines to improve the performance and time required to do the action, for instance:

Body:
This code will print all files, after each filename matched string will be printed. You can play with parameters to make exactly what you want. For example if you move -print to the end, then only matched files will be printed (but after matched strings)

find /path/to/somewhere/ -type f -print -exec bash -c "cat -n {} | tail | grep -we pattern" \;


问:
Optimizing LINQ combining multiple lists into new generic list
Given the following three lists:

```<code>    var FirstNames = new List<string>(){ "Bob", "Sondra", "Avery", "Von", "Randle", "Gwen", "Paisley" };
    var LastNames = new List<string>(){ "Anderson", "Carlson", "Vickers", "Black", "Schultz", "Marigold", "Johnson" };
    var Birthdates = new List<DateTime>()
                    {
                        Convert.ToDateTime("11/12/1980"),
                        Convert.ToDateTime("09/16/1978"),
                        Convert.ToDateTime("05/18/1985"),
                        Convert.ToDateTime("10/29/1980"),
                        Convert.ToDateTime("01/19/1989"),
                        Convert.ToDateTime("01/14/1972"),
                        Convert.ToDateTime("02/20/1981")
                    };
</code>```

I'd like to combine them into a new generic type where the relationship the lists share is their position in the collection. i.e. FirstNames[0], LastNames[0], Birthdates[0] are related.

So I have come up with this LINQ, matching the indices, which seems to work fine for now:

```<code>    var students = from fn in FirstNames
                   from ln in LastNames
                   from bd in Birthdates
                   where FirstNames.IndexOf(fn) == LastNames.IndexOf(ln)
                   where FirstNames.IndexOf(fn) == Birthdates.IndexOf(bd)
                   select new { First = fn, Last = ln, Birthdate = bd.Date };
</code>```

However, I have stressed tested this code (Each List<string> and List<DateTime> loaded with a few million records) and I run into SystemOutOfMemory Exception.

Is there any other way of writing out this query to achieve the same results more effectively using Linq?

答:
Yeap, use range generator:</p>

```<code>var result = Enumerable.Range(0, FirstNames.Count)
    .Select(i => new
                 {
                     First = FirstNames[i],
                     Last = LastNames[i],
                     Birthdate = Birthdates[i]
                 });
</code>```

Body:
Given the following three lists:

    var FirstNames = new List<string>(){ "Bob", "Sondra", "Avery", "Von", "Randle", "Gwen", "Paisley" };
    var LastNames = new List<string>(){ "Anderson", "Carlson", "Vickers", "Black", "Schultz", "Marigold", "Johnson" };
    var Birthdates = new List<DateTime>()
                    {
                        Convert.ToDateTime("11/12/1980"),
                        Convert.ToDateTime("09/16/1978"),
                        Convert.ToDateTime("05/18/1985"),
                        Convert.ToDateTime("10/29/1980"),
                        Convert.ToDateTime("01/19/1989"),
                        Convert.ToDateTime("01/14/1972"),
                        Convert.ToDateTime("02/20/1981")
                    };

I'd like to combine them into a new generic type where the relationship the lists share is their position in the collection. i.e. FirstNames[0], LastNames[0], Birthdates[0] are related.

So I have come up with this LINQ, matching the indices, which seems to work fine for now:

    var students = from fn in FirstNames
                   from ln in LastNames
                   from bd in Birthdates
                   where FirstNames.IndexOf(fn) == LastNames.IndexOf(ln)
                   where FirstNames.IndexOf(fn) == Birthdates.IndexOf(bd)
                   select new { First = fn, Last = ln, Birthdate = bd.Date };

However, I have stressed tested this code (Each List<string> and List<DateTime> loaded with a few million records) and I run into SystemOutOfMemory Exception.

Is there any other way of writing out this query to achieve the same results more effectively using Linq?

Body:
Yeap, use range generator:

var result = Enumerable.Range(0, FirstNames.Count)
    .Select(i => new
                 {
                     First = FirstNames[i],
                     Last = LastNames[i],
                     Birthdate = Birthdates[i]
                 });


问:
Warning: mysql_connect(): [2002] No such file or directory (trying to connect via unix:///tmp/mysql.sock) in
I'm trying to connect to my MySQL DB with the Terminal on my Apple (With PHP).

Yesterday it worked fine, and now I suddenly get the error in the title.

The script works when I use my browser to run it (I have XAMPP installed), but Terminal refuses to connect to the DB.

Here is the file that I include to connect (the script works when I don't include this, but then it doesn't connect to the DB):

```<code><?php
    mysql_connect("localhost", "root", "") or die(mysql_error());
    mysql_select_db("FNB1C_data") or die(mysql_error());
?>
</code>```

That should work, since it works with my browser.

The command I use at the Terminal is php scriptname.php.

答:
Since your might use MAMP, either change your Port to the default 3306 or use 127.0.0.1 in the database.php

```<code>$db['default'] = array(
    'dsn'   => '',
    'hostname' => 'localhost',// leave it for port 3306
    'username' => 'yourUserhere',
    'password' => 'yourPassword',
    'database' => 'yourDatabase',
    'dbdriver' => 'mysqli',
    'dbprefix' => '',
    'pconnect' => FALSE,
    'db_debug' => (ENVIRONMENT !== 'production'),
    'cache_on' => FALSE,
    'cachedir' => '',
    'char_set' => 'utf8',
    'dbcollat' => 'utf8_general_ci',
    'swap_pre' => '',
    'encrypt' => FALSE,
    'compress' => FALSE,
    'stricton' => FALSE,
    'failover' => array(),
    'save_queries' => TRUE
);
</code>```

Or with the default settings:

```<code>$db['default'] = array(
        'dsn'   => '',
        'hostname' => '127.0.0.1:8889',// leave it for port 8889
        'username' => 'yourUserhere',
        'password' => 'yourPassword',
        'database' => 'yourDatabase',
        'dbdriver' => 'mysqli',
        'dbprefix' => '',
        'pconnect' => FALSE,
        'db_debug' => (ENVIRONMENT !== 'production'),
        'cache_on' => FALSE,
        'cachedir' => '',
        'char_set' => 'utf8',
        'dbcollat' => 'utf8_general_ci',
        'swap_pre' => '',
        'encrypt' => FALSE,
        'compress' => FALSE,
        'stricton' => FALSE,
        'failover' => array(),
        'save_queries' => TRUE
    );
</code>```

Body:
I'm trying to connect to my MySQL DB with the Terminal on my Apple (With PHP).

Yesterday it worked fine, and now I suddenly get the error in the title.

The script works when I use my browser to run it (I have XAMPP installed), but Terminal refuses to connect to the DB.

Here is the file that I include to connect (the script works when I don't include this, but then it doesn't connect to the DB):

<?php
    mysql_connect("localhost", "root", "") or die(mysql_error());
    mysql_select_db("FNB1C_data") or die(mysql_error());
?>

That should work, since it works with my browser.

The command I use at the Terminal is php scriptname.php.

Body:
Since your might use MAMP, either change your Port to the default 3306 or use 127.0.0.1 in the database.php

$db['default'] = array(
    'dsn'   => '',
    'hostname' => 'localhost',// leave it for port 3306
    'username' => 'yourUserhere',
    'password' => 'yourPassword',
    'database' => 'yourDatabase',
    'dbdriver' => 'mysqli',
    'dbprefix' => '',
    'pconnect' => FALSE,
    'db_debug' => (ENVIRONMENT !== 'production'),
    'cache_on' => FALSE,
    'cachedir' => '',
    'char_set' => 'utf8',
    'dbcollat' => 'utf8_general_ci',
    'swap_pre' => '',
    'encrypt' => FALSE,
    'compress' => FALSE,
    'stricton' => FALSE,
    'failover' => array(),
    'save_queries' => TRUE
);

Or with the default settings:

$db['default'] = array(
        'dsn'   => '',
        'hostname' => '127.0.0.1:8889',// leave it for port 8889
        'username' => 'yourUserhere',
        'password' => 'yourPassword',
        'database' => 'yourDatabase',
        'dbdriver' => 'mysqli',
        'dbprefix' => '',
        'pconnect' => FALSE,
        'db_debug' => (ENVIRONMENT !== 'production'),
        'cache_on' => FALSE,
        'cachedir' => '',
        'char_set' => 'utf8',
        'dbcollat' => 'utf8_general_ci',
        'swap_pre' => '',
        'encrypt' => FALSE,
        'compress' => FALSE,
        'stricton' => FALSE,
        'failover' => array(),
        'save_queries' => TRUE
    );


问:
UTF-8 Encoding Error when Running External Groovy Script from Grails
I am trying to call an external Groovy script from within a Grails application.  I have the following code:

```<code>def initialSize = 4096
def outStream = new ByteArrayOutputStream(initialSize)
def errStream = new ByteArrayOutputStream(initialSize)
def process ="groovy -cp src/groovy/ src/groovy/externalscript.groovy ".execute()
process.consumeProcessOutput(outStream, errStream)
process.waitFor()
println 'out:\n' + outStream
println 'err:\n' + errStream
println process.exitValue()
</code>```

However, I get the following exception:

Error occurred during initialization of VM java.nio.charset.IllegalCharsetNameException: "UTF-8" at java.nio.charset.Charset.checkName(Charset.java:284) at java.nio.charset.Charset.lookup2(Charset.java:458) at java.nio.charset.Charset.lookup(Charset.java:437) at java.nio.charset.Charset.defaultCharset(Charset.java:579) at sun.nio.cs.StreamEncoder.forOutputStreamWriter(StreamEncoder.java:37) at java.io.OutputStreamWriter.(OutputStreamWriter.java:94) at java.io.PrintStream.(PrintStream.java:100) at java.lang.System.initializeSystemClass(System.java:1092)

The script works fine outside of Grails and I am not sure where the encoding issue is coming from. I have tried saving the externalscript.groovy as UTF-8 but I run into the same issue.

答:
What if you change your output streams to:</p>

```<code>def outStream = new StringWriter(initialSize)
def errStream = new StringWriter(initialSize)
</code>```

Body:
I am trying to call an external Groovy script from within a Grails application.  I have the following code:

def initialSize = 4096
def outStream = new ByteArrayOutputStream(initialSize)
def errStream = new ByteArrayOutputStream(initialSize)
def process ="groovy -cp src/groovy/ src/groovy/externalscript.groovy ".execute()
process.consumeProcessOutput(outStream, errStream)
process.waitFor()
println 'out:\n' + outStream
println 'err:\n' + errStream
println process.exitValue()

However, I get the following exception:

Error occurred during initialization of VM java.nio.charset.IllegalCharsetNameException: "UTF-8" at java.nio.charset.Charset.checkName(Charset.java:284) at java.nio.charset.Charset.lookup2(Charset.java:458) at java.nio.charset.Charset.lookup(Charset.java:437) at java.nio.charset.Charset.defaultCharset(Charset.java:579) at sun.nio.cs.StreamEncoder.forOutputStreamWriter(StreamEncoder.java:37) at java.io.OutputStreamWriter.(OutputStreamWriter.java:94) at java.io.PrintStream.(PrintStream.java:100) at java.lang.System.initializeSystemClass(System.java:1092)

The script works fine outside of Grails and I am not sure where the encoding issue is coming from. I have tried saving the externalscript.groovy as UTF-8 but I run into the same issue.

Body:
What if you change your output streams to:

def outStream = new StringWriter(initialSize)
def errStream = new StringWriter(initialSize)


问:
javascript alert box close automatically
I need a function, which close the alert box (window) in few seconds automatically:</p>

```<code>$("#upload-btn").on('click', function() {
  var dt = canvas.toDataURL('image/jpeg');
  if (window.Lollipop) {
     window.Lollipop.save(dt);
  }
   $.post('saveImage.php',
       {
           img : dt
       }, function(data) {
           if(data){
               alert("Image Saved");
           }
       });
</code>```

答: There is no web api function to close the opened alert.

Body:
I need a function, which close the alert box (window) in few seconds automatically:

$("#upload-btn").on('click', function() {
  var dt = canvas.toDataURL('image/jpeg');
  if (window.Lollipop) {
     window.Lollipop.save(dt);
  }
   $.post('saveImage.php',
       {
           img : dt
       }, function(data) {
           if(data){
               alert("Image Saved");
           }
       });