问:
Separating my library to Libs, Core & Addons
I'm pretty new in this world so bear with me.

I have my big library that i'm trying to convert it to es6 modules, babel & webpack to bundle it later on to several files.

My library folders look like this

```<code>--src
  -- core
     -- folder1
     -- folder2
  -- addons
     -- addon 1
        -- addon 1 files and folders
     -- addon 2
        -- addon 2 files and folders
  -- libs
     -- internal
        -- internal lib1
        -- internal lib2
     -- external
        -- external lib1
        -- external lib2
</code>```

My library code is separate to 2 - the core code and the addons and i'm using some libraries (libs folder)

My wish is that:

All internal libs will be bundeled into one libs file

External libs are excluded from bundle

All core files will be bundleds into one core file

All my addons will be bundleds into each addon file

Note: addons are using core files and are not to bundle in them

final result:
libs.js
core.js
addon1.js
addon2.js

My clients will have to use the first 2 js files. and Addon will be included as they wish.

So far I've managed to separate my internal lib using CommonsChunkPlugin

```<code>new webpack.optimize.CommonsChunkPlugin({
    name: "libs",
    minChunks: function(module){
      return module.context && module.context.indexOf("\\libs\\internal\\") !== -1;
    },
  });
</code>```

External libs are ignored using null-loader

```<code>{
   test: /libs\\external/,
   loader: 'null-loader'
},
</code>```

my entry point js looks like this

import a from

```<code>"./core/a";
import b from "./core/b";
import addon1C from "./addons/addon1/c";

const myLib = {
   core: {a,b},
   addons: {addon1C}
}

export {myLib}
</code>```

and now the problem starts with the core and addons.

If i'm skipping the addons part, in my client side including 2 scripts (libs, core)

and simply myLib.core.a is working.

The question do i prevent the bundling of the core code in the addons.

I've tried to do it with another chunk plugin but it causes some errors in the modules because the addon is using the core code and the entry point is using the addons to export it, so it doesn't find the module.

Tried 2 entry points so i will have the first entry point without the addons
and export the addons separately, but now the core code is bundled in it.

So, How do I do that ?
Or if there is a better way to do any of what I've done so far. i'm happy to learn.

答:
In order to achieve that, I think you have to use a different approach. I had a similar situation where some other team needed to extend the core functionality of the application on demand.

In order to achieve that, I had to make sure that the core and the add-on's don't communicate each other directly. Instead, your core code should provide some kind of API that will be used by your add-on's.

From the other end, when your add-on's will try to import the core, you will have to provide a shim file, not the core itself.

I will try to write a couple of examples down here:

```<code>// core
export default const Core = {}
const addons = []
Core.addPlugin = function(addOn) {
   addons.push(addOn) // or doing something else
}

// shim-core.js
export default typeof window.Core !== undefined ? window.Core : Core

// add-on
import Core from 'shim-core'
const addOn = function() {
   // something funky
   return {}
}
Core.addPlugin(addOn)
</code>```

I hope it helps you to understand the 'architecture'

Body:
I'm pretty new in this world so bear with me.

I have my big library that i'm trying to convert it to es6 modules, babel & webpack to bundle it later on to several files.

My library folders look like this

--src
  -- core
     -- folder1
     -- folder2
  -- addons
     -- addon 1
        -- addon 1 files and folders
     -- addon 2
        -- addon 2 files and folders
  -- libs
     -- internal
        -- internal lib1
        -- internal lib2
     -- external
        -- external lib1
        -- external lib2

My library code is separate to 2 - the core code and the addons and i'm using some libraries (libs folder)

My wish is that:

All internal libs will be bundeled into one libs file

External libs are excluded from bundle

All core files will be bundleds into one core file

All my addons will be bundleds into each addon file

Note: addons are using core files and are not to bundle in them

final result:
libs.js
core.js
addon1.js
addon2.js

My clients will have to use the first 2 js files. and Addon will be included as they wish.

So far I've managed to separate my internal lib using CommonsChunkPlugin

new webpack.optimize.CommonsChunkPlugin({
    name: "libs",
    minChunks: function(module){
      return module.context && module.context.indexOf("\\libs\\internal\\") !== -1;
    },
  });

External libs are ignored using null-loader

{
   test: /libs\\external/,
   loader: 'null-loader'
},

my entry point js looks like this

import a from

"./core/a";
import b from "./core/b";
import addon1C from "./addons/addon1/c";

const myLib = {
   core: {a,b},
   addons: {addon1C}
}

export {myLib}

and now the problem starts with the core and addons.

If i'm skipping the addons part, in my client side including 2 scripts (libs, core)

and simply myLib.core.a is working.

The question do i prevent the bundling of the core code in the addons.

I've tried to do it with another chunk plugin but it causes some errors in the modules because the addon is using the core code and the entry point is using the addons to export it, so it doesn't find the module.

Tried 2 entry points so i will have the first entry point without the addons
and export the addons separately, but now the core code is bundled in it.

So, How do I do that ?
Or if there is a better way to do any of what I've done so far. i'm happy to learn.

Body:
In order to achieve that, I think you have to use a different approach. I had a similar situation where some other team needed to extend the core functionality of the application on demand.

In order to achieve that, I had to make sure that the core and the add-on's don't communicate each other directly. Instead, your core code should provide some kind of API that will be used by your add-on's.

From the other end, when your add-on's will try to import the core, you will have to provide a shim file, not the core itself.

I will try to write a couple of examples down here:

// core
export default const Core = {}
const addons = []
Core.addPlugin = function(addOn) {
   addons.push(addOn) // or doing something else
}

// shim-core.js
export default typeof window.Core !== undefined ? window.Core : Core

// add-on
import Core from 'shim-core'
const addOn = function() {
   // something funky
   return {}
}
Core.addPlugin(addOn)

I hope it helps you to understand the 'architecture'


来源: stackexchange

问:
How to redirect readthedocs web pages to other website
We started having our project's docs on readthedocs site (say http://abc.readthedocs.org). For various reasons we now moved to our own web servers with new domain (http://abc.io).

We want to bring down http://abc.readthedocs.org gracefully so that our project documentation is not broken all across the internet.

One way we are thinking is to have "redirects" from all pages with prefix (http://abc.readthedocs.org) to (http://abc.io).

But, I don't see any redirection options in readthedocs site that provides redirection to completely new domain. Readthedocs only allow redirection within different pages under same domain.

Any pointers on how I can proceed would be very helpful.

答:
I added the following section to my index.rst:

```<code>.. raw:: html

    <script type="text/javascript">
    if (String(window.location).indexOf("readthedocs") !== -1) {
        window.alert('The documentation has moved. I will redirect you to the new location.');
        window.location.replace('http://cosmo-docs.phys.ethz.ch/cosmoHammer');
    }
    </script>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I added the following section to my index.rst:

.. raw:: html

    <script type="text/javascript">
    if (String(window.location).indexOf("readthedocs") !== -1) {
        window.alert('The documentation has moved. I will redirect you to the new location.');
        window.location.replace('http://cosmo-docs.phys.ethz.ch/cosmoHammer');
    }
    </script>


问:
NameError: name 'urlpatterns' is not defined
I'm trying to show an image using "ImageField"

```<code>from django.conf.urls.static import static
from django.conf import settings
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
</code>```

settings.py:

```<code>STATIC_URL = '/static/'
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static"),
    )
MEDIA_ROOT = ''
MEDIA_URL = "/media/"
</code>```

答:
You need initialise urlpatterns first. Like,

```<code>urlpatterns = []
</code>```

Then, you can do this,

```<code>urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
</code>```

set your settings.py like this,

```<code>STATIC_URL = '/static/'
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static"),
    )
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
MEDIA_URL = "/media/"
</code>```

Body:
I'm trying to show an image using "ImageField"

from django.conf.urls.static import static
from django.conf import settings
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

settings.py:

STATIC_URL = '/static/'
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static"),
    )
MEDIA_ROOT = ''
MEDIA_URL = "/media/"

Body:
You need initialise urlpatterns first. Like,

urlpatterns = []

Then, you can do this,

urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

set your settings.py like this,

STATIC_URL = '/static/'
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static"),
    )
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
MEDIA_URL = "/media/"


问:
Database Patterns
Does anyone know of papers/books/etc. that document patterns for databases?  For example, one common rule of thumb is that every table should have a primary key and that the key should be devoid of information content.  So I was wondering if anyone had written a book or published papers regarding design patterns for designing relational databases?

@Gaius,

That is the question that a database designer needs to weigh--what is the probable stability of the database structure?  Given a long-enough horizon nothing is stable. Or to say the converse, given a long-enough horizon, everything is subject to change.  A surrogate key (in theory) should never change its meaning because it never had meaning to begin with.

I guess the other thing to consider in that particular design scenario is who is it that will be seeing the primary key?  If the primary key is something that end-users will actually need to refer to then it makes sense to make it something they can understand.  But I can't think of many cases where an end-user needs to see a primary key; usually the primary key is present to allow the DB engine to speed up certain operations.

My original thought in asking the question was to find design patterns for database design that were codified by more experienced database designers than myself so as to, hopefully, avoid some easily avoidable errors.  It would be interesting reading if anyone had ever codified database design anti-patterns.

答: Using primary keys with business meaning ("natural keys") certainly has its merits, but it can make refactoring your database very difficult.  Use caution, especially if there's any reason to believe the database structure will change over time.

OwnerDisplayName: Onorio Catenacci

Title: Database Patterns

OwnerDisplayName: Gaius

ContentLicense: CC BY-SA 2.5


问:
Optimizing Aggregate for String Concatenation
Update - for those of a facetious frame of mind, you can assume that Aggregate still produces the normal result whatever function is passed to it, including in the case being optimized.

I wrote this program to build a long string of integers from 0 to 19999 separate by commas.

```<code>using System;
using System.Linq;
using System.Diagnostics;

namespace ConsoleApplication5
{
    class Program
    {
        static void Main(string[] args)
        {
            const int size = 20000;

            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();
            Enumerable.Range(0, size).Select(n => n.ToString()).Aggregate((a, b) => a + ", " + b);
            stopwatch.Stop();

            Console.WriteLine(stopwatch.ElapsedMilliseconds + "ms");
        }
    }
}
</code>```

When I run it, it says:

```<code>5116ms
</code>```

Over five seconds, terrible. Of course it's because the whole string is being copied each time around the loop.

But what if make one very small change indicated by the comment?

```<code>using System;
using System.Linq;
using System.Diagnostics;

namespace ConsoleApplication5
{
    using MakeAggregateGoFaster;  // <---- inserted this

    class Program
    {
        static void Main(string[] args)
        {
            const int size = 20000;

            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();
            Enumerable.Range(0, size).Select(n => n.ToString()).Aggregate((a, b) => a + ", " + b);
            stopwatch.Stop();

            Console.WriteLine(stopwatch.ElapsedMilliseconds + "ms");
        }
    }
}
</code>```

Now when I run it, it says:

```<code>42ms
</code>```

Over 100x faster.

Question

What's in the MakeAggregateGoFaster namespace?

Update 2: Wrote up my answer here.

答:
Why not use one of the other forms of Aggregate?

```<code>Enumerable.Range(0, size ).Aggregate(new StringBuilder(),
        (a, b) => a.Append(", " + b.ToString()),
        (a) => a.Remove(0,2).ToString());
</code>```

You can specify any type for your seed, perform whatever formatting or custom calls are needed in the first lambda function and then customize the output type in the second lambda function.  The built in features already provide the flexibility you need.  My runs went from 1444ms to 6ms.

OwnerDisplayName: Earwicker

Body:
Update - for those of a facetious frame of mind, you can assume that Aggregate still produces the normal result whatever function is passed to it, including in the case being optimized.

I wrote this program to build a long string of integers from 0 to 19999 separate by commas.

using System;
using System.Linq;
using System.Diagnostics;

namespace ConsoleApplication5
{
    class Program
    {
        static void Main(string[] args)
        {
            const int size = 20000;

            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();
            Enumerable.Range(0, size).Select(n => n.ToString()).Aggregate((a, b) => a + ", " + b);
            stopwatch.Stop();

            Console.WriteLine(stopwatch.ElapsedMilliseconds + "ms");
        }
    }
}

When I run it, it says:

5116ms

Over five seconds, terrible. Of course it's because the whole string is being copied each time around the loop.

But what if make one very small change indicated by the comment?

using System;
using System.Linq;
using System.Diagnostics;

namespace ConsoleApplication5
{
    using MakeAggregateGoFaster;  // <---- inserted this

    class Program
    {
        static void Main(string[] args)
        {
            const int size = 20000;

            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();
            Enumerable.Range(0, size).Select(n => n.ToString()).Aggregate((a, b) => a + ", " + b);
            stopwatch.Stop();

            Console.WriteLine(stopwatch.ElapsedMilliseconds + "ms");
        }
    }
}

Now when I run it, it says:

42ms

Over 100x faster.

Question

What's in the MakeAggregateGoFaster namespace?

Update 2: Wrote up my answer here.

LastEditorDisplayName: Earwicker

Body:
Why not use one of the other forms of Aggregate?

Enumerable.Range(0, size ).Aggregate(new StringBuilder(),
        (a, b) => a.Append(", " + b.ToString()),
        (a) => a.Remove(0,2).ToString());

You can specify any type for your seed, perform whatever formatting or custom calls are needed in the first lambda function and then customize the output type in the second lambda function.  The built in features already provide the flexibility you need.  My runs went from 1444ms to 6ms.

OwnerDisplayName: davesem

LastEditorDisplayName: davesem


问:
Why do I have "Checksum fail" on every bad SQL request in Oracle when Native Encryption (ASO) is enabled?
We recently configured our Oracle database to be in so-called native encryption (Oracle Advanced Security Option).

As development goes on, some SQL queries are sometimes badly-written and so an error should be returned by the JDBC driver (ojdbc7 v12.1.0.2). Instead of that, a Checksum Fail IOException is raised.

So the problem is that we do not have anymore any syntax or database integrity error at all. The problem is the same in SQL GUI editors, like DBeaver, SQLDeveloper or SQuirrel.

答:
With driver ojdbc7 12.1.0.1 the correct VM parameter names are as follows:</p>

```<code>-Doracle.net.crypto_checksum_client=REQUIRED
-Doracle.net.crypto_checksum_types_client=SHA1
</code>```

Body:
With driver ojdbc7 12.1.0.1 the correct VM parameter names are as follows:

-Doracle.net.crypto_checksum_client=REQUIRED
-Doracle.net.crypto_checksum_types_client=SHA1


问:
Parsing table to regex method
I have this Javascript snippet :

```<code>var appId = document.URL;
var ele = [];
ele = appId.split('/', 5);
appId = ele[4];
</code>```

which extracts the sub-site name from some urls :

Example

http://www.test.com/france/Admin/Get.aspx  ==> Admin

www.test.com/france/Gallery ==> Gallery

It works fine, but I need to change the table approach to regex ie I need to get the string just after france.

What is the best way to do this?

答:
Try this pattern \/france\/(.*?(?=\/)|.*)

Demo regex and Explanation

Upadted
All matching with first position

console.log(find("http://www.test.com/france/Admin/Get.aspx"))
console.log(find("www.test.com/france/Gallery"))
console.log(find("test.com/france/Admin-en-france/Get.aspx"))

function find(str){
return /\/france\/(.*?(?=\/)|.*)/g.exec(str)[1]
}```

Title: Parsing table to regex method

Body:
I have this Javascript snippet :

var appId = document.URL;
var ele = [];
ele = appId.split('/', 5);
appId = ele[4];

which extracts the sub-site name from some urls :

Example

http://www.test.com/france/Admin/Get.aspx  ==> Admin

www.test.com/france/Gallery ==> Gallery

It works fine, but I need to change the table approach to regex ie I need to get the string just after france.

What is the best way to do this?


问:
Remove Underline Border Materialize Input Text
I try to make the border bottom of the text box (input text) disappear.

It's working with border-bottom: none but when I write something the border appear again. I want to make the green line disappear (the image show the page when I'm writing in the input).

Any idea?

答:
what you see is outline no border.For Fix it use outline: none;

For Example :

input[type="text"] {
  border-bottom: none;
  outline: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" name=""></code>```

Body:
what you see is outline no border.For Fix it use outline: none;

For Example :

input[type="text"] {
  border-bottom: none;
  outline: none;
}

<input type="text" name="">


问:
A cycle was detected in the build path of project xxx - Build Path Problem
I'm in the process of converting my projects to OSGI bundles using maven and eclipse. Maven builds the stuff just fine, only I get the above error now within Eclipse. How can I find out which project causes this? Is there a special view or something? How can this happen, I would expect that maven can detect cyclic dependencies as well?

Update

Ok, I found something
here
and
here

Could this be caused by the felix maven-bundle-plugin which does for each export also an import?

答: I have this problem,too.I just disable Workspace resolution,and then all was right.enter image description here</p>


问:
tfs build server - string interpolation $ Character is not valid
i am using string interpolation using $ in my code. It compiles fine but when i check in my code, the build server throws an error BC30037: Character is not valid. Following is an example on how i have used string interpolation:

```<code>dim r = New RadNode($"{acq.FormNo} -  ${CInt(acq.TotalAmount)}", icon:=RadTreeIcons.RedTriangle)
</code>```

The build server has Visual Studio 2015 Entreprise edition installed.

If i run this from command prompt:

C:\Program Files (x86)\MSBuild\14.0\Bin>MSBuild /tv:14.0 "Proj.sln", the code compiles file. However if i change the above argument to

C:\Program Files (x86)\MSBuild\14.0\Bin>MSBuild /tv:12.0 "Proj.sln", i get the same error

I have also made these changes:

i have set the MSBuildArguments Property to /p:VisualStudioVersion=14.0 and also changed the TFSBuild.proj file and changed this line to <Project DefaultTargets="DesktopBuild" xmlns="schemas.microsoft.com/developer/msbuild/2003"; ToolsVersion="14.0">" but same issue is happening.

Changed the (web vbproj) file and changed ToolSet Version to 14.0 from 12.0. Other vb projects part of the solution are still targeting 12.0 but gets compiled in dll as part of web vb project.

答:
when i check in my code, the build server throws an error, seems you are using a CI build. You could also give a try with manually queue the build. And build your code in local to narrow down if it's related to your TFS environment or not.

Also take a look at event view in the build agent/server, if there are some useful info.

Error BC30037: Character is not valid without TFxxxx may related to your code or syntax.

Check to see if an extra character has accidentally been inserted    into the programming element.

Check that the programming element is spelled or constructed using    only characters that are valid for that kind of element

Character is not valid

Body:
i am using string interpolation using $ in my code. It compiles fine but when i check in my code, the build server throws an error BC30037: Character is not valid. Following is an example on how i have used string interpolation:

dim r = New RadNode($"{acq.FormNo} -  ${CInt(acq.TotalAmount)}", icon:=RadTreeIcons.RedTriangle)

The build server has Visual Studio 2015 Entreprise edition installed.

If i run this from command prompt:

C:\Program Files (x86)\MSBuild\14.0\Bin>MSBuild /tv:14.0 "Proj.sln", the code compiles file. However if i change the above argument to

C:\Program Files (x86)\MSBuild\14.0\Bin>MSBuild /tv:12.0 "Proj.sln", i get the same error

I have also made these changes:

i have set the MSBuildArguments Property to /p:VisualStudioVersion=14.0 and also changed the TFSBuild.proj file and changed this line to <Project DefaultTargets="DesktopBuild" xmlns="schemas.microsoft.com/developer/msbuild/2003"; ToolsVersion="14.0">" but same issue is happening.

Changed the (web vbproj) file and changed ToolSet Version to 14.0 from 12.0. Other vb projects part of the solution are still targeting 12.0 but gets compiled in dll as part of web vb project.


问:
Selenium input text not working in JSF
I have some page in JSF2.0 where I need to validate fields. This is cross-field validation, so I binded fields to UIComponents. All three fields are <h:inputText> so all are binded to HtmlInputText.

Validation method just reads values from all the HtmlInputTexts. It works pretty well when I run the app and use it by hand. Problem is it doesn't work when selenium inputs values. Part of selenium code is:

```<code>selenium.type("identifier=myForm:myTextField", "someText");
</code>```

So it inputs text into the text field. It works and I can see text is really there. But when I debug validation method, which reads values from UIComponents, the value is null after clicking "Submit". It is not null when entered by hand, only when selenium enters it.

Why is that? Why selenium doesn't work? It does pretty the same I do by hand, yet it works by hand, doesn't work by selenium.

答: Note that JSF-generated IDs are usually not the ID you have assigned. For example myTextField in a form called myForm will have an ID myForm:myTextField

Title: Selenium input text not working in JSF

Body:
I have some page in JSF2.0 where I need to validate fields. This is cross-field validation, so I binded fields to UIComponents. All three fields are <h:inputText> so all are binded to HtmlInputText.

Validation method just reads values from all the HtmlInputTexts. It works pretty well when I run the app and use it by hand. Problem is it doesn't work when selenium inputs values. Part of selenium code is:

selenium.type("identifier=myForm:myTextField", "someText");

So it inputs text into the text field. It works and I can see text is really there. But when I debug validation method, which reads values from UIComponents, the value is null after clicking "Submit". It is not null when entered by hand, only when selenium enters it.

Why is that? Why selenium doesn't work? It does pretty the same I do by hand, yet it works by hand, doesn't work by selenium.


问:
Error when inserting data to Wordpress database. SQLSTATE[HY093]: Invalid parameter number
I am trying to make a code that can insert products in a WooCommerce installation (Wordpress). I keep getting this error, even tough the parameter count seems okay both in the database table (23 columns), query (23 columns) and values (also 23). I guess that something is wrong, but no matter how many times I check the code, everything seems fine to me.

```<code>$sqlinsert = "INSERT INTO wp_posts (ID,post_author,post_date,post_date_gmt,post_content,post_title,post_excerpt,post_status,comment_status,ping_status,post_password,post_name,to_ping,pinged,post_modified,post_modified_gmt,post_content_filtered,post_parent,guid,menu_order,post_type,post_mime_type,comment_count) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
              $sth = $dbh->prepare($sqlinsert);

              if($sth->execute(array(
                 "ID" => $id,
                 "post_author" => $post_author,
                 "post_date" => "NOW()",
                 "post_date_gmt" => "NOW()",
                 "post_content" => $post_content,
                 "post_title" => $post_title,
                 "post_excerpt" => $post_excerpt,
                 "post_status" => $post_status,
                 "comment_status" => $comment_status,
                 "ping_status" => $ping_status,
                 "post_password" => $post_password,
                 "post_name" => $post_name,
                 "to_ping" => $to_ping,
                 "pinged" => $pinged,
                 "post_modified" => "NOW()",
                 "post_modified_gmt" => "NOW()",
                 "post_content_filtered" => $post_content_filtered,
                 "post_parent" => $post_parent,
                 "guid" => $guid,
                 "menu_order" => $menu_order,
                 "post_type" => $post_type,
                 "post_mime_type" => $post_mime_type,
                 "comment_count" => $comment_count
              ))){
                 $contadorinsert++;
              }else{
                 $contadorerror++;
              }
</code>```

I have checked several times that none of the values are NULL, because all the fields in the Wordpress wp_posts tables are set to require NOT NULL values. This is the var_dump of my $post array, which contains all the values I am sending to the database:

/var/www/fs/plugins/importador_woocommerce/controller/importador_woocommerce.php:115:
array (size=18)
    'post_author' => int 1
    'post_title' => string 'SIME BRAVA SLIM 25BF ESTANCA NATURAL IONIZADA 8112500' (length=53)
    'post_content' => string '' (length=0)
    'post_excerpt' => string '' (length=0)
    'post_status' => string 'publish' (length=7)
    'comment_status' => string 'closed' (length=6)
    'ping_status' => string 'closed' (length=6)
    'post_password' => string '' (length=0)
    'post_name' => string '' (length=0)
    'to_ping' => string '' (length=0)
    'pinged' => string '' (length=0)
    'post_content_filtered' => string '' (length=0)
    'post_parent' => int 0
    'guid' => string 'http://fs.local/?post_type=product&p=' (length=37)
    'menu_order' => int 0
    'post_type' => string 'product' (length=7)
    'post_mime_type' => string '' (length=0)
    'comment_count' => int 0

The Wordpress original wp_posts table has the following structure (with utf8mb4_unicode_520_ci encoding instead of ut8_general_ci for the newer versions of Wordpress):

my table structure :

Any help is greatly appreciated. Thanks in advance.

答:
```<code>$currenttime= current_time( 'mysql' );
</code>```

Place this  $currenttime rather than now() at post_modified/post_modified_gmt

Body:
I am trying to make a code that can insert products in a WooCommerce installation (Wordpress). I keep getting this error, even tough the parameter count seems okay both in the database table (23 columns), query (23 columns) and values (also 23). I guess that something is wrong, but no matter how many times I check the code, everything seems fine to me.

$sqlinsert = "INSERT INTO wp_posts (ID,post_author,post_date,post_date_gmt,post_content,post_title,post_excerpt,post_status,comment_status,ping_status,post_password,post_name,to_ping,pinged,post_modified,post_modified_gmt,post_content_filtered,post_parent,guid,menu_order,post_type,post_mime_type,comment_count) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
              $sth = $dbh->prepare($sqlinsert);

              if($sth->execute(array(
                 "ID" => $id,
                 "post_author" => $post_author,
                 "post_date" => "NOW()",
                 "post_date_gmt" => "NOW()",
                 "post_content" => $post_content,
                 "post_title" => $post_title,
                 "post_excerpt" => $post_excerpt,
                 "post_status" => $post_status,
                 "comment_status" => $comment_status,
                 "ping_status" => $ping_status,
                 "post_password" => $post_password,
                 "post_name" => $post_name,
                 "to_ping" => $to_ping,
                 "pinged" => $pinged,
                 "post_modified" => "NOW()",
                 "post_modified_gmt" => "NOW()",
                 "post_content_filtered" => $post_content_filtered,
                 "post_parent" => $post_parent,
                 "guid" => $guid,
                 "menu_order" => $menu_order,
                 "post_type" => $post_type,
                 "post_mime_type" => $post_mime_type,
                 "comment_count" => $comment_count
              ))){
                 $contadorinsert++;
              }else{
                 $contadorerror++;
              }

I have checked several times that none of the values are NULL, because all the fields in the Wordpress wp_posts tables are set to require NOT NULL values. This is the var_dump of my $post array, which contains all the values I am sending to the database:

/var/www/fs/plugins/importador_woocommerce/controller/importador_woocommerce.php:115:
array (size=18)
    'post_author' => int 1
    'post_title' => string 'SIME BRAVA SLIM 25BF ESTANCA NATURAL IONIZADA 8112500' (length=53)
    'post_content' => string '' (length=0)
    'post_excerpt' => string '' (length=0)
    'post_status' => string 'publish' (length=7)
    'comment_status' => string 'closed' (length=6)
    'ping_status' => string 'closed' (length=6)
    'post_password' => string '' (length=0)
    'post_name' => string '' (length=0)
    'to_ping' => string '' (length=0)
    'pinged' => string '' (length=0)
    'post_content_filtered' => string '' (length=0)
    'post_parent' => int 0
    'guid' => string 'http://fs.local/?post_type=product&p=' (length=37)
    'menu_order' => int 0
    'post_type' => string 'product' (length=7)
    'post_mime_type' => string '' (length=0)
    'comment_count' => int 0

The Wordpress original wp_posts table has the following structure (with utf8mb4_unicode_520_ci encoding instead of ut8_general_ci for the newer versions of Wordpress):

my table structure :

Any help is greatly appreciated. Thanks in advance.

Body:
$currenttime= current_time( 'mysql' );

Place this  $currenttime rather than now() at post_modified/post_modified_gmt


问:
Keep User logged in on android webview (wordpress site)
i have developed a wordpress website and I used webview for the android app.
now my concern is that whenever a user log in to the app and opens the app after closing the app.I want to keep them logged in ! </p>

答: This is to be managed by wordpress side, and not in Android. </p>


问:
Converted all drawables to WebP, apk size stayed the same
Very confused. I just converted a lot of drawables in my res folder to the lossless WebP format. As I did it, Android Studio told me I saved 6mb, however I just build an production-release apk, one for the branch with WebP images and one with everything still as PNG, the difference is negligible. The PNG apk size is 23.2MB, the WebP apk size is 21.3.

I ran the apk analyzer tool, and I can see that the big difference is my res folder is now 7MB smaller, yet that wasn't translated to the apk size?

Here is the apk analyzer results, firstly the old apk (PNGs) Left number is uncompressed, right value is compressed, so what goes out to users in the apk:

Secondly here is the new apk (WebP):

The drawable files are quite clearly smaller, my biggest folder inside res is now 200kb.

Can someone who has played with WebP in Android offer some information on why this didn't work? No other numbers have changed in the apk analyzer.

Edit: Sorry about the small images, view in new tab to see clearer

答: You can get better results by using cwebp -near_lossless 40 for your PNG files. I doubt that the automated shrinkResources is able to use near lossless. This may give another 30-40 % compression gain, depending naturally a lot on what kind of graphics you have.


问:
Looping through all the variables that ends with a character in Batch
I was wondering if there's a simple way to loop through all the variables that end with a character in Batch?

For instance, I have the following variables set:

```<code>SET id1=something
SET id2=something1
SET id3=something3
</code>```

then I would like to loop through them using id* something like:

```<code>for %%a in ("%id*%") do echo %%a
</code>```

Using array is not an option for the use case that I have.

any ideas would be extremely appreciated.

答:
The answer you're looking for is:

```<code>Set id
</code>```

If you want to be able to split the result up then you can put it into a for loop:

```<code>For /F "Tokens=1* Delims==" %A In ('Set id') Do @Echo Variable %A is %B
</code>```

Double the % in a batch file.

Body:
I was wondering if there's a simple way to loop through all the variables that end with a character in Batch?

For instance, I have the following variables set:

SET id1=something
SET id2=something1
SET id3=something3

then I would like to loop through them using id* something like:

for %%a in ("%id*%") do echo %%a

Using array is not an option for the use case that I have.

any ideas would be extremely appreciated.

Body:
The answer you're looking for is:

Set id

If you want to be able to split the result up then you can put it into a for loop:

For /F "Tokens=1* Delims==" %A In ('Set id') Do @Echo Variable %A is %B

Double the % in a batch file.


问:
IndexError: index out of bounds in pandas
I am a beginner in pandas. I want to extract a column from excel file to python array with pandas.I want to run a loop through whole column. I want to print 1st data in that column.Here is my code:

```<code>import pandas as pd
xl_workbook = pd.ExcelFile("Summary.xlsx")  # Load the excel workbook
df = xl_workbook.parse("Sheet1")  # Parse the sheet into a dataframe
df['transactionqtr'] = pd.to_datetime(df['transactionqtr'],errors ='coerce')
df['commencementdate'] = pd.to_datetime(df['commencementdate'],errors ='coerce')
df=df.dropna()
df['transactionqtr'] = df['transactionqtr'].apply(lambdax:x.date().strftime('%m%d%y'))
df['commencementdate'] = df['commencementdate'].apply(lambda x:x.date().strftime('%m%d%y'))
arr1 = df['transactionqtr'][1][1]
arr2 = df['commencementdate'][1][1]
print(arr1)
print(arr2)
</code>```

But it shows IndexError: index out of bounds in this line:

```<code>arr1 = df['transactionqtr'][1][1]
arr2 = df['commencementdate'][1][1]
</code>```

How should I solve this? Please also guide me for better code.

答:
I think you need dt.strftime with tolist or values:

```<code>#if need list
arr1 = df['transactionqtr'].dt.strftime('%m%d%y').tolist()
arr2 = df['commencementdate'].dt.strftime('%m%d%y').tolist()

#if need numpy array
arr1 = df['transactionqtr'].dt.strftime('%m%d%y').values
arr2 = df['commencementdate'].dt.strftime('%m%d%y').values
</code>```

And for first value use indexing with []:

```<code>a = arr1[0]
</code>```

Body:
I am a beginner in pandas. I want to extract a column from excel file to python array with pandas.I want to run a loop through whole column. I want to print 1st data in that column.Here is my code:

import pandas as pd
xl_workbook = pd.ExcelFile("Summary.xlsx")  # Load the excel workbook
df = xl_workbook.parse("Sheet1")  # Parse the sheet into a dataframe
df['transactionqtr'] = pd.to_datetime(df['transactionqtr'],errors ='coerce')
df['commencementdate'] = pd.to_datetime(df['commencementdate'],errors ='coerce')
df=df.dropna()
df['transactionqtr'] = df['transactionqtr'].apply(lambdax:x.date().strftime('%m%d%y'))
df['commencementdate'] = df['commencementdate'].apply(lambda x:x.date().strftime('%m%d%y'))
arr1 = df['transactionqtr'][1][1]
arr2 = df['commencementdate'][1][1]
print(arr1)
print(arr2)

But it shows IndexError: index out of bounds in this line:

arr1 = df['transactionqtr'][1][1]
arr2 = df['commencementdate'][1][1]

How should I solve this? Please also guide me for better code.

Body:
I think you need dt.strftime with tolist or values:

#if need list
arr1 = df['transactionqtr'].dt.strftime('%m%d%y').tolist()
arr2 = df['commencementdate'].dt.strftime('%m%d%y').tolist()

#if need numpy array
arr1 = df['transactionqtr'].dt.strftime('%m%d%y').values
arr2 = df['commencementdate'].dt.strftime('%m%d%y').values

And for first value use indexing with []:

a = arr1[0]


问:
Where to find bootstrap classes' css definitons?
What I want is, for example, to change the css background color of navigations bar of .navbar-default, which can be done by .navbar-default{background-color:#000;}

But I want is, to see the full css style definitions of .navbar-default class, so I can look and change every element(text-color, hovering colors and every other thing) as I like. Rather than inspecting webpage elements for css codes from browsers, I want to look in a place where the definitions contain.

答:
If you are using the CDN "version" of Bootstrap, then you won't be able to edit the CSS.

A good way to do what you want is by using your own local copy of the bootstrap.css file. You'll find herein all the definitions, and you can alter them as per your wish.

Conversely, you could also edit the .sass or .less files if you want more control.

edit:

Since the OP is using CDN, follow the following steps and you should be just fine:

Identify the element/ tag that you want to edit: div, input, etc.

Identify the attribute you want to edit: color, height, etc.

most importantly: identify the class or id of the element.

After you've done the above, create a new styles file, for example: styles.css, and write your new custom CSS rules in there as per CSS rules.

Include this file by linking it in your .html file using the link tag

Voila!


问:
Comparing boolean and int using isinstance
Can someone give me an explanation why isinstance() returns True in the following case? I expected False, when writing the code.

```<code>print isinstance(True, (float, int))
True
</code>```

My guess would be that its Python's internal subclassing, as zero and one - whether float or int - both evaluate when used as boolean, but don't know the exact reason.

What would be the most pythonic way to solve such a situation? I could use type() but in most cases this is considered less pythonic.

答:
Yes, this is right, it's a subclass of int, you can verify it using the interpreter:

>>> int.__subclasses__()
[<type 'bool'>]
```

ContentLicense: CC BY-SA 4.0

Body:
Can someone give me an explanation why isinstance() returns True in the following case? I expected False, when writing the code.

print isinstance(True, (float, int))
True

My guess would be that its Python's internal subclassing, as zero and one - whether float or int - both evaluate when used as boolean, but don't know the exact reason.

What would be the most pythonic way to solve such a situation? I could use type() but in most cases this is considered less pythonic.


问:
Any ideas about how to check Azure's blob storage for viruses?
Our application stores files uploaded from our customers to blob storage. These files are exchanged between different parties (our customers and their suppliers). Is there a way to check the uploaded files for viruses? The Antimalware service seems to just check virtual machines, but I cannot get any information about using it to check files as a service.

A great solution would be if we could store such a file in Azure Storage as an "on hold" file till it is checked. Then we would need a service to check this file and returns the result. If the file is virus-free we could then move it to the final destination.

答:
As the other answer states Azure Storage is just storage. There are a couple of ways you could do this though,

The first solution would be to run your own anti-virus and use this either as a gateway or programatically download the file from the Blob storage, check the file and then take the appropriate action. It's possible to run something like ClamAV to do this yourself.

Alternatively you could use a third party service like AttachmentScanner (which is exactly what you mention in your comment) which will accept a URL or a direct file upload. With Azure you can generate a temporary url pointing to the file with an expiration of a few minutes, pass the URL to AttachmentScanner and then take the appropriate action depending on the result.


问:
Connecting to Postgres Database via Python
I am trying to connect to my database via Python 2.7 with this code:

```<code>import csv
import psycopg2

try:
    conn = psycopg2.connect("dbname='student', user='postgres',password='password', host='localhost'")
    cursor = conn_cursor()
    reader = csv.reader(open('last_file.csv', 'rb'))
    print "connected"
except:
    print "not Connected"
</code>```

It did work last week and we don't think we've changed anything, but now it won't connect.
We've tried using it with the database open and closed, nothing worked.
The database does exist in Postgres.

答:
Try this:</p>

```<code>import csv
import psycopg2

try:
    conn = psycopg2.connect("dbname='student', user='postgres',password='password', host='localhost'")
except:
    print "I am unable to connect to the database."
    cursor = conn.cursor()
try:
    reader = csv.reader(open('last_file.csv', 'rb'))
    print "connected"
except:
    print "not Connected"
</code>```

Body:
I am trying to connect to my database via Python 2.7 with this code:

import csv
import psycopg2

try:
    conn = psycopg2.connect("dbname='student', user='postgres',password='password', host='localhost'")
    cursor = conn_cursor()
    reader = csv.reader(open('last_file.csv', 'rb'))
    print "connected"
except:
    print "not Connected"

It did work last week and we don't think we've changed anything, but now it won't connect.
We've tried using it with the database open and closed, nothing worked.
The database does exist in Postgres.

Body:
Try this:

import csv
import psycopg2

try:
    conn = psycopg2.connect("dbname='student', user='postgres',password='password', host='localhost'")
except:
    print "I am unable to connect to the database."
    cursor = conn.cursor()
try:
    reader = csv.reader(open('last_file.csv', 'rb'))
    print "connected"
except:
    print "not Connected"


问:
What is an anonymous inode in Linux?
I made a google search about "anonymous inode" and it seems it's related to epoll ... but what actually is it?</p>

答:
open with O_TMPFILE

This would be a good definition of anonymous inode: it creates an inode inside a given directory without any name, which does not appear at all with ls.

Then when you close the descriptor the file is deleted.

It was added in Linux 3.11.

main.c

```<code>#define _GNU_SOURCE
#include <assert.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

int main(void) {
    char buf[]  = { 'a', 'b', 'c', 'd' };
    char buf2[]  = { 'e', 'f', 'g', 'h' };
    int f, ret;
    size_t off;

    /* write */
    f = open(".", O_TMPFILE | O_RDWR, S_IRUSR | S_IWUSR);
    ret = write(f, buf, sizeof(buf));

    /* Interactivelly check if anything changed on directory. It hasn't. */
    /*puts("hit enter to continue");*/
    /*getchar();*/

    /* read */
    lseek(f, 0, SEEK_SET);
    off = 0;
    while ((ret = read(f, buf2 + off, sizeof(buf) - off))) {
        off += ret;
    }
    close(f);
    assert(!memcmp(buf, buf2, sizeof(buf)));

    return EXIT_SUCCESS;
}
</code>```

GitHub upstream.

Compile and run:

```<code>gcc -o main.out -std=c99 -Wall -Wextra -pedantic  main.c
./main.out
</code>```

This is therefore essentially the optimal way of implementing temporary files: How to create a temporary text file in C++? as it can:

always immediately find a free name without us having to loop over filenames (no name is needed!)

and has automatic deletion

Compare that to a more manual method for directories as the one shown at: How to create a temporary directory in C++?

Tested in Ubuntu 17.04, Linux 4.10, glibc 2.24.

How O_TMPFILE looks like in /proc/PID/fd

We can examine it quickly with:

```<code>#define _GNU_SOURCE
#include <fcntl.h>
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

int main(void) {
    int f = open(".", O_TMPFILE | O_RDWR, S_IRUSR | S_IWUSR);
    struct stat s;
    fstat(f, &s);
    printf("pid %jd\n", (intmax_t)getpid());
    printf("inode %jd\n", (intmax_t)s.st_ino);
    getchar();
}
</code>```

then for a sample output:

```<code>pid 15952
inode 44698689
</code>```

we do:

```<code>ls -l /proc/15952/fd
</code>```

and that contains:

```<code>3 -> '/home/ciro/test/#44698689 (deleted)'
</code>```

which shows us how to find temporary files for a given process and see their inode and inode parent directory.

anon_inode_getfd Linux kernel function

If you are dealing with kernel modules, this is a likely definition.

You call it like:

```<code>fd = anon_inode_getfd("random", &fops_anon, NULL, O_RDONLY | O_CLOEXEC);
</code>```

and return fd to user, e.g. from an ioctl.

Now the user has an fd with associated arbitrary file_operations and inode, and when that fd is closed, everything is freed.

This method is useful e.g. if you want to have multiple read syscalls, but don't want to create multiple device files, which further pollutes /dev: you just create extra ioctls instead.

Minimal runnable example with QEMU Buildroot:

https://github.com/cirosantilli/linux-kernel-module-cheat/blob/de6c179fc0cf122789f0fe85cc69b847a1f4fe9c/kernel_module/anonymous_inode.c

https://github.com/cirosantilli/linux-kernel-module-cheat/blob/de6c179fc0cf122789f0fe85cc69b847a1f4fe9c/rootfs_overlay/anonymous_inode.sh

```<code>#include <asm/uaccess.h> /* copy_from_user, copy_to_user */
#include <linux/anon_inodes.h>
#include <linux/debugfs.h>
#include <linux/errno.h> /* EFAULT */
#include <linux/fs.h>
#include <linux/jiffies.h>
#include <linux/kernel.h> /* min */
#include <linux/module.h>
#include <linux/printk.h> /* printk */

#include "anonymous_inode.h"

MODULE_LICENSE("GPL");

static struct dentry *dir;

static ssize_t read(struct file *filp, char __user *buf, size_t len, loff_t *off)
{
    char kbuf[1024];
    size_t ret;

    ret = snprintf(kbuf, sizeof(kbuf), "%llu", (unsigned long long)jiffies);
    if (copy_to_user(buf, kbuf, ret)) {
        ret = -EFAULT;
    }
    return ret;
}

static const struct file_operations fops_anon = {
    .read = read,
};

static long unlocked_ioctl(struct file *filp, unsigned int cmd, unsigned long argp)
{
    int fd;

    switch (cmd) {
        case LKMC_ANONYMOUS_INODE_GET_FD:
            fd = anon_inode_getfd(
                "random",
                &fops_anon,
                NULL,
                O_RDONLY | O_CLOEXEC
            );
            if (copy_to_user((void __user *)argp, &fd, sizeof(fd))) {
                return -EFAULT;
            }
        break;
        default:
            return -EINVAL;
        break;
    }
    return 0;
}

static const struct file_operations fops_ioctl = {
    .owner = THIS_MODULE,
    .unlocked_ioctl = unlocked_ioctl
};

static int myinit(void)
{
    dir = debugfs_create_dir("lkmc_anonymous_inode", 0);
    debugfs_create_file("f", 0, dir, NULL, &fops_ioctl);
    return 0;
}

static void myexit(void)
{
    debugfs_remove_recursive(dir);
}

module_init(myinit)
module_exit(myexit)
</code>```

anon_inode in /proc/PID/fd

These are pipes and sockets, see: https://unix.stackexchange.com/questions/463548/what-is-anon-inode-in-the-output-of-ls-l

Title: What is an anonymous inode in Linux?

Body:
open with O_TMPFILE

This would be a good definition of anonymous inode: it creates an inode inside a given directory without any name, which does not appear at all with ls.

Then when you close the descriptor the file is deleted.

It was added in Linux 3.11.

main.c

#define _GNU_SOURCE
#include <assert.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

int main(void) {
    char buf[]  = { 'a', 'b', 'c', 'd' };
    char buf2[]  = { 'e', 'f', 'g', 'h' };
    int f, ret;
    size_t off;

    /* write */
    f = open(".", O_TMPFILE | O_RDWR, S_IRUSR | S_IWUSR);
    ret = write(f, buf, sizeof(buf));

    /* Interactivelly check if anything changed on directory. It hasn't. */
    /*puts("hit enter to continue");*/
    /*getchar();*/

    /* read */
    lseek(f, 0, SEEK_SET);
    off = 0;
    while ((ret = read(f, buf2 + off, sizeof(buf) - off))) {
        off += ret;
    }
    close(f);
    assert(!memcmp(buf, buf2, sizeof(buf)));

    return EXIT_SUCCESS;
}

GitHub upstream.

Compile and run:

gcc -o main.out -std=c99 -Wall -Wextra -pedantic  main.c
./main.out

This is therefore essentially the optimal way of implementing temporary files: How to create a temporary text file in C++? as it can:

always immediately find a free name without us having to loop over filenames (no name is needed!)

and has automatic deletion

Compare that to a more manual method for directories as the one shown at: How to create a temporary directory in C++?

Tested in Ubuntu 17.04, Linux 4.10, glibc 2.24.

How O_TMPFILE looks like in /proc/PID/fd

We can examine it quickly with:

#define _GNU_SOURCE
#include <fcntl.h>
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

int main(void) {
    int f = open(".", O_TMPFILE | O_RDWR, S_IRUSR | S_IWUSR);
    struct stat s;
    fstat(f, &s);
    printf("pid %jd\n", (intmax_t)getpid());
    printf("inode %jd\n", (intmax_t)s.st_ino);
    getchar();
}

then for a sample output:

pid 15952
inode 44698689

we do:

ls -l /proc/15952/fd

and that contains:

3 -> '/home/ciro/test/#44698689 (deleted)'

which shows us how to find temporary files for a given process and see their inode and inode parent directory.

anon_inode_getfd Linux kernel function

If you are dealing with kernel modules, this is a likely definition.

You call it like:

fd = anon_inode_getfd("random", &fops_anon, NULL, O_RDONLY | O_CLOEXEC);

and return fd to user, e.g. from an ioctl.

Now the user has an fd with associated arbitrary file_operations and inode, and when that fd is closed, everything is freed.

This method is useful e.g. if you want to have multiple read syscalls, but don't want to create multiple device files, which further pollutes /dev: you just create extra ioctls instead.

Minimal runnable example with QEMU Buildroot:

https://github.com/cirosantilli/linux-kernel-module-cheat/blob/de6c179fc0cf122789f0fe85cc69b847a1f4fe9c/kernel_module/anonymous_inode.c

https://github.com/cirosantilli/linux-kernel-module-cheat/blob/de6c179fc0cf122789f0fe85cc69b847a1f4fe9c/rootfs_overlay/anonymous_inode.sh

#include <asm/uaccess.h> /* copy_from_user, copy_to_user */
#include <linux/anon_inodes.h>
#include <linux/debugfs.h>
#include <linux/errno.h> /* EFAULT */
#include <linux/fs.h>
#include <linux/jiffies.h>
#include <linux/kernel.h> /* min */
#include <linux/module.h>
#include <linux/printk.h> /* printk */

#include "anonymous_inode.h"

MODULE_LICENSE("GPL");

static struct dentry *dir;

static ssize_t read(struct file *filp, char __user *buf, size_t len, loff_t *off)
{
    char kbuf[1024];
    size_t ret;

    ret = snprintf(kbuf, sizeof(kbuf), "%llu", (unsigned long long)jiffies);
    if (copy_to_user(buf, kbuf, ret)) {
        ret = -EFAULT;
    }
    return ret;
}

static const struct file_operations fops_anon = {
    .read = read,
};

static long unlocked_ioctl(struct file *filp, unsigned int cmd, unsigned long argp)
{
    int fd;

    switch (cmd) {
        case LKMC_ANONYMOUS_INODE_GET_FD:
            fd = anon_inode_getfd(
                "random",
                &fops_anon,
                NULL,
                O_RDONLY | O_CLOEXEC
            );
            if (copy_to_user((void __user *)argp, &fd, sizeof(fd))) {
                return -EFAULT;
            }
        break;
        default:
            return -EINVAL;
        break;
    }
    return 0;
}

static const struct file_operations fops_ioctl = {
    .owner = THIS_MODULE,
    .unlocked_ioctl = unlocked_ioctl
};

static int myinit(void)
{
    dir = debugfs_create_dir("lkmc_anonymous_inode", 0);
    debugfs_create_file("f", 0, dir, NULL, &fops_ioctl);
    return 0;
}

static void myexit(void)
{
    debugfs_remove_recursive(dir);
}

module_init(myinit)
module_exit(myexit)

anon_inode in /proc/PID/fd

These are pipes and sockets, see: https://unix.stackexchange.com/questions/463548/what-is-anon-inode-in-the-output-of-ls-l


问:
How can create Inter-Dependent SQL Jobs within SQL Agent
How can create Inter-Dependent SQL Jobs within SQL Agent,

For example:
Creating three SQL Jobs via script and want to schedule them inter-dependent like...
when first Job finish then second job should start and when second job finish then third job should start and so on

SAMPLE SCRIPT:

```<code>DECLARE @MyJobName varchar(50) = 'MyJob01'
EXEC msdb..sp_add_job @job_name =@MyJobName,@enabled=1, @start_step_id=1, @delete_level=1 --Job will delete itself after success
EXEC msdb..sp_add_jobstep @job_name=@MyJobName,@step_id=1, @step_name='STEP1',@command='SELECT * FROM TABLE1'
EXEC msdb..sp_add_jobserver @job_name =@MyJobName, @server_name = N'MySQLServer'
EXEC msdb..sp_start_job @job_name=@MyJobName

SET @MyJobName = 'MyJob02'
EXEC msdb..sp_add_job @job_name =@MyJobName, @enabled=1,    @start_step_id=1, @delete_level=1
EXEC msdb..sp_add_jobstep @job_name=@MyJobName,@step_id=1, @step_name='STEP1',@command='SELECT * FROM TABLE2'
EXEC msdb..sp_add_jobserver @job_name =@MyJobName, @server_name = N'MySQLServer'
EXEC msdb..sp_start_job @job_name=@MyJobName

SET @MyJobName = 'MyJob03'
EXEC msdb..sp_add_job @job_name =@MyJobName, @enabled=1,    @start_step_id=1, @delete_level=1
EXEC msdb..sp_add_jobstep @job_name=@MyJobName,@step_id=1, @step_name='STEP1',@command='SELECT * FROM TABLE3'
EXEC msdb..sp_add_jobserver @job_name =@MyJobName, @server_name = N'MySQLServer'
EXEC msdb..sp_start_job @job_name=@MyJobName
</code>```

答:
A job step can execute a SQL Server Agent job. So you can create another job that executes MyJob01, then MyJob02, then MyJob03. See sp_start_job. Something like</p>

```<code>EXEC dbo.sp_start_job N'MyJob01' ;
EXEC dbo.sp_start_job N'MyJob02' ;
EXEC dbo.sp_start_job N'MyJob03' ;
</code>```

Body:
How can create Inter-Dependent SQL Jobs within SQL Agent,

For example:
Creating three SQL Jobs via script and want to schedule them inter-dependent like...
when first Job finish then second job should start and when second job finish then third job should start and so on

SAMPLE SCRIPT:

DECLARE @MyJobName varchar(50) = 'MyJob01'
EXEC msdb..sp_add_job @job_name =@MyJobName,@enabled=1, @start_step_id=1, @delete_level=1 --Job will delete itself after success
EXEC msdb..sp_add_jobstep @job_name=@MyJobName,@step_id=1, @step_name='STEP1',@command='SELECT * FROM TABLE1'
EXEC msdb..sp_add_jobserver @job_name =@MyJobName, @server_name = N'MySQLServer'
EXEC msdb..sp_start_job @job_name=@MyJobName

SET @MyJobName = 'MyJob02'
EXEC msdb..sp_add_job @job_name =@MyJobName, @enabled=1,    @start_step_id=1, @delete_level=1
EXEC msdb..sp_add_jobstep @job_name=@MyJobName,@step_id=1, @step_name='STEP1',@command='SELECT * FROM TABLE2'
EXEC msdb..sp_add_jobserver @job_name =@MyJobName, @server_name = N'MySQLServer'
EXEC msdb..sp_start_job @job_name=@MyJobName

SET @MyJobName = 'MyJob03'
EXEC msdb..sp_add_job @job_name =@MyJobName, @enabled=1,    @start_step_id=1, @delete_level=1
EXEC msdb..sp_add_jobstep @job_name=@MyJobName,@step_id=1, @step_name='STEP1',@command='SELECT * FROM TABLE3'
EXEC msdb..sp_add_jobserver @job_name =@MyJobName, @server_name = N'MySQLServer'
EXEC msdb..sp_start_job @job_name=@MyJobName

Body:
A job step can execute a SQL Server Agent job. So you can create another job that executes MyJob01, then MyJob02, then MyJob03. See sp_start_job. Something like

EXEC dbo.sp_start_job N'MyJob01' ;
EXEC dbo.sp_start_job N'MyJob02' ;
EXEC dbo.sp_start_job N'MyJob03' ;


问:
Why do we need a generic here? Isn't the protocol enough?
I found the following example on the web about using generics together with protocols, however I don't understand why do we need generics at all, when all we need is to use a protocol.

We define a protocol:

```<code>protocol Healthy {
    mutating func setAlive(status: Bool)
    var health: Int { get }
}
</code>```

And then a function using a generic adotping that protocol

```<code>func check<T:Healthy>(inout object: T) {
    if (object.health <= 0) {
        object.setAlive(false)
    }
}
</code>```

I've changed the code as below and everything is still fine.

```<code>func check( object: inout Healthy) {
    if (object.health <= 0) {
        object.setAlive(status: false)
    }
}
</code>```

Or not?

The only reason I could think of to use a generic there, if it's a protocol has an associatedtype and it can't used as an instance.

答:
Because this is using an inout (ugh) and not returning a value means that the generic is not required.

When I would use a generic for this example is if the method signature was like this...

```<code>func check<T:Healthy>(object: T) -> T {
}
</code>```

This would then ensure that the type of object passed in and the type returned are the same type.

Without the generic you could pass in an instance of...

```<code>struct A: Healthy {}
</code>```

and return an instance of...

```<code>struct B: Healthy {}
</code>```

Hmm... maybe this is still the case with the inout. Can you create another struct that conforms to the protocol and change the object to an instance of your new struct? Maybe... will have to check that later.

Body:
I found the following example on the web about using generics together with protocols, however I don't understand why do we need generics at all, when all we need is to use a protocol.

We define a protocol:

protocol Healthy {
    mutating func setAlive(status: Bool)
    var health: Int { get }
}

And then a function using a generic adotping that protocol

func check<T:Healthy>(inout object: T) {
    if (object.health <= 0) {
        object.setAlive(false)
    }
}

I've changed the code as below and everything is still fine.

func check( object: inout Healthy) {
    if (object.health <= 0) {
        object.setAlive(status: false)
    }
}

Or not?

The only reason I could think of to use a generic there, if it's a protocol has an associatedtype and it can't used as an instance.

Body:
Because this is using an inout (ugh) and not returning a value means that the generic is not required.

When I would use a generic for this example is if the method signature was like this...

func check<T:Healthy>(object: T) -> T {
}

This would then ensure that the type of object passed in and the type returned are the same type.

Without the generic you could pass in an instance of...

struct A: Healthy {}

and return an instance of...

struct B: Healthy {}

Hmm... maybe this is still the case with the inout. Can you create another struct that conforms to the protocol and change the object to an instance of your new struct? Maybe... will have to check that later.


问:
Use of Scaler with LassoCV, RidgeCV
I would like to use scikit-learn LassoCV/RidgeCV while applying a 'StandardScaler' on each fold training set. I do not want to apply the scaler before the cross-validation to avoid leakage but I cannot figure out how I am supposed to do that with LassoCV/RidgeCV.

Is there a way to do this ? Or should I create a pipeline with Lasso/Ridge and 'manually' search for the hyperparameters (using GridSearchCV for instance) ?

Many thanks.

答:
If you want to apply the scaling to each iteration in cross-validation, you could use the make_pipeline function (this function will call "fit" on each training fold and call "transform" on each test fold)

The make_my_pipe below can be considered as an esitmator with a StandardScaler attached to it.

code:

```<code>from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
from sklearn.cross_validation import cross_val_score
from sklearn.linear_model import Ridge

X = "some data"
y = "the labels of the data"

make_my_pipe = make_pipeline(StandardScaler(), Ridge())
scores = cross_val_score(pipe, X, y)

print(scores)
</code>```

Title: Use of Scaler with LassoCV, RidgeCV

Body:
If you want to apply the scaling to each iteration in cross-validation, you could use the make_pipeline function (this function will call "fit" on each training fold and call "transform" on each test fold)

The make_my_pipe below can be considered as an esitmator with a StandardScaler attached to it.

code:

from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
from sklearn.cross_validation import cross_val_score
from sklearn.linear_model import Ridge

X = "some data"
y = "the labels of the data"

make_my_pipe = make_pipeline(StandardScaler(), Ridge())
scores = cross_val_score(pipe, X, y)

print(scores)


问:
Export HTML to EXCEL with PHP & jQuery

I would like to export an HTML table to a MS Excel document (and PDF ideally) as it is displayed on the HTML/CSS page. I read a lot of pages and topics about it (on stack mainly) but everyone seemed to be talking about exporting the table, and not formatting the final excel file.

I think it should work like this:

click on export button: call to jQuery

jQuery creates a pure HTML document from the HTML/CSS of the table

jQuery calls a PHP function/class (http://phpexcel.codeplex.com maybe) to generate the EXCEL file from the HTML code reformatted

With the headers sent by PHP, the browser asks the user to save/open the excel generated file

Would this work? If so do you know any jQuery plugins and PHP classes/functions to do so? If not, what is your ideas about it?

EDIT: Thanks to Matt, I came to the idea of using an XLS file template, is it possible? It will avoid me all the formatting as it would be done in the template file. Is it possible?

Cheers,

Nicolas.

答:
I finally choose to redo all the formatting with PHPexcel. The drawback is that if I change something in the HTML rendered I have to do the same in the PHPexcel helper I've created and vice versa.

Thank you for your suggestion everyone.

Nicolas.

Title: Export HTML to EXCEL with PHP & jQuery


问:
How to solve the error " missing required header GL/gl.h" while installing the Package mvoutlier in R?
I am trying to install the package mvoutlier but following error occurs during installation:

```<code>install.packages("mvoutlier")
configure: error: missing required header GL/gl.h
ERROR: configuration failed for package ‘rgl’
* removing ‘/home/sam/R/x86_64-pc-linux-gnu-library /2.15/rgl’
ERROR: dependency ‘rgl’ is not available for package ‘compositions’
* removing ‘/home/sam/R/x86_64-pc-linux-gnu-library/2.15/compositions’
ERROR: dependency ‘compositions’ is not available for package ‘mvoutlier’
* removing ‘/home/sam/R/x86_64-pc-linux-gnu-library/2.15/mvoutlier’
</code>```

After that I have install the rgl package successfully, then I tried to install the compositions package then the again same error occurs. Then I have again tried to install the mvoutlier package the same error occurs.

Can anyone let me know how I can resolve this problem. Thanking you in advance.

答: Based on the work breakdown by 3manuek, I figured only the libglu1-mesa-dev library was needed in ubuntu 16.04 LTS, and it worked.</p>

Body:
I am trying to install the package mvoutlier but following error occurs during installation:

install.packages("mvoutlier")
configure: error: missing required header GL/gl.h
ERROR: configuration failed for package ‘rgl’
* removing ‘/home/sam/R/x86_64-pc-linux-gnu-library /2.15/rgl’
ERROR: dependency ‘rgl’ is not available for package ‘compositions’
* removing ‘/home/sam/R/x86_64-pc-linux-gnu-library/2.15/compositions’
ERROR: dependency ‘compositions’ is not available for package ‘mvoutlier’
* removing ‘/home/sam/R/x86_64-pc-linux-gnu-library/2.15/mvoutlier’

After that I have install the rgl package successfully, then I tried to install the compositions package then the again same error occurs. Then I have again tried to install the mvoutlier package the same error occurs.

Can anyone let me know how I can resolve this problem. Thanking you in advance.


问:
How to process new files in HDFS directory once their writing has eventually finished?
In my scenario I have CSV files continuously uploaded to HDFS.

As soon as a new file gets uploaded I'd like to process the new file with Spark SQL (e.g., compute the maximum of a field in the file,  transform the file into parquet). i.e. I have a one-to-one mapping between each input file and a transformed/processed output file.

I was evaluating Spark Streaming to listen to the HDFS directory, then to process the "streamed file" with Spark.

However, in order to process the whole file I would need to know when the "file stream" completes. I'd like to apply the transformation to the whole file in order to preserve the end-to-end one-to-one mapping between files.

How can I transform the whole file and not its micro-batches?

As far as I know, Spark Streaming can only apply transformation to batches (DStreams mapped to RDDs) and not to the whole file at once (when its finite stream has completed).

Is that correct? If so, what alternative should I consider for my scenario?

答:
I may have misunderstood your question the first try...

As far as I know, Spark Streaming can only apply transformation to batches (DStreams mapped to RDDs) and not to the whole file at once (when its finite stream has completed).

Is that correct?

No. That's not correct.

Spark Streaming will apply transformation to the whole file at once as was written to HDFS at the time Spark Streaming's batch interval elapsed.

Spark Streaming will take the current content of a file and start processing it.

As soon as a new file gets uploaded I need to process the new file with Spark/SparkSQL

Almost impossible with Spark due to its architecture which takes some time from the moment "gets uploaded" and Spark processes it.

You should consider using a brand new and shiny Structured Streaming or (soon obsolete) Spark Streaming.

Both solutions support watching a directory for new files and trigger Spark job once a new file gets uploaded (which is exactly your use case).

Quoting Structured Streaming's Input Sources:

In Spark 2.0, there are a few built-in sources.

File source - Reads files written in a directory as a stream of data. Supported file formats are text, csv, json, parquet. See the docs of the DataStreamReader interface for a more up-to-date list, and supported options for each file format. Note that the files must be atomically placed in the given directory, which in most file systems, can be achieved by file move operations.

See also Spark Streaming's Basic Sources:

Besides sockets, the StreamingContext API provides methods for creating DStreams from files as input sources.

File Streams: For reading data from files on any file system compatible with the HDFS API (that is, HDFS, S3, NFS, etc.), a DStream can be created as:

```<code>streamingContext.fileStream[KeyClass, ValueClass, InputFormatClass](dataDirectory)
</code>```

Spark Streaming will monitor the directory dataDirectory and process any files created in that directory (files written in nested directories not supported).

One caveat though given your requirement:

I would need to know when the "file stream" completes.

Don't do this with Spark.

Quoting Spark Streaming's Basic Sources again:

The files must be created in the dataDirectory by atomically moving or renaming them into the data directory.

Once moved, the files must not be changed. So if the files are being continuously appended, the new data will not be read.

Wrapping up...you should only move the files to the directory that Spark watches when the files are complete and ready for processing using Spark. This is outside the scope of Spark.

Body:
I may have misunderstood your question the first try...

As far as I know, Spark Streaming can only apply transformation to batches (DStreams mapped to RDDs) and not to the whole file at once (when its finite stream has completed).

Is that correct?

No. That's not correct.

Spark Streaming will apply transformation to the whole file at once as was written to HDFS at the time Spark Streaming's batch interval elapsed.

Spark Streaming will take the current content of a file and start processing it.

As soon as a new file gets uploaded I need to process the new file with Spark/SparkSQL

Almost impossible with Spark due to its architecture which takes some time from the moment "gets uploaded" and Spark processes it.

You should consider using a brand new and shiny Structured Streaming or (soon obsolete) Spark Streaming.

Both solutions support watching a directory for new files and trigger Spark job once a new file gets uploaded (which is exactly your use case).

Quoting Structured Streaming's Input Sources:

In Spark 2.0, there are a few built-in sources.

File source - Reads files written in a directory as a stream of data. Supported file formats are text, csv, json, parquet. See the docs of the DataStreamReader interface for a more up-to-date list, and supported options for each file format. Note that the files must be atomically placed in the given directory, which in most file systems, can be achieved by file move operations.

See also Spark Streaming's Basic Sources:

Besides sockets, the StreamingContext API provides methods for creating DStreams from files as input sources.

File Streams: For reading data from files on any file system compatible with the HDFS API (that is, HDFS, S3, NFS, etc.), a DStream can be created as:

streamingContext.fileStream[KeyClass, ValueClass, InputFormatClass](dataDirectory)

Spark Streaming will monitor the directory dataDirectory and process any files created in that directory (files written in nested directories not supported).

One caveat though given your requirement:

I would need to know when the "file stream" completes.

Don't do this with Spark.

Quoting Spark Streaming's Basic Sources again:

The files must be created in the dataDirectory by atomically moving or renaming them into the data directory.

Once moved, the files must not be changed. So if the files are being continuously appended, the new data will not be read.

Wrapping up...you should only move the files to the directory that Spark watches when the files are complete and ready for processing using Spark. This is outside the scope of Spark.


问:
C# .NET web api return from post request
I am making a POST request to a route which is returning JSON data.

```<code>    [HttpPost("api/v1/testGetAll")]
    public object Test([FromBody]object filteringOptions)
    {
        return myService.GetLogs(filteringOptions).ToArray();
    }
</code>```

Route works fine, filtering works fine, and when I test the route in Postman I get the right response. However this is only a back-end, and I would like to invoke this route from my custom API gateway.

The issue I'm facing is getting that exact response back. Instead I am getting success status, headers, version, request message etc.

```<code>    public object TestGetAll(string ApiRoute, T json)
    {
        Task<HttpResponseMessage> response;
        var url = ApiHome + ApiRoute;
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri(url);
            client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
            try
            {
                response = client.PostAsync(url, new StringContent(json.ToString(), Encoding.UTF8, "application/json"));

                return response.Result;
            }
            catch (Exception e)
            {
                ...
            }
        }
    }
</code>```

How can I get exact content back?

答:
You need to read the content from response.

```<code>var contentString = response.Result.Content.ReadAsStringAsync().Result;
</code>```

If you wish, you can then deserialize the string response into the object you want returning.

```<code>public async Task<TResult> TestGetAll<TResult>(string apiRoute, string json)
{
    // For simplicity I've left out the using, but assume it in your code.

    var response = await client.PostAsJsonAsync(url, json);

    var resultString = await response.Content.ReadAsStringAsync();

    var result = JsonConvert.DeserializeObject<TResult>(resultString);

    return result;
}
</code>```

Body:
I am making a POST request to a route which is returning JSON data.

    [HttpPost("api/v1/testGetAll")]
    public object Test([FromBody]object filteringOptions)
    {
        return myService.GetLogs(filteringOptions).ToArray();
    }

Route works fine, filtering works fine, and when I test the route in Postman I get the right response. However this is only a back-end, and I would like to invoke this route from my custom API gateway.

The issue I'm facing is getting that exact response back. Instead I am getting success status, headers, version, request message etc.

    public object TestGetAll(string ApiRoute, T json)
    {
        Task<HttpResponseMessage> response;
        var url = ApiHome + ApiRoute;
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri(url);
            client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
            try
            {
                response = client.PostAsync(url, new StringContent(json.ToString(), Encoding.UTF8, "application/json"));

                return response.Result;
            }
            catch (Exception e)
            {
                ...
            }
        }
    }

How can I get exact content back?

Body:
You need to read the content from response.

var contentString = response.Result.Content.ReadAsStringAsync().Result;

If you wish, you can then deserialize the string response into the object you want returning.

public async Task<TResult> TestGetAll<TResult>(string apiRoute, string json)
{
    // For simplicity I've left out the using, but assume it in your code.

    var response = await client.PostAsJsonAsync(url, json);

    var resultString = await response.Content.ReadAsStringAsync();

    var result = JsonConvert.DeserializeObject<TResult>(resultString);

    return result;
}


问:
FreeMarker convert string with commas to number
I need to convert a locale specific string value having either commas or dot in between to indicate thousands separator, to a number in FreeMarker by removing the decimal places. For example: 13,456.79 to 13,456 OR 23.675,98 to 23.675

Using ?number throws exception saying this string can't be converted to a number. I see a similar question here:
Convert string with commas into integer in Freemarker but no solution exist. Is there a way to do so?

答:
I would parse the variable as Integer before (in the Controller/Business layer) exposing it to the template (and react in case of problems with the format).

In my opinion templates should handle nothing more than the presentation of (valid) data.

Alternately...

You can try to transform the string...

```<code><#function string_to_int s >
    <#local a = s?replace(",", "") >
    <#return a?keep_before_last(".") />
</#function>
</code>```

${string_to_int("13,456.79")}

will output

13456

Body:
I would parse the variable as Integer before (in the Controller/Business layer) exposing it to the template (and react in case of problems with the format).

In my opinion templates should handle nothing more than the presentation of (valid) data.

Alternately...

You can try to transform the string...

<#function string_to_int s >
    <#local a = s?replace(",", "") >
    <#return a?keep_before_last(".") />
</#function>

${string_to_int("13,456.79")}

will output

13456


问:
NuGet.Server returns 404 error
I have followed the instructions to setup and host my own NuGet feed.  I am running the web application on a Windows 2012 (IIS 8.5) box.

I build and run the solution and get the default.aspx page...

Which says "You are running NuGet.Server v2.8.60318.667"
and "Click here to view your packages".

When I click on the "here" link I get a "404 - File or directory not found." error.

I can successfully run a nuget.exe push command to put packages on
the Nuget server; however I get a 404 error when attempting to run
nugget.exe list command.

I have restarted IIS and the server

I have rebuilt the NuGet.Server web application from scratch.

I have tried hosting the NuGet.Server    on a Windows 7 box with no
success.

The Web.Config has the following entry

```<code><modules runAllManagedModulesForAllRequests="true">
</code>```

The web.config also has an entry to register the .nupkg extension as mimeType="application/zip"

It seems like the url routing is not working, but I can't seem to pin down what I am doing wrong.  Something is preventing the odata feed from working.

I know there are great 3rd party implementations of NuGet server, but I would really like to just get the free one working and it seems like it should be so easy. Any thoughts or troubleshooting tips would be appreciated.

答:
If you create a new empty VB project you will also get a 404 (in Packages and browsing using NuGet Manager).

You appear to have to create the project as C# and it works as advertised!

And yet the source code appears identical :(

Title: NuGet.Server returns 404 error

Body:
I have followed the instructions to setup and host my own NuGet feed.  I am running the web application on a Windows 2012 (IIS 8.5) box.

I build and run the solution and get the default.aspx page...

Which says "You are running NuGet.Server v2.8.60318.667"
and "Click here to view your packages".

When I click on the "here" link I get a "404 - File or directory not found." error.

I can successfully run a nuget.exe push command to put packages on
the Nuget server; however I get a 404 error when attempting to run
nugget.exe list command.

I have restarted IIS and the server

I have rebuilt the NuGet.Server web application from scratch.

I have tried hosting the NuGet.Server    on a Windows 7 box with no
success.

The Web.Config has the following entry

<modules runAllManagedModulesForAllRequests="true">

The web.config also has an entry to register the .nupkg extension as mimeType="application/zip"

It seems like the url routing is not working, but I can't seem to pin down what I am doing wrong.  Something is preventing the odata feed from working.

I know there are great 3rd party implementations of NuGet server, but I would really like to just get the free one working and it seems like it should be so easy. Any thoughts or troubleshooting tips would be appreciated.


问:
unlimited nested category in MYSQL using PHP
I want to create categories for products with no limit on how deep it can go.

is this possible. I read up on trees and  hierarchies. I'm confuse as to how i should go about. Please advice .

答:
have a table like this.

```<code>+----+-----------+------+
| id | parent_id | name |
+----+-----------+------+
</code>```

There you go, refer parent_id to same table and you have what you want.
As for a query? I suggest to either get all and write some code to generate the structure or if you're going to have thousands of categories, just get all with parent_id = 0 and query the children when you need.

Body:
have a table like this.

+----+-----------+------+
| id | parent_id | name |
+----+-----------+------+

There you go, refer parent_id to same table and you have what you want.
As for a query? I suggest to either get all and write some code to generate the structure or if you're going to have thousands of categories, just get all with parent_id = 0 and query the children when you need.