问:
Can't find how to use CONFIG:: directives properly
Let's say I have to compile two different versions of my .swf for different sites. The difference is in hostnames for the ajax and redirection, several minor tweaks in code and in graphics added to the project in .swc. I can switch different swcs easily, but the code tweaks are hard to manage easily. I've got

```<code>CONFIG::site1
{
    private var _domainName:String = "site1.com";
}

CONFIG::site2
{
    private var _domainName:String = "site2.com";
}
</code>```

FB brings up an error: 1151: A conflict exists with definition _domainName in namespace internal.

What I need is smthn like this in C:

```<code>#ifdef SITE1
char hostname[] = "site1";
#endif

#ifdef SITE2
char hostname[] = "site2";
#endif
</code>```

Is there any way to use compile directives that way using mxmlc?

P.S. Everything works now

答:
You could do this :

```<code>private var _domainName:String = CONFIG::site1 ? "site1.com" : "site2.com";
</code>```

If you want to know what's possible with configuration constants have a look at this page :

http://wiki.ecmascript.org/doku.php?id=proposals:program_configuration

So far I've found that the compiler support everything mentioned on this page.

Body:
Let's say I have to compile two different versions of my .swf for different sites. The difference is in hostnames for the ajax and redirection, several minor tweaks in code and in graphics added to the project in .swc. I can switch different swcs easily, but the code tweaks are hard to manage easily. I've got

CONFIG::site1
{
    private var _domainName:String = "site1.com";
}

CONFIG::site2
{
    private var _domainName:String = "site2.com";
}

FB brings up an error: 1151: A conflict exists with definition _domainName in namespace internal.

What I need is smthn like this in C:

#ifdef SITE1
char hostname[] = "site1";
#endif

#ifdef SITE2
char hostname[] = "site2";
#endif

Is there any way to use compile directives that way using mxmlc?

P.S. Everything works now

Body:
You could do this :

private var _domainName:String = CONFIG::site1 ? "site1.com" : "site2.com";

If you want to know what's possible with configuration constants have a look at this page :

http://wiki.ecmascript.org/doku.php?id=proposals:program_configuration

So far I've found that the compiler support everything mentioned on this page.


来源: stackexchange

问:
photoswipe js "Cannot read property 'x' of undefined"
Library return me error on photoswipe.min.js:
"Uncaught TypeError: Cannot read property 'x' of undefined"

myPhotoswipe code is the same on official site get start:

```<code>var initPhotoSwipeFromDOM = function(gallerySelector) {

// parse slide data (url, title, size ...) from DOM elements
// (children of gallerySelector)
var parseThumbnailElements = function(el) {
    var thumbElements = el.childNodes,
        numNodes = thumbElements.length,
        items = [],
        figureEl,
        linkEl,
        size,
        item;

    for(var i = 0; i < numNodes; i++) {

        figureEl = thumbElements[i]; // <figure> element
        // include only element nodes
        if(figureEl.nodeType !== 1) {
            continue;
        }

        linkEl = figureEl.children[0]; // <a> element

        size = linkEl.getAttribute('data-size').split('x');

        // create slide object
        item = {
            src: linkEl.getAttribute('href'),
            w: parseInt(size[0], 10),
            h: parseInt(size[1], 10)
        };

        if(figureEl.children.length > 1) {
            // <figcaption> content
            item.title = figureEl.children[1].innerHTML;
        }

        if(linkEl.children.length > 0) {
            // <img> thumbnail element, retrieving thumbnail url
            item.msrc = linkEl.children[0].getAttribute('src');
        }

        item.el = figureEl; // save link to element for getThumbBoundsFn
        items.push(item);
    }

    return items;
};

// find nearest parent element
var closest = function closest(el, fn) {
    return el && ( fn(el) ? el : closest(el.parentNode, fn) );
};

// triggers when user clicks on thumbnail
var onThumbnailsClick = function(e) {
    e = e || window.event;
    e.preventDefault ? e.preventDefault() : e.returnValue = false;

    var eTarget = e.target || e.srcElement;

    // find root element of slide
    var clickedListItem = closest(eTarget, function(el) {
        return (el.tagName && el.tagName.toUpperCase() === 'FIGURE');
    });

    if(!clickedListItem) {
        return;
    }

    // find index of clicked item by looping through all child nodes
    // alternatively, you may define index via data- attribute
    var clickedGallery = clickedListItem.parentNode,
        childNodes = clickedListItem.parentNode.childNodes,
        numChildNodes = childNodes.length,
        nodeIndex = 0,
        index;

    for (var i = 0; i < numChildNodes; i++) {
        if(childNodes[i].nodeType !== 1) {
            continue;
        }

        if(childNodes[i] === clickedListItem) {
            index = nodeIndex;
            break;
        }
        nodeIndex++;
    }

    if(index >= 0) {
        // open PhotoSwipe if valid index found
        openPhotoSwipe( index, clickedGallery );
    }
    return false;
};

// parse picture index and gallery index from URL (#&pid=1&gid=2)
var photoswipeParseHash = function() {
    var hash = window.location.hash.substring(1),
    params = {};

    if(hash.length < 5) {
        return params;
    }

    var vars = hash.split('&');
    for (var i = 0; i < vars.length; i++) {
        if(!vars[i]) {
            continue;
        }
        var pair = vars[i].split('=');
        if(pair.length < 2) {
            continue;
        }
        params[pair[0]] = pair[1];
    }

    if(params.gid) {
        params.gid = parseInt(params.gid, 10);
    }

    return params;
};

var openPhotoSwipe = function(index, galleryElement, disableAnimation, fromURL) {
    var pswpElement = document.querySelectorAll('.pswp')[0],
        gallery,
        options,
        items;

    items = parseThumbnailElements(galleryElement);

    // define options (if needed)
    options = {

        // define gallery index (for URL)
        galleryUID: galleryElement.getAttribute('data-pswp-uid'),

        getThumbBoundsFn: function(index) {
            // See Options -> getThumbBoundsFn section of documentation for more info
            var thumbnail = items[index].el.getElementsByTagName('span')[0], // find thumbnail
                pageYScroll = window.pageYOffset || document.documentElement.scrollTop,
                rect = thumbnail.getBoundingClientRect();

            return {x:rect.left, y:rect.top + pageYScroll, w:rect.width};
        }

    };

    // PhotoSwipe opened from URL
    if(fromURL) {
        if(options.galleryPIDs) {
            // parse real index when custom PIDs are used
            // http://photoswipe.com/documentation/faq.html#custom-pid-in-url
            for(var j = 0; j < items.length; j++) {
                if(items[j].pid == index) {
                    options.index = j;
                    break;
                }
            }
        } else {
            // in URL indexes start from 1
            options.index = parseInt(index, 10) - 1;
        }
    } else {
        options.index = parseInt(index, 10);
    }

    // exit if index not found
    if( isNaN(options.index) ) {
        return;
    }

    if(disableAnimation) {
        options.showAnimationDuration = 0;
    }

    // Pass data to PhotoSwipe and initialize it
    gallery = new PhotoSwipe( pswpElement, PhotoSwipeUI_Default, items, options);
    gallery.init();
};

// loop through all gallery elements and bind events
var galleryElements = document.querySelectorAll( gallerySelector );

for(var i = 0, l = galleryElements.length; i < l; i++) {
    galleryElements[i].setAttribute('data-pswp-uid', i+1);
    galleryElements[i].onclick = onThumbnailsClick;
}

// Parse URL and open gallery if it contains #&pid=3&gid=1
var hashData = photoswipeParseHash();
if(hashData.pid && hashData.gid) {
    openPhotoSwipe( hashData.pid ,  galleryElements[ hashData.gid - 1 ], true, true );
}
</code>```

};

// execute above function
initPhotoSwipeFromDOM('.my-gallery');

答:
Removing an inline style on the pswp template to display none fixed this for me. For example,

```<code><div class="pswp" tabindex="-1" role="dialog" aria-hidden="true" style="display:none">
</code>```

should be

```<code><div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Library return me error on photoswipe.min.js:
"Uncaught TypeError: Cannot read property 'x' of undefined"

myPhotoswipe code is the same on official site get start:

var initPhotoSwipeFromDOM = function(gallerySelector) {

// parse slide data (url, title, size ...) from DOM elements
// (children of gallerySelector)
var parseThumbnailElements = function(el) {
    var thumbElements = el.childNodes,
        numNodes = thumbElements.length,
        items = [],
        figureEl,
        linkEl,
        size,
        item;

    for(var i = 0; i < numNodes; i++) {

        figureEl = thumbElements[i]; //
 element
        // include only element nodes
        if(figureEl.nodeType !== 1) {
            continue;
        }

        linkEl = figureEl.children[0]; //  element

        size = linkEl.getAttribute('data-size').split('x');

        // create slide object
        item = {
            src: linkEl.getAttribute('href'),
            w: parseInt(size[0], 10),
            h: parseInt(size[1], 10)
        };

        if(figureEl.children.length > 1) {
            //
 content
            item.title = figureEl.children[1].innerHTML;
        }

        if(linkEl.children.length > 0) {
            //  thumbnail element, retrieving thumbnail url
            item.msrc = linkEl.children[0].getAttribute('src');
        }

        item.el = figureEl; // save link to element for getThumbBoundsFn
        items.push(item);
    }

    return items;
};

// find nearest parent element
var closest = function closest(el, fn) {
    return el && ( fn(el) ? el : closest(el.parentNode, fn) );
};

// triggers when user clicks on thumbnail
var onThumbnailsClick = function(e) {
    e = e || window.event;
    e.preventDefault ? e.preventDefault() : e.returnValue = false;

    var eTarget = e.target || e.srcElement;

    // find root element of slide
    var clickedListItem = closest(eTarget, function(el) {
        return (el.tagName && el.tagName.toUpperCase() === 'FIGURE');
    });

    if(!clickedListItem) {
        return;
    }

    // find index of clicked item by looping through all child nodes
    // alternatively, you may define index via data- attribute
    var clickedGallery = clickedListItem.parentNode,
        childNodes = clickedListItem.parentNode.childNodes,
        numChildNodes = childNodes.length,
        nodeIndex = 0,
        index;

    for (var i = 0; i < numChildNodes; i++) {
        if(childNodes[i].nodeType !== 1) {
            continue;
        }

        if(childNodes[i] === clickedListItem) {
            index = nodeIndex;
            break;
        }
        nodeIndex++;
    }

    if(index >= 0) {
        // open PhotoSwipe if valid index found
        openPhotoSwipe( index, clickedGallery );
    }
    return false;
};

// parse picture index and gallery index from URL (#&pid=1&gid=2)
var photoswipeParseHash = function() {
    var hash = window.location.hash.substring(1),
    params = {};

    if(hash.length < 5) {
        return params;
    }

    var vars = hash.split('&');
    for (var i = 0; i < vars.length; i++) {
        if(!vars[i]) {
            continue;
        }
        var pair = vars[i].split('=');
        if(pair.length < 2) {
            continue;
        }
        params[pair[0]] = pair[1];
    }

    if(params.gid) {
        params.gid = parseInt(params.gid, 10);
    }

    return params;
};

var openPhotoSwipe = function(index, galleryElement, disableAnimation, fromURL) {
    var pswpElement = document.querySelectorAll('.pswp')[0],
        gallery,
        options,
        items;

    items = parseThumbnailElements(galleryElement);

    // define options (if needed)
    options = {

        // define gallery index (for URL)
        galleryUID: galleryElement.getAttribute('data-pswp-uid'),

        getThumbBoundsFn: function(index) {
            // See Options -> getThumbBoundsFn section of documentation for more info
            var thumbnail = items[index].el.getElementsByTagName('span')[0], // find thumbnail
                pageYScroll = window.pageYOffset || document.documentElement.scrollTop,
                rect = thumbnail.getBoundingClientRect();

            return {x:rect.left, y:rect.top + pageYScroll, w:rect.width};
        }

    };

    // PhotoSwipe opened from URL
    if(fromURL) {
        if(options.galleryPIDs) {
            // parse real index when custom PIDs are used
            // http://photoswipe.com/documentation/faq.html#custom-pid-in-url
            for(var j = 0; j < items.length; j++) {
                if(items[j].pid == index) {
                    options.index = j;
                    break;
                }
            }
        } else {
            // in URL indexes start from 1
            options.index = parseInt(index, 10) - 1;
        }
    } else {
        options.index = parseInt(index, 10);
    }

    // exit if index not found
    if( isNaN(options.index) ) {
        return;
    }

    if(disableAnimation) {
        options.showAnimationDuration = 0;
    }

    // Pass data to PhotoSwipe and initialize it
    gallery = new PhotoSwipe( pswpElement, PhotoSwipeUI_Default, items, options);
    gallery.init();
};

// loop through all gallery elements and bind events
var galleryElements = document.querySelectorAll( gallerySelector );

for(var i = 0, l = galleryElements.length; i < l; i++) {
    galleryElements[i].setAttribute('data-pswp-uid', i+1);
    galleryElements[i].onclick = onThumbnailsClick;
}

// Parse URL and open gallery if it contains #&pid=3&gid=1
var hashData = photoswipeParseHash();
if(hashData.pid && hashData.gid) {
    openPhotoSwipe( hashData.pid ,  galleryElements[ hashData.gid - 1 ], true, true );
}

};

// execute above function
initPhotoSwipeFromDOM('.my-gallery');

Body:
Removing an inline style on the pswp template to display none fixed this for me. For example,

<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true" style="display:none">

should be

<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

ContentLicense: CC BY-SA 4.0


问:
Switch from ip address to domain name in Apache httpd (CentOS 7)
I'm trying to access the web from client by domain name using httpd. I'm already set up DNS server and Httpd, the result is root can access by domain name right now. Now is only the client, so i set up a virtual host:

```<code>#Setup to /etc/httpd/conf.d/vhost.conf
<VirtualHost 192.168.160.128:80>
   DocumentRoot /var/www/html
   ServerName www.trangweb.world
</VirtualHost>
</code>```

The domain is the one that root can access, but client now can access only by ip.
Somehow from client, i'm still cant access by domain name, what did i missing here?

答: The virtual host is set to listen for port 80 from the IP. If you set it to a * instead of IP, you will be able to access it by Domain name from anywhere.</p>

Body:
I'm trying to access the web from client by domain name using httpd. I'm already set up DNS server and Httpd, the result is root can access by domain name right now. Now is only the client, so i set up a virtual host:

#Setup to /etc/httpd/conf.d/vhost.conf
<VirtualHost 192.168.160.128:80>
   DocumentRoot /var/www/html
   ServerName www.trangweb.world
</VirtualHost>

The domain is the one that root can access, but client now can access only by ip.
Somehow from client, i'm still cant access by domain name, what did i missing here?


问:
DDB Throttling With Provisioned Capacity
I have a DDB table that I am trying to delete half of the keys from. I have all of the keys in hand that I want to delete and I am now using 8 processes with 32 threads each for 256 concurrency to batch delete keys.

I have been hitting throttles so I set the provisioned capacity well above the limit I'm hitting to see if that helps at all. It does not and I am still getting throttled heavily.

I do not have hot keys, and contributor insights show that I am being throttled on thousands of unique keys with at most 3-4 throttle events for the top throttled key.

I do have a GSI where each primary key may have 2-4 GSI primary keys on the flip side. But it is not showing throttling occurring on the GSI.

Any idea why I'd still be getting throttled?

答:
Each DynamoDB partition supports a maximum of 1000 WCUs. If delete requests are not hitting each partition equally you will get throttled before hitting your max provisioned WCUs.

You may not have hot keys, but you can still have hot partitions. Data might not be evenly balanced across partitions either, so even a completely uniform sample of keys on your side can result in unbalanced access to DynamoDB partitions.


问:
How to efficiently transform df?
I have the following df:

```<code>          CUI1      CUI2  tot
0     C0000699  C3894683    2
1     C0000699  C0101725    1
2     C0000699  C1882413    3
...        ...       ...  ...
9995  C0000715  C0026382   56
9996  C0000715  C0010334   101
...
</code>```

which I need to transform into a co-occurrence matrix:

```<code>          C0000699 C3894683 C0101725 C1882413 ... C0026382
C0000699  0        2        1        3            m
...
C3894683  2        0        n        p        ... q
...
etc..
</code>```

The df is extremely large (~11 m rows), and I have tried looping through it to set columns (using unstack and get_level, etc.), but it is taking an inordinate amount of time and memory.  Also, note, that pairs that have a count of 0 tot are not given in the initial stacked df.

Any vectorized solutions to speed this up and lower the memory footprint? The closest I could find was this constructing-a-co-occurrence-matrix-in-python-pandas, but the df is structured differently.

答:
you can try this.</p>
```<code>df.pivot_table(index='CUI1',columns='CUI2',values='tot')
</code>```

Title: How to efficiently transform df?

Body:
I have the following df:

          CUI1      CUI2  tot
0     C0000699  C3894683    2
1     C0000699  C0101725    1
2     C0000699  C1882413    3
...        ...       ...  ...
9995  C0000715  C0026382   56
9996  C0000715  C0010334   101
...

which I need to transform into a co-occurrence matrix:

          C0000699 C3894683 C0101725 C1882413 ... C0026382
C0000699  0        2        1        3            m
...
C3894683  2        0        n        p        ... q
...
etc..

The df is extremely large (~11 m rows), and I have tried looping through it to set columns (using unstack and get_level, etc.), but it is taking an inordinate amount of time and memory.  Also, note, that pairs that have a count of 0 tot are not given in the initial stacked df.

Any vectorized solutions to speed this up and lower the memory footprint? The closest I could find was this constructing-a-co-occurrence-matrix-in-python-pandas, but the df is structured differently.

Body:
you can try this.

df.pivot_table(index='CUI1',columns='CUI2',values='tot')


问:
How to close OneNote cleanly when a C# interop console app is closed
I am relatively new to C# and Visual Studio, and I am completely new to Microsoft.Office.Interop.OneNote. I have begun work on a console app using as a starting place the code in this answer, which is a reply to a question about writing to a OneNote app using C# and interop. My app does successfully retrieve content from a OneNote notebook, but I am not sure how to close the app in such a way that OneNote shuts down cleanly. Whenever I run the app in Visual Studio and then close the console, the next time I try to open OneNote, I get a message saying "We're sorry. OneNote is cleaning up from the last time it was open. Please wait." After about 30 seconds, this is followed by a message saying "It looks like OneNote is having trouble starting right now. If you keep seeing this message, restart your computer and start OneNote again. We're sorry."

It is impossible to open OneNote again until I either reboot or empty the contents of C:\users%userprofile%\appdata\local\temp.

What is the proper code to use to close out of OneNote cleanly, and/or how should I be closing my app inside Visual Studio? (As I said, I'm a noob.)

Here is my code:

```<code>using System;
using Word = Microsoft.Office.Interop.Word;
using OneNote = Microsoft.Office.Interop.OneNote;
using System.Runtime.InteropServices;
using System.Xml.Linq;
using System.Linq;

namespace OneNote_to_Word
{
    class Program
    {
        static OneNote.Application onenoteApp = new OneNote.Application();
        static XNamespace ns = null;

        static void Main(string[] args)
        {
            GetNamespace();
            string notebookId = GetObjectId(null, OneNote.HierarchyScope.hsNotebooks, "Notebook Name");
            string sectionId = GetObjectId(notebookId, OneNote.HierarchyScope.hsSections, "done");
            string firstPageId = GetObjectId(sectionId, OneNote.HierarchyScope.hsPages, "140506");
            GetPageContent(firstPageId);
            Console.Read();
        }
        static void GetNamespace()
        {
            string xml;

            onenoteApp.GetHierarchy(null, OneNote.HierarchyScope.hsNotebooks, out xml);
            var doc = XDocument.Parse(xml);
            ns = doc.Root.Name.Namespace;
        }

        static string GetObjectId(string parentId, OneNote.HierarchyScope scope, string objectName)
        {
            string xml;
            onenoteApp.GetHierarchy(parentId, scope, out xml);

            var doc = XDocument.Parse(xml);
            var nodeName = "";

            switch (scope)
            {
                case (OneNote.HierarchyScope.hsNotebooks): nodeName = "Notebook"; break;
                case (OneNote.HierarchyScope.hsPages): nodeName = "Page"; break;
                case (OneNote.HierarchyScope.hsSections): nodeName = "Section"; break;
                default:
                    return null;
            }

            var node = doc.Descendants(ns + nodeName).Where(n => n.Attribute("name").Value == objectName).FirstOrDefault();

            return node.Attribute("ID").Value;
        }
        static string GetPageContent(string pageId)
        {
            string xml;
            onenoteApp.GetPageContent(pageId, out xml, OneNote.PageInfo.piAll);
            var doc = XDocument.Parse(xml);
            var outLine = doc.Descendants(ns + "Outline").First();
            var content = outLine.Descendants(ns + "T").First();
            string contentVal = content.Value;
            //content.Value = "modified";
            //onenoteApp.UpdatePageContent(doc.ToString());
            Console.WriteLine(contentVal);
            return null;
        }
    }
}
</code>```

答:
At least for .NET < 5, I needed to add the following lines at the end of main():

```<code>    Marshal.FinalReleaseComObject(onenoteApp);
    onenoteApp = null;
    GC.Collect(); // Start .NET CLR Garbage Collection
    GC.WaitForPendingFinalizers(); // Wait for Garbage Collection to finish
</code>```

So main() now looks like this:

```<code>static void Main(string[] args)
    {
        GetNamespace();
        string notebookId = GetObjectId(null, OneNote.HierarchyScope.hsNotebooks, "My Notebook");
        string sectionId = GetObjectId(notebookId, OneNote.HierarchyScope.hsSections, "done");
        string firstPageId = GetObjectId(sectionId, OneNote.HierarchyScope.hsPages, "140506");
        GetPageContent(firstPageId);
        Marshal.FinalReleaseComObject(onenoteApp);
        onenoteApp = null;
        GC.Collect(); // Start .NET CLR Garbage Collection
        GC.WaitForPendingFinalizers(); // Wait for Garbage Collection to finish
    }
</code>```

However, in .NET 5, when I tried to use Marshal.FinalReleaseComObject(), Visual Studio complained that "This call site is reachable on all platforms. 'Marshal.FinalReleaseComObject(object)' is only supported on: 'windows'". This problem could be fixed by placing this line above the containing class, main() (cf. this answer):

```<code>[System.Runtime.Versioning.SupportedOSPlatform("windows")]
</code>```

Body:
I am relatively new to C# and Visual Studio, and I am completely new to Microsoft.Office.Interop.OneNote. I have begun work on a console app using as a starting place the code in this answer, which is a reply to a question about writing to a OneNote app using C# and interop. My app does successfully retrieve content from a OneNote notebook, but I am not sure how to close the app in such a way that OneNote shuts down cleanly. Whenever I run the app in Visual Studio and then close the console, the next time I try to open OneNote, I get a message saying "We're sorry. OneNote is cleaning up from the last time it was open. Please wait." After about 30 seconds, this is followed by a message saying "It looks like OneNote is having trouble starting right now. If you keep seeing this message, restart your computer and start OneNote again. We're sorry."

It is impossible to open OneNote again until I either reboot or empty the contents of C:\users%userprofile%\appdata\local\temp.

What is the proper code to use to close out of OneNote cleanly, and/or how should I be closing my app inside Visual Studio? (As I said, I'm a noob.)

Here is my code:

using System;
using Word = Microsoft.Office.Interop.Word;
using OneNote = Microsoft.Office.Interop.OneNote;
using System.Runtime.InteropServices;
using System.Xml.Linq;
using System.Linq;

namespace OneNote_to_Word
{
    class Program
    {
        static OneNote.Application onenoteApp = new OneNote.Application();
        static XNamespace ns = null;

        static void Main(string[] args)
        {
            GetNamespace();
            string notebookId = GetObjectId(null, OneNote.HierarchyScope.hsNotebooks, "Notebook Name");
            string sectionId = GetObjectId(notebookId, OneNote.HierarchyScope.hsSections, "done");
            string firstPageId = GetObjectId(sectionId, OneNote.HierarchyScope.hsPages, "140506");
            GetPageContent(firstPageId);
            Console.Read();
        }
        static void GetNamespace()
        {
            string xml;

            onenoteApp.GetHierarchy(null, OneNote.HierarchyScope.hsNotebooks, out xml);
            var doc = XDocument.Parse(xml);
            ns = doc.Root.Name.Namespace;
        }

        static string GetObjectId(string parentId, OneNote.HierarchyScope scope, string objectName)
        {
            string xml;
            onenoteApp.GetHierarchy(parentId, scope, out xml);

            var doc = XDocument.Parse(xml);
            var nodeName = "";

            switch (scope)
            {
                case (OneNote.HierarchyScope.hsNotebooks): nodeName = "Notebook"; break;
                case (OneNote.HierarchyScope.hsPages): nodeName = "Page"; break;
                case (OneNote.HierarchyScope.hsSections): nodeName = "Section"; break;
                default:
                    return null;
            }

            var node = doc.Descendants(ns + nodeName).Where(n => n.Attribute("name").Value == objectName).FirstOrDefault();

            return node.Attribute("ID").Value;
        }
        static string GetPageContent(string pageId)
        {
            string xml;
            onenoteApp.GetPageContent(pageId, out xml, OneNote.PageInfo.piAll);
            var doc = XDocument.Parse(xml);
            var outLine = doc.Descendants(ns + "Outline").First();
            var content = outLine.Descendants(ns + "T").First();
            string contentVal = content.Value;
            //content.Value = "modified";
            //onenoteApp.UpdatePageContent(doc.ToString());
            Console.WriteLine(contentVal);
            return null;
        }
    }
}

Body:
At least for .NET < 5, I needed to add the following lines at the end of main():

    Marshal.FinalReleaseComObject(onenoteApp);
    onenoteApp = null;
    GC.Collect(); // Start .NET CLR Garbage Collection
    GC.WaitForPendingFinalizers(); // Wait for Garbage Collection to finish

So main() now looks like this:

static void Main(string[] args)
    {
        GetNamespace();
        string notebookId = GetObjectId(null, OneNote.HierarchyScope.hsNotebooks, "My Notebook");
        string sectionId = GetObjectId(notebookId, OneNote.HierarchyScope.hsSections, "done");
        string firstPageId = GetObjectId(sectionId, OneNote.HierarchyScope.hsPages, "140506");
        GetPageContent(firstPageId);
        Marshal.FinalReleaseComObject(onenoteApp);
        onenoteApp = null;
        GC.Collect(); // Start .NET CLR Garbage Collection
        GC.WaitForPendingFinalizers(); // Wait for Garbage Collection to finish
    }

However, in .NET 5, when I tried to use Marshal.FinalReleaseComObject(), Visual Studio complained that "This call site is reachable on all platforms. 'Marshal.FinalReleaseComObject(object)' is only supported on: 'windows'". This problem could be fixed by placing this line above the containing class, main() (cf. this answer):

[System.Runtime.Versioning.SupportedOSPlatform("windows")]


问:
assign a value from a list to corresponding string on terminal
I am trying to do create a list with assigning the corresponding values from another list.

I have a file like this(list.txt);

```<code>.
.
ak_1002
ak_1002
ak_1014
ak_1017
ak_1017
ak_1239
ak_1246
ak_1284
ak_1286
ak_1320
ak_138
ak_139
.
.
</code>```

And another file with the corresponding values (ref.txt)

```<code>.
.
ak_1     39,877
ak_10    75,636
ak_100   32,936
ak_1000  81,609
ak_1002  30,946
ak_1003  40,862
ak_1004  96,566
ak_1005  50,778
ak_1006  62,698
ak_1007  47,8
ak_1008  37,895
ak_1009  126,501
ak_101   45,829
ak_1011  33,925
ak_1012  50,778
ak_1013  43,842
ak_1014  65,676
ak_1015  161,859
ak_1016  70,652
ak_1017  32,933
.
.
</code>```

I am trying to obtain a result file should be looking like this:

```<code>.
.
ak_1002 30,946
ak_1002 30,946
ak_1014 65,676
ak_1017 32,933
ak_1017 32,933
.
.
</code>```

Actually, I was using this code with other datasets and it was working perfectly, but right now it is returning no result.

```<code>awk 'FNR==NR{ arr[NR]=$0 }
    NR!=FNR{ for(i in arr){
      if(arr[i]==$1){ print arr[i],$2 } } }' list.txt ref.txt > result.txt
</code>```

PS: I am sure that there is only one corresponding value to every unique string, and also sure that all of the strings in the list.txt exist in ref.txt, because list.txt is a subset of ref.txt.

I could not figure out the reason. If you have any idea thank you in advance.

答:
You can use the join command:

join list.txt ref.txt
```
```ak_1002 30,946
ak_1002 30,946
ak_1014 65,676
ak_1017 32,933
ak_1017 32,933
```
<hr />
<p><strong>Update:</strong> handling <code>CRLF</code> line endings in <code>list.txt</code>:</p>
<pre class="lang-sh prettyprint-override"><code>#!/bin/bash

join <(sed $'s/\r$//' list.txt) ref.txt
</code>```

Body:
I am trying to do create a list with assigning the corresponding values from another list.

I have a file like this(list.txt);

.
.
ak_1002
ak_1002
ak_1014
ak_1017
ak_1017
ak_1239
ak_1246
ak_1284
ak_1286
ak_1320
ak_138
ak_139
.
.

And another file with the corresponding values (ref.txt)

.
.
ak_1     39,877
ak_10    75,636
ak_100   32,936
ak_1000  81,609
ak_1002  30,946
ak_1003  40,862
ak_1004  96,566
ak_1005  50,778
ak_1006  62,698
ak_1007  47,8
ak_1008  37,895
ak_1009  126,501
ak_101   45,829
ak_1011  33,925
ak_1012  50,778
ak_1013  43,842
ak_1014  65,676
ak_1015  161,859
ak_1016  70,652
ak_1017  32,933
.
.

I am trying to obtain a result file should be looking like this:

.
.
ak_1002 30,946
ak_1002 30,946
ak_1014 65,676
ak_1017 32,933
ak_1017 32,933
.
.

Actually, I was using this code with other datasets and it was working perfectly, but right now it is returning no result.

awk 'FNR==NR{ arr[NR]=$0 }
    NR!=FNR{ for(i in arr){
      if(arr[i]==$1){ print arr[i],$2 } } }' list.txt ref.txt > result.txt

PS: I am sure that there is only one corresponding value to every unique string, and also sure that all of the strings in the list.txt exist in ref.txt, because list.txt is a subset of ref.txt.

I could not figure out the reason. If you have any idea thank you in advance.

Body:
You can use the join command:

join list.txt ref.txt

ak_1002 30,946
ak_1002 30,946
ak_1014 65,676
ak_1017 32,933
ak_1017 32,933

Update: handling CRLF line endings in list.txt:

#!/bin/bash

join <(sed $'s/\r$//' list.txt) ref.txt


问:
Working with multiple processes in Ruby
Is there a module for Ruby that makes it easy to share objects between multiple processes?  I'm looking for something similar to Python's multiprocessing, which supports process-safe queues and pipes that can be shared between processes.</p>

答:
I think you can do a lot of what you want using the facilities of Ruby IO; you're sharing between processes, not threads, correct?

If that's the case, IO.pipe will do what you need.  Ruby doesn't have any built-in way of handling cross-process queues (to my knowledge), but you can also use FIFOs (if you're on Unix).

If you want something more fine-grained, and with good threading support, I'm fairly certain that you can piggyback on java.util.concurrent if you use JRuby.  MRI has pretty lousy threading/concurrency support, so if that's what your aiming for, JRuby is probably a better place to go.

OwnerDisplayName: Readonly

ContentLicense: CC BY-SA 2.5

Title: Working with multiple processes in Ruby

OwnerDisplayName: Don Werve


问:
Create-React-App with TypeScript failing to compile after importing Semantic UI
I've created a new React app by running npx create-react-app@latest --typescript . and I've run the project using npm start and it all works as expected. I ran npm install semantic-ui-react semantic-ui-css and that installs correctly.

But when I add import 'semantic-ui-css/semantic.min.css'; to index.tsx as instructed, I get a failed to compile error.

Here's my index.tsx file:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import 'semantic-ui-css/semantic.min.css';

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint.
reportWebVitals();
```
<p>Everything else is untouched.</p>
<p>If I remove <code>import 'semantic-ui-css/semantic.min.css';</code> from line 6 of <code>index.tsx</code> it compiles correctly. I'm guessing this is a Webpack issue, but I'm new to Webpack and I'm not sure how to solve the issue. I've tried setting the project up from scratch again but I get the same results.</p>
<p>I'm using <code>react 17.0.2</code>, <code>react scripts 5.0.0</code>, <code>semantic-ui-react 2.0.4</code> and <code>typescript 4.5.4</code>. Is there something obvious that I'm missing that would fix this?</p>
<p>And here is the error code I get:</p>
```Failed to compile.

Module build failed: UnhandledSchemeError: Reading from "data:application/x-font-ttf;charset=utf-8;;base64,AAEAAAAOAIAAAwBgT1MvMj3hSQEAAADsAAAAVmNtYXDQEhm3AAABRAAAAUpjdnQgBkn/lAAABuwAAAAcZnBnbYoKeDsAAAcIAAAJkWdhc3AAAAAQAAAG5AAAAAhnbHlm32cEdgAAApAAAAC2aGVhZAErPHsAAANIAAAANmhoZWEHUwNNAAADgAAAACRobXR4CykAAAAAA6QAAAAMbG9jYQA4AFsAAAOwAAAACG1heHAApgm8AAADuAAAACBuYW1lzJ0aHAAAA9gAAALNcG9zdK69QJgAAAaoAAAAO3ByZXCSoZr/AAAQnAAAAFYAAQO4AZAABQAIAnoCvAAAAIwCegK8AAAB4AAxAQIAAAIABQMAAAAAAAAAAAAAAAAAAAAAAAAYALAMI0IgYLABYbUNDQEACwBCQopgsQ0FK7BtKxsiWS2wDyyxAA4rLbAQLLEBDistsBEssQIOKy2wEiyxAw4rLbATLLEEDistsBQssQUOKy2wFSyxBg4rLbAWLLEHDistsBcssQgOKy2wGCyxCQ4rLbAZLrsDgrLbBpLLA1Ky6xJgEUKy2waiywNSuwNistsGsssDUrsDcrLbBsLLA1K7A4Ky2wbSwrsAhlsAMkUHiwARUwLQAAAEu4AMhSWLEBAY5ZuQgACABjILABI0SwAyNwsgQoCUVSRLIKAgcqsQYBRLEkAYhRWLBAiFixBgNEsSYBiFFYuAQAiFixBgFEWVlZWbgB/4WwBI2xBQBEAAA=" is not handled by plugins (Unhandled scheme).
Webpack supports "data:" and "file:" URIs by default.
You may need an additional plugin to handle "data:" URIs.
assets by path static/ 9.45 KiB
  asset static/js/node_modules_web-vitals_dist_web-vitals_js.chunk.js 6.88 KiB [emitted] 1 related asset
  asset static/media/logo.6ce24c58023cc2f8fd88fe9d219db6c6.svg 2.57 KiB [emitted] (auxiliary name: main)
asset index.html 1.62 KiB [emitted]
asset asset-manifest.json 429 bytes [emitted]
Entrypoint main (2.57 KiB) = 1 auxiliary asset
cached modules 2.72 MiB (javascript) 1.66 MiB (asset) 31.4 KiB (runtime) [cached] 150 modules
runtime modules 54 bytes 1 module
modules by layer 4.38 KiB (javascript) 1 bytes (asset)
  ./src/index.tsx 1.82 KiB [built] [code generated]
  ./src/App.tsx 2.51 KiB [built] [code generated]
  data:application/x-font-ttf;charset=utf-8;;base64,AAEAAAAOAIAAAwBgT1MvMj3hSQEAAADsAAAAVmNtYXDQEhm3AAABRAAAAUpjdnQgBkn/lAAABuwAAAAcZnBnbYoKeDsAAAcIAAAJkWdhc3AAAAAQAAAG5AAAAAhnbHlm32cEdgAAApAAAAC2aGVhZAErPHsAAANIAAAANmhoZWEHUwND4rLbBYLLIBAT4rLbBZLLIAADorLbBaLLIAATorLbBbLLIBADorLbBcLLIBATorLbBdLLAyKy6xJgEUKy2wXiywMiuwNistsF8ssDIrsDcrLbBgLLAAFrAyK7A4Ky2wYSywMysusSYBFCstsGIssDMrsDYrLbBjLLAzK7A3Ky2wZCywMyuwOCstsGUssDQrLrEmARQrLbBmLLA0K7A2Ky2wZyywNCuwNystsGgssDQrsDgrLbBpLLA1Ky6xJgEUKy2waiywNSuwNistsGsssDUrsDcrLbBsLLA1K7A4Ky2wbSwrsAhlsAMkUHiwARUwLQAAAEu4AMhSWLEBAY5ZuQgACABjILABI0SwAyNwsgQoCUVSRLIKAgcqsQYBRLEkAYhRWLBAiFixBgNEsSYBiFFYuAQAiFixBgFEWVlZWbgB/4WwBI2xBQBEAAA= 42 bytes (javascript) 1 bytes (asset) [built] [1 error]

ERROR in data:application/x-font-ttf;charset=utf-8;;base64,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
Module build failed: UnhandledSchemeError: Reading from "data:application/x-font-ttf;charset=utf-8;;base64,[encoded data, 5788 characters]" is not handled by plugins (Unhandled scheme).
Webpack supports "data:" and "file:" URIs by default.
You may need an additional plugin to handle "data:" URIs.
    at /Users/eamon/projects/frontend/node_modules/webpack/lib/NormalModule.js:825:25
    at Hook.eval [as callAsync] (eval at create (/Users/eamon/projects/frontend/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:16:1)
    at Hook.CALL_ASYNC_DELEGATE [as _callAsync] (/Users/eamon/projects/frontend/node_modules/tapable/lib/Hook.js:18:14)
    at Object.processResource (/Users/eamon/projects/frontend/node_modules/webpack/lib/NormalModule.js:822:8)
    at processResource (/Users/eamon/projects/frontend/node_modules/loader-runner/lib/LoaderRunner.js:220:11)
    at iteratePitchingLoaders (/Users/eamon/projects/frontend/node_modules/loader-runner/lib/LoaderRunner.js:171:10)
    at runLoaders (/Users/eamon/projects/frontend/node_modules/loader-runner/lib/LoaderRunner.js:397:2)
    at NormalModule._doBuild (/Users/eamon/projects/frontend/node_modules/webpack/lib/NormalModule.js:812:3)
    at NormalModule.build (/Users/eamon/projects/frontend/node_modules/webpack/lib/NormalModule.js:956:15)
    at /Users/eamon/projects/frontend/node_modules/webpack/lib/Compilation.js:1367:12
 @ ./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[1].oneOf[5].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[1].oneOf[5].use[2]!./node_modules/source-map-loader/dist/cjs.js!./node_modules/semantic-ui-css/semantic.min.css 22:37-5903
 @ ./node_modules/semantic-ui-css/semantic.min.css 8:6-230 22:17-24 26:7-21 58:25-39 59:36-47 59:50-64 63:6-73:7 64:54-65 64:68-82 70:42-53 70:56-70 72:21-28 83:0-200 83:0-200 84:22-29 84:33-47 84:50-64 61:4-74:5
 @ ./src/index.tsx 9:0-42

ERROR in [entry] [initial]
Cannot read properties of undefined (reading 'get')
during rendering of asset asset/inline|data:application/x-font-ttf;charset=utf-8;;base64,[encoded data, 5788 characters]
TypeError: Cannot read properties of undefined (reading 'get')
during rendering of asset asset/inline|data:application/x-font-ttf;charset=utf-8;;base64,[encoded data, 5788 characters]
    at /Users/eamon/projects/frontend/node_modules/webpack/lib/asset/AssetModulesPlugin.js:183:30
    at Hook.eval [as call] (eval at create (/Users/eamon/projects/frontend/node_modules/tapable/lib/HookCodeFactory.js:19:10), <anonymous>:12:16)
    at Hook.CALL_DELEGATE [as _call] (/Users/eamon/projects/frontend/node_modules/tapable/lib/Hook.js:14:14)
    at Compilation.getRenderManifest (/Users/eamon/projects/frontend/node_modules/webpack/lib/Compilation.js:4439:36)
    at /Users/eamon/projects/frontend/node_modules/webpack/lib/Compilation.js:4459:22
    at symbolIterator (/Users/eamon/projects/frontend/node_modules/neo-async/async.js:3482:9)
    at timesSync (/Users/eamon/projects/frontend/node_modules/neo-async/async.js:2297:7)
    at Object.eachLimit (/Users/eamon/projects/frontend/node_modules/neo-async/async.js:3463:5)
    at Compilation.createChunkAssets (/Users/eamon/projects/frontend/node_modules/webpack/lib/Compilation.js:4452:12)
    at /Users/eamon/projects/frontend/node_modules/webpack/lib/Compilation.js:3095:14

webpack 5.65.0 compiled with 2 errors in 1597 ms
Files successfully emitted, waiting for typecheck results...
Issues checking in progress...
No issues found.
```

答:
A good solution is use Fomantic-UI  that is a fork of semantic.
This is currently maintained.

Fomantic-UI

so, you can install, and then use it.

npm install fomantic-ui
```

Here is te official Fomantic:

Getting Started

And here is a tutorial for implementation and more info about Fomantic:

Medium - Fomantic

Why you should use Fomantic?

because Semantic development has come to a standstill and there were multiple issues started questioning the development.

Body:
I've created a new React app by running npx create-react-app@latest --typescript . and I've run the project using npm start and it all works as expected. I ran npm install semantic-ui-react semantic-ui-css and that installs correctly.

But when I add import 'semantic-ui-css/semantic.min.css'; to index.tsx as instructed, I get a failed to compile error.

Here's my index.tsx file:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import 'semantic-ui-css/semantic.min.css';

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint.
reportWebVitals();

Everything else is untouched.

If I remove import 'semantic-ui-css/semantic.min.css'; from line 6 of index.tsx it compiles correctly. I'm guessing this is a Webpack issue, but I'm new to Webpack and I'm not sure how to solve the issue. I've tried setting the project up from scratch again but I get the same results.

I'm using react 17.0.2, react scripts 5.0.0, semantic-ui-react 2.0.4 and typescript 4.5.4. Is there something obvious that I'm missing that would fix this?

And here is the error code I get:

Failed to compile.

Module build failed: UnhandledSchemeError: Reading from "data:application/x-font-ttf;charset=utf-8;;base64,AAEAAAAOAIAAAwBgT1MvMj3hSQEAAADsAAAAVmNtYXDQEhm3AAABRAAAAUpjdnQgBkn/lAAABuwAAAAcZnBnbYoKeDsAAAcIAAAJkWdhc3AAAAAQAAAG5AAAAAhnbHlm32cEdgAAApAAAAC2aGVhZAErPHsAAANIAAAANmhoZWEHUwNNAAADgAAAACRobXR4CykAAAAAA6QAAAAMbG9jYQA4AFsAAAOwAAAACG1heHAApgm8AAADuAAAACBuYW1lzJ0aHAAAA9gAAALNcG9zdK69QJgAAAaoAAAAO3ByZXCSoZr/AAAQnAAAAFYAAQO4AZAABQAIAnoCvAAAAIwCegK8AAAB4AAxAQIAAAIABQMAAAAAAAAAAAAAAAAAAAAAAAAYALAMI0IgYLABYbUNDQEACwBCQopgsQ0FK7BtKxsiWS2wDyyxAA4rLbAQLLEBDistsBEssQIOKy2wEiyxAw4rLbATLLEEDistsBQssQUOKy2wFSyxBg4rLbAWLLEHDistsBcssQgOKy2wGCyxCQ4rLbAZLrsDgrLbBpLLA1Ky6xJgEUKy2waiywNSuwNistsGsssDUrsDcrLbBsLLA1K7A4Ky2wbSwrsAhlsAMkUHiwARUwLQAAAEu4AMhSWLEBAY5ZuQgACABjILABI0SwAyNwsgQoCUVSRLIKAgcqsQYBRLEkAYhRWLBAiFixBgNEsSYBiFFYuAQAiFixBgFEWVlZWbgB/4WwBI2xBQBEAAA=" is not handled by plugins (Unhandled scheme).
Webpack supports "data:" and "file:" URIs by default.
You may need an additional plugin to handle "data:" URIs.
assets by path static/ 9.45 KiB
  asset static/js/node_modules_web-vitals_dist_web-vitals_js.chunk.js 6.88 KiB [emitted] 1 related asset
  asset static/media/logo.6ce24c58023cc2f8fd88fe9d219db6c6.svg 2.57 KiB [emitted] (auxiliary name: main)
asset index.html 1.62 KiB [emitted]
asset asset-manifest.json 429 bytes [emitted]
Entrypoint main (2.57 KiB) = 1 auxiliary asset
cached modules 2.72 MiB (javascript) 1.66 MiB (asset) 31.4 KiB (runtime) [cached] 150 modules
runtime modules 54 bytes 1 module
modules by layer 4.38 KiB (javascript) 1 bytes (asset)
  ./src/index.tsx 1.82 KiB [built] [code generated]
  ./src/App.tsx 2.51 KiB [built] [code generated]
  data:application/x-font-ttf;charset=utf-8;;base64,AAEAAAAOAIAAAwBgT1MvMj3hSQEAAADsAAAAVmNtYXDQEhm3AAABRAAAAUpjdnQgBkn/lAAABuwAAAAcZnBnbYoKeDsAAAcIAAAJkWdhc3AAAAAQAAAG5AAAAAhnbHlm32cEdgAAApAAAAC2aGVhZAErPHsAAANIAAAANmhoZWEHUwND4rLbBYLLIBAT4rLbBZLLIAADorLbBaLLIAATorLbBbLLIBADorLbBcLLIBATorLbBdLLAyKy6xJgEUKy2wXiywMiuwNistsF8ssDIrsDcrLbBgLLAAFrAyK7A4Ky2wYSywMysusSYBFCstsGIssDMrsDYrLbBjLLAzK7A3Ky2wZCywMyuwOCstsGUssDQrLrEmARQrLbBmLLA0K7A2Ky2wZyywNCuwNystsGgssDQrsDgrLbBpLLA1Ky6xJgEUKy2waiywNSuwNistsGsssDUrsDcrLbBsLLA1K7A4Ky2wbSwrsAhlsAMkUHiwARUwLQAAAEu4AMhSWLEBAY5ZuQgACABjILABI0SwAyNwsgQoCUVSRLIKAgcqsQYBRLEkAYhRWLBAiFixBgNEsSYBiFFYuAQAiFixBgFEWVlZWbgB/4WwBI2xBQBEAAA= 42 bytes (javascript) 1 bytes (asset) [built] [1 error]

ERROR in data:application/x-font-ttf;charset=utf-8;;base64,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
Module build failed: UnhandledSchemeError: Reading from "data:application/x-font-ttf;charset=utf-8;;base64,[encoded data, 5788 characters]" is not handled by plugins (Unhandled scheme).
Webpack supports "data:" and "file:" URIs by default.
You may need an additional plugin to handle "data:" URIs.
    at /Users/eamon/projects/frontend/node_modules/webpack/lib/NormalModule.js:825:25
    at Hook.eval [as callAsync] (eval at create (/Users/eamon/projects/frontend/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:16:1)
    at Hook.CALL_ASYNC_DELEGATE [as _callAsync] (/Users/eamon/projects/frontend/node_modules/tapable/lib/Hook.js:18:14)
    at Object.processResource (/Users/eamon/projects/frontend/node_modules/webpack/lib/NormalModule.js:822:8)
    at processResource (/Users/eamon/projects/frontend/node_modules/loader-runner/lib/LoaderRunner.js:220:11)
    at iteratePitchingLoaders (/Users/eamon/projects/frontend/node_modules/loader-runner/lib/LoaderRunner.js:171:10)
    at runLoaders (/Users/eamon/projects/frontend/node_modules/loader-runner/lib/LoaderRunner.js:397:2)
    at NormalModule._doBuild (/Users/eamon/projects/frontend/node_modules/webpack/lib/NormalModule.js:812:3)
    at NormalModule.build (/Users/eamon/projects/frontend/node_modules/webpack/lib/NormalModule.js:956:15)
    at /Users/eamon/projects/frontend/node_modules/webpack/lib/Compilation.js:1367:12
 @ ./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[1].oneOf[5].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[1].oneOf[5].use[2]!./node_modules/source-map-loader/dist/cjs.js!./node_modules/semantic-ui-css/semantic.min.css 22:37-5903
 @ ./node_modules/semantic-ui-css/semantic.min.css 8:6-230 22:17-24 26:7-21 58:25-39 59:36-47 59:50-64 63:6-73:7 64:54-65 64:68-82 70:42-53 70:56-70 72:21-28 83:0-200 83:0-200 84:22-29 84:33-47 84:50-64 61:4-74:5
 @ ./src/index.tsx 9:0-42

ERROR in [entry] [initial]
Cannot read properties of undefined (reading 'get')
during rendering of asset asset/inline|data:application/x-font-ttf;charset=utf-8;;base64,[encoded data, 5788 characters]
TypeError: Cannot read properties of undefined (reading 'get')
during rendering of asset asset/inline|data:application/x-font-ttf;charset=utf-8;;base64,[encoded data, 5788 characters]
    at /Users/eamon/projects/frontend/node_modules/webpack/lib/asset/AssetModulesPlugin.js:183:30
    at Hook.eval [as call] (eval at create (/Users/eamon/projects/frontend/node_modules/tapable/lib/HookCodeFactory.js:19:10), <anonymous>:12:16)
    at Hook.CALL_DELEGATE [as _call] (/Users/eamon/projects/frontend/node_modules/tapable/lib/Hook.js:14:14)
    at Compilation.getRenderManifest (/Users/eamon/projects/frontend/node_modules/webpack/lib/Compilation.js:4439:36)
    at /Users/eamon/projects/frontend/node_modules/webpack/lib/Compilation.js:4459:22
    at symbolIterator (/Users/eamon/projects/frontend/node_modules/neo-async/async.js:3482:9)
    at timesSync (/Users/eamon/projects/frontend/node_modules/neo-async/async.js:2297:7)
    at Object.eachLimit (/Users/eamon/projects/frontend/node_modules/neo-async/async.js:3463:5)
    at Compilation.createChunkAssets (/Users/eamon/projects/frontend/node_modules/webpack/lib/Compilation.js:4452:12)
    at /Users/eamon/projects/frontend/node_modules/webpack/lib/Compilation.js:3095:14

webpack 5.65.0 compiled with 2 errors in 1597 ms
Files successfully emitted, waiting for typecheck results...
Issues checking in progress...
No issues found.

Body:
A good solution is use Fomantic-UI  that is a fork of semantic.
This is currently maintained.

Fomantic-UI

so, you can install, and then use it.

npm install fomantic-ui

Here is te official Fomantic:

Getting Started

And here is a tutorial for implementation and more info about Fomantic:

Medium - Fomantic

Why you should use Fomantic?

because Semantic development has come to a standstill and there were multiple issues started questioning the development.


问:
what is an alternative version of sys.sdout.flush() except its on kivy ui texts?
the question is pretty simple but yeah couldnt find an answer, I've asked previously before too but yeah no responses and even views, so made my goal more clear this time
example, this doesnt work. it will wait until the full char adding to the text is done and THEN show the text</p>
```<code>class buttonex(BoxLayout):
    mytext=StringProperty("helloyes")
    hello=ObjectProperty(None)
    def on_button_click(self):
        self.hello.text=""
        for char in "hi noob lol hahaha":
            sleep(0.07)
            self.hello.text=self.hello.text+char
</code>```

答:
Addressing the question,

what is an alternative version of sys.sdout.flush() except its on kivy ui texts?

Here is a simple implementation using Clock.

from kivy.app import App
from kivy.clock import Clock
from kivy.lang import Builder
from kivy.properties import (NumericProperty, StringProperty)
from kivy.uix.boxlayout import BoxLayout

Builder.load_string("""

<TextBox>:
    orientation: "vertical"
    padding: "10dp"

    Label:
        id: label

    TextInput:
        multiline: 0
        hint_text: "Enter text and hit enter"
        on_text_validate: root.type_text(self.text)

""")

class TextBox(BoxLayout):

    cache_text = StringProperty("") # For storing the entered text.
    index = NumericProperty(0) # For iteration over cache_text.

    def type_text(self, txt, *args):
        self.cache_text = txt # Store the entered text here.
        # For more control you may use method Clock.create_trigger.
        self.ev = Clock.schedule_interval(self.update_text, 0.25) # Update text after every 0.25 sec.

    def update_text(self, *args):
        if self.index < len(self.cache_text):
            val = self.cache_text[self.index]
            self.ids.label.text += val # Appending to existing text.
            self.index += 1
        else:
            self.ids.label.text = "" # Comment it out to retain the text.
            self.index = 0 # Reset index.
            self.cache_text = "" # Clear cache.
            self.ev.cancel() # Cancel text updation.

class TestApp(App):

    def build(self):
        return TextBox()

TestApp().run()
```

Body:
the question is pretty simple but yeah couldnt find an answer, I've asked previously before too but yeah no responses and even views, so made my goal more clear this time
example, this doesnt work. it will wait until the full char adding to the text is done and THEN show the text

class buttonex(BoxLayout):
    mytext=StringProperty("helloyes")
    hello=ObjectProperty(None)
    def on_button_click(self):
        self.hello.text=""
        for char in "hi noob lol hahaha":
            sleep(0.07)
            self.hello.text=self.hello.text+char


问:
tspath collects incorrect paths
I have an express application that I develop with typescript, I want to use relative paths, without using tspath, because it doesn't work correctly. Here I will give a couple of examples of his mistakes.

my tsconfig.v1 -> input -> output Here I am getting error during dev process in my ts file, and my output file correct

my tsconfig.v2 -> input -> output But this time I get wrong path in my output file :D

if i try use this tsconfig.v3 i get next error errorLog

Tell me, are there any alternatives, or is my tsconfig not correct?

答: I found an alternative, this is tscpaths, the name is very similar, but they have at least some instructions that helped me build my output project well</p>

Title: tspath collects incorrect paths


问:
reactstrap tooltip dynamic id
I am developing a react application and using reactstrap.

I am using Tooltip Component of reactstrap which requires a target attribute, a value of target element's id. This id is being geneated dynamically and seems reactstrap tooltip doesn't like it.

Component looks like:

MovieCard.jsx

```<code>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Col, Card, CardImg, CardBody, CardTitle, CardSubtitle, CardText, Button, Tooltip } from 'reactstrap';
import { LimitedTextTitle } from '../custom-styled/CustomStyledComponents';

class MovieCard extends Component {

  constructor (props) {
    super(props);
    this.state = {
      open: false
    };
    this.toggle = this.toggle.bind(this);
  }

  toggle () {
    this.setState({
      open: !this.state.open
    })
  }

  render () {
    const { imdbID, Title, Year, Rated, Plot, Country, Poster } = this.props.movie;

    return (
  <Col md="4">
    <Card>
      <CardImg
        top
        width="100%"
        src={Poster}
        alt="blah"
      />
    </Card>
    <CardBody>
      <CardTitle>
        <LimitedTextTitle id={imdbID}>
          {`${Title} - (${Year})`}
        </LimitedTextTitle>
        <Tooltip placement='top' target={imdbID} isOpen={this.state.open} toggle={this.toggle}>
          {Title}
        </Tooltip>
      </CardTitle>
      <CardSubtitle>{`Rated: ${Rated} Country: ${Country}`}</CardSubtitle>
      <CardText>{Plot}</CardText>
      <Button>Read More</Button>
    </CardBody>
  </Col>
);
  }
}

MovieCard.propTypes = {
  movie: PropTypes.object.isRequired // eslint-disable-line
};

export default MovieCard;
</code>```

Any suggestions?

react vesion 16.2.0

reactstrap 5.0.0-alpha.4

答:
I tried a lot of solutions and was still having trouble with Reactstrap Tooltip crashing when the target element is not in the Dom.

I combined a couple other solutions that people posted and this is the only way it worked for me. Conditional rendering FTW.

```<code>const ElementWithTooltip = ({
    dynamicIdentifier, // string, number, w/e
}): ReactElement => {
    // Target element state.
    const [isTargetReady, setIsTargetReady] = useState(false);

    // Target element ref.
    const tooltipRef = useRef(null);

    // Hook to recognize that the target is ready.
    useEffect(() => {
        const targetElement = tooltipRef.current;
        if (targetElement) {
            setIsTargetReady(true);
        }
      }, [tooltipRef.current]);

    // TSX.
    return (
        <>
            <span ref={tooltipRef}>This is the target element</span>
            {isTargetReady && <UncontrolledTooltip autohide={false} target={tooltipRef}>
                Tooltippy text stuff
            </UncontrolledTooltip>}
        </>
    );
</code>```

Title: reactstrap tooltip dynamic id

Body:
I am developing a react application and using reactstrap.

I am using Tooltip Component of reactstrap which requires a target attribute, a value of target element's id. This id is being geneated dynamically and seems reactstrap tooltip doesn't like it.

Component looks like:

MovieCard.jsx

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Col, Card, CardImg, CardBody, CardTitle, CardSubtitle, CardText, Button, Tooltip } from 'reactstrap';
import { LimitedTextTitle } from '../custom-styled/CustomStyledComponents';

class MovieCard extends Component {

  constructor (props) {
    super(props);
    this.state = {
      open: false
    };
    this.toggle = this.toggle.bind(this);
  }

  toggle () {
    this.setState({
      open: !this.state.open
    })
  }

  render () {
    const { imdbID, Title, Year, Rated, Plot, Country, Poster } = this.props.movie;

    return (
  <Col md="4">
    <Card>
      <CardImg
        top
        width="100%"
        src={Poster}
        alt="blah"
      />
    </Card>
    <CardBody>
      <CardTitle>
        <LimitedTextTitle id={imdbID}>
          {`${Title} - (${Year})`}
        </LimitedTextTitle>
        <Tooltip placement='top' target={imdbID} isOpen={this.state.open} toggle={this.toggle}>
          {Title}
        </Tooltip>
      </CardTitle>
      <CardSubtitle>{`Rated: ${Rated} Country: ${Country}`}</CardSubtitle>
      <CardText>{Plot}</CardText>
      <Button>Read More</Button>
    </CardBody>
  </Col>
);
  }
}

MovieCard.propTypes = {
  movie: PropTypes.object.isRequired // eslint-disable-line
};

export default MovieCard;

Any suggestions?

react vesion 16.2.0

reactstrap 5.0.0-alpha.4

Body:
I tried a lot of solutions and was still having trouble with Reactstrap Tooltip crashing when the target element is not in the Dom.

I combined a couple other solutions that people posted and this is the only way it worked for me. Conditional rendering FTW.

const ElementWithTooltip = ({
    dynamicIdentifier, // string, number, w/e
}): ReactElement => {
    // Target element state.
    const [isTargetReady, setIsTargetReady] = useState(false);

    // Target element ref.
    const tooltipRef = useRef(null);

    // Hook to recognize that the target is ready.
    useEffect(() => {
        const targetElement = tooltipRef.current;
        if (targetElement) {
            setIsTargetReady(true);
        }
      }, [tooltipRef.current]);

    // TSX.
    return (
        <>
            <span ref={tooltipRef}>This is the target element</span>
            {isTargetReady && <UncontrolledTooltip autohide={false} target={tooltipRef}>
                Tooltippy text stuff
            </UncontrolledTooltip>}
        </>
    );


问:
How To Parse A List Of Strings And Add Values to a Map<String,Integer> Using Lambdas
In my console project I receive input {String resource} {int quantity} on one line (can receive several pairs example: 3 Motes 5 stones 5 Shards

My goal is to refactor the body of while loop to use as many lambdas as possible.
I'd love to reduce the ungodly amount of if-else statements and use a Predicate, but I'm a newbie and am more looking for pointers what else I could try.

I've checked the javadoc for Collectors, Arrays.stream() and also read through the tutorials in Oracle's JDK 8 lambdas and functional programming, but obviously need more of a practical example.

The goal is to obtain 250 of a resource for one of the legendaries Map key and stop the program.
I parse the values with Scanner, split by one whitespace and implement my logic as follows:

```<code>private final static int REQUIRED_QUANTITY = 250;
private static boolean gameOver = false;
Map<String, String> legendary = new HashMap<>();
        legendary.put("shards", "Shadowmourne");
        legendary.put("fragments", "Valanyr");
        legendary.put("motes", "Dragonwrath");

        Map<String, Integer> resources = new HashMap<>();

        while (true) {
            String[] loot = scanner.nextLine().toLowerCase().split(" ");
            String material = null;
            int quantity = 0;

            for (int i = 0; i < loot.length; i++) {
                if (i % 2 != 0) {
                    material = loot[i];
                } else {
                    quantity = Integer.parseInt(loot[i]);
                }

                if (material != null && quantity != 0) {
                    if (resources.containsKey(material.toLowerCase())) {
                        resources.replace(material, resources.get(material) + quantity);
                    }
                    resources.putIfAbsent(material.toLowerCase(), quantity);

                    material = null;
                    quantity = 0;
                }
            }

            resources.forEach((s, integer) -> {
                if (integer > REQUIRED_QUANTITY) {
                    System.out.println("Legendary obtained: " + legendary.get(s));
                    gameOver = true;
                }
            });
</code>```

答:
I made some changes.

using a for loop for just 2 values.  Just process one line at a time.

using compute to handle updating map

put in placeholder to check for proper resource (it could be spelled wrong upon input.

```<code>private final static int REQUIRED_QUANTITY = 250;
private static boolean gameOver = false;

Map<String, String> legendary = new HashMap<>();
legendary.put("shards", "Shadowmourne");
legendary.put("fragments", "Valanyr");
legendary.put("motes", "Dragonwrath");

Map<String, Integer> resources = new HashMap<>();
Scanner scanner = new Scanner(System.in);
while (!gameOver) {
    String[] loot =
            scanner.nextLine().toLowerCase().split("\\s+");
    for (int i = 0; i < loot.length; i+=2) {
    String material = loot[i+1];
    if (!legendary.containsKey(material)) {
        // do some error processing
    }
        int quantity = Integer.parseInt(loot[i]);
        // you may want to catch exception here.
        resources.compute(material.toLowerCase(),
                (k, v) -> v == null ? quantity : v + quantity);

    }
    resources.forEach((s, integer) -> {
        if (integer > REQUIRED_QUANTITY) {
            System.out.println("Legendary obtained: "
                    + legendary.get(s));
            gameOver = true;
        }
    });
}
</code>```

Body:
In my console project I receive input {String resource} {int quantity} on one line (can receive several pairs example: 3 Motes 5 stones 5 Shards

My goal is to refactor the body of while loop to use as many lambdas as possible.
I'd love to reduce the ungodly amount of if-else statements and use a Predicate, but I'm a newbie and am more looking for pointers what else I could try.

I've checked the javadoc for Collectors, Arrays.stream() and also read through the tutorials in Oracle's JDK 8 lambdas and functional programming, but obviously need more of a practical example.

The goal is to obtain 250 of a resource for one of the legendaries Map key and stop the program.
I parse the values with Scanner, split by one whitespace and implement my logic as follows:

private final static int REQUIRED_QUANTITY = 250;
private static boolean gameOver = false;
Map<String, String> legendary = new HashMap<>();
        legendary.put("shards", "Shadowmourne");
        legendary.put("fragments", "Valanyr");
        legendary.put("motes", "Dragonwrath");

        Map<String, Integer> resources = new HashMap<>();

        while (true) {
            String[] loot = scanner.nextLine().toLowerCase().split(" ");
            String material = null;
            int quantity = 0;

            for (int i = 0; i < loot.length; i++) {
                if (i % 2 != 0) {
                    material = loot[i];
                } else {
                    quantity = Integer.parseInt(loot[i]);
                }

                if (material != null && quantity != 0) {
                    if (resources.containsKey(material.toLowerCase())) {
                        resources.replace(material, resources.get(material) + quantity);
                    }
                    resources.putIfAbsent(material.toLowerCase(), quantity);

                    material = null;
                    quantity = 0;
                }
            }

            resources.forEach((s, integer) -> {
                if (integer > REQUIRED_QUANTITY) {
                    System.out.println("Legendary obtained: " + legendary.get(s));
                    gameOver = true;
                }
            });

Body:
I made some changes.

using a for loop for just 2 values.  Just process one line at a time.

using compute to handle updating map

put in placeholder to check for proper resource (it could be spelled wrong upon input.

private final static int REQUIRED_QUANTITY = 250;
private static boolean gameOver = false;

Map<String, String> legendary = new HashMap<>();
legendary.put("shards", "Shadowmourne");
legendary.put("fragments", "Valanyr");
legendary.put("motes", "Dragonwrath");

Map<String, Integer> resources = new HashMap<>();
Scanner scanner = new Scanner(System.in);
while (!gameOver) {
    String[] loot =
            scanner.nextLine().toLowerCase().split("\\s+");
    for (int i = 0; i < loot.length; i+=2) {
    String material = loot[i+1];
    if (!legendary.containsKey(material)) {
        // do some error processing
    }
        int quantity = Integer.parseInt(loot[i]);
        // you may want to catch exception here.
        resources.compute(material.toLowerCase(),
                (k, v) -> v == null ? quantity : v + quantity);

    }
    resources.forEach((s, integer) -> {
        if (integer > REQUIRED_QUANTITY) {
            System.out.println("Legendary obtained: "
                    + legendary.get(s));
            gameOver = true;
        }
    });
}


问:
df.to_dict make duplicated index (pandas) as primary key in a nested dict
I have this data frame which I'd like to convert to a dict in python, I have many other categories, but showed just two for simplicity

```<code>Category   Name                     Description             Price
Diesel     Land Rover               No Description found    £ x
Electric   Tesla Model X            No Description found    £ x
</code>```

I want the output to be like this

```<code>dict = {"Category": {"Diesel" : {
                                "Name": "Land Rover",
                                "Description":"No Description Found",
                                "Price": "£ x" },

                    "Electric" : {"Name": "Tesla Model X",
                                  "Description":"No Description Found",
                                  "Price": "£ x" }
                    }
        }
</code>```

答:
You can start by creating a dictionary for each record and then group by category to create the final dictionary format desired.</p>
```<code>df['dict'] = df[['Name', 'Description', 'Price']].to_dict("records")

dictionary = dict()
dictionary['Category'] = df.groupby('Category')['dict'].apply(list).to_dict()
</code>```

Body:
I have this data frame which I'd like to convert to a dict in python, I have many other categories, but showed just two for simplicity

Category   Name                     Description             Price
Diesel     Land Rover               No Description found    £ x
Electric   Tesla Model X            No Description found    £ x

I want the output to be like this

dict = {"Category": {"Diesel" : {
                                "Name": "Land Rover",
                                "Description":"No Description Found",
                                "Price": "£ x" },

                    "Electric" : {"Name": "Tesla Model X",
                                  "Description":"No Description Found",
                                  "Price": "£ x" }
                    }
        }

Body:
You can start by creating a dictionary for each record and then group by category to create the final dictionary format desired.

df['dict'] = df[['Name', 'Description', 'Price']].to_dict("records")

dictionary = dict()
dictionary['Category'] = df.groupby('Category')['dict'].apply(list).to_dict()


问:
How to include the local hostname as parameter in a GET URL?
I am working on an IoT project, having multiple clients in kiosk mode, opening a single URL. I want to create session but instead of manually entered username, I would like to use the client hostname automatically inserted in the URL as parameter to authenticate the session.
Any ideas how can this be achieved?</p>

答:
When you configure openbox, you will set the environment variable KIOSK_URL.  This will need to be set on each kiosk to its private login.  For example:

```<code>KIOSK_URL=https://www.example.com/login?user=foo&key=password
</code>```

When Chromium does the get request on https://www.example.com/login it will pass the parameters that you provide.  Change user and key to the parameter names in the login form, and foo and password to your name and correcthorsebatterystaple.

Body:
When you configure openbox, you will set the environment variable KIOSK_URL.  This will need to be set on each kiosk to its private login.  For example:

KIOSK_URL=https://www.example.com/login?user=foo&key=password

When Chromium does the get request on https://www.example.com/login it will pass the parameters that you provide.  Change user and key to the parameter names in the login form, and foo and password to your name and correcthorsebatterystaple.


问:
#line keyword in C
I am trying to understand some code and I've come across a keyword that I've never seen before. I tried to google it, but haven't found anything regarding it as well.

```<code>char *valtext;
#line 1 "Values.l"
#define INITIAL 0
#line 2 "Values.l"
int reserve(char *s);
#line 388 "lex.val.c"
</code>```

I've included the entire block hoping that perhaps someone can help me understand this chunk of code. I can't find any files on my system named "Values.l" and this chunk of code is located in the "lex.val.c" file.

Thanks in advance.

答:
The #line directive is for the use of preprocessors, so that the original line number of the source can be communicated to the C compiler.  It makes it so that error messages from the compiler properly refer to line numbers the user will understand.

For example, line 12 of your mycode.c may go through a preprocessor, and now be line 183 of mycode.tmp.cc.  If the C compiler finds an error on that line, you don't want to be told the error is on line 183 of mycode.tmp.cc.  So the C compiler needs to be given "original coordinates" of each line.  The #line directive does this, telling the compiler the current line number and filename to use in error messages.

Title: #line keyword in C

Body:
I am trying to understand some code and I've come across a keyword that I've never seen before. I tried to google it, but haven't found anything regarding it as well.

char *valtext;
#line 1 "Values.l"
#define INITIAL 0
#line 2 "Values.l"
int reserve(char *s);
#line 388 "lex.val.c"

I've included the entire block hoping that perhaps someone can help me understand this chunk of code. I can't find any files on my system named "Values.l" and this chunk of code is located in the "lex.val.c" file.

Thanks in advance.


问:
How is the itab struct actually having a list of function pointers?
Researching the interface value in go - I found a great (maybe outdated) article by Russ Cox.
According to it:

The itable begins with some metadata about the types involved and then becomes a list of function pointers.

The implementation for this itable should be the one from src/runtime/runtime2.go:

type itab struct {
    inter *interfacetype
    _type *_type
    hash  uint32 // copy of _type.hash. Used for type switches.
    _     [4]byte
    fun   [1]uintptr // variable sized. fun[0]==0 means _type does not implement inter.
}
```

First confusing thing is - how is an array - variable sized?
Second, assuming that we have a function pointer at index 0 for a method that satisfies the interface, where could we store a second/third/... function pointer?

答:
The compiled code and runtime access fun as if the field is declared fun [n]uintpr where n is the number of methods in the interface. The second method is stored at fun[1], the third at fun[2] and so on. The Go Language does not have a variable size array feature like this, but unsafe shenanigans can be used to simulate the feature.

Here's how itab is allocated:

```<code>m = (*itab)(persistentalloc(unsafe.Sizeof(itab{})+uintptr(len(inter.mhdr)-1)*goarch.PtrSize, 0, &memstats.other_sys))
</code>```

The function persistentalloc allocates memory.  The first argument to the function is the size to allocate. The expression inter.mhdr is the number of methods in the interface.

Here's code that creates a slice on the variable size array:

```<code>methods := (*[1 << 16]unsafe.Pointer)(unsafe.Pointer(&m.fun[0]))[:ni:ni]
</code>```

The expression methods[i] refers to the same element as m.fun[i] in a hypothetical world where m.fun is a variable size array with length > i.  Later code uses normal slice syntax with methods to access the variable size array m.fun.

Body:
Researching the interface value in go - I found a great (maybe outdated) article by Russ Cox.
According to it:

The itable begins with some metadata about the types involved and then becomes a list of function pointers.

The implementation for this itable should be the one from src/runtime/runtime2.go:

type itab struct {
    inter *interfacetype
    _type *_type
    hash  uint32 // copy of _type.hash. Used for type switches.
    _     [4]byte
    fun   [1]uintptr // variable sized. fun[0]==0 means _type does not implement inter.
}

First confusing thing is - how is an array - variable sized?
Second, assuming that we have a function pointer at index 0 for a method that satisfies the interface, where could we store a second/third/... function pointer?

Body:
The compiled code and runtime access fun as if the field is declared fun [n]uintpr where n is the number of methods in the interface. The second method is stored at fun[1], the third at fun[2] and so on. The Go Language does not have a variable size array feature like this, but unsafe shenanigans can be used to simulate the feature.

Here's how itab is allocated:

m = (*itab)(persistentalloc(unsafe.Sizeof(itab{})+uintptr(len(inter.mhdr)-1)*goarch.PtrSize, 0, &memstats.other_sys))

The function persistentalloc allocates memory.  The first argument to the function is the size to allocate. The expression inter.mhdr is the number of methods in the interface.

Here's code that creates a slice on the variable size array:

methods := (*[1 << 16]unsafe.Pointer)(unsafe.Pointer(&m.fun[0]))[:ni:ni]

The expression methods[i] refers to the same element as m.fun[i] in a hypothetical world where m.fun is a variable size array with length > i.  Later code uses normal slice syntax with methods to access the variable size array m.fun.


问:
what is the use of annotations @Id and @GeneratedValue(strategy = GenerationType.IDENTITY)? Why the generationtype is identity?
```<code>@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
</code>```

Why we are using this annotations?
i need to know if this autoincrement my table id values.
(GenerationType.IDENTITY) is there any other types whats actually happening when we use this annotation

```<code>public class Author extends Domain
{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "id")
    private Integer id;

    @Basic(optional = false)
    @Column(name = "name")
    private String name;

    @Column(name = "address")
    private String address;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "authorId")
    private List<Book>
    bookList;

    public Author()
    {
        setServiceClassName("wawo.tutorial.service.admin.AuthorService");
    }
}
</code>```

*Is it necessary to extend Domain abstract class?What is the use?

答:
Why are we using this annotation?

First I would like to remind everyone that the annotations, such as @Id, are providing metadata to the persistence layer(I will assume hibernate).This metadata will most likely be stored in the .class file(but not stored in the database) and is used to tell hibernate how to recognize, interpret and manage the entity. So, Why are you using the annotation? To provide your persistence layer with the proper information about how to manage the entity.

Why use the @Id annotation?

The @Id annotation is one of the two mandatory annotations needed when creating an entity with JPA. The other one being @Entity. @Id does two things for us:

1) signifies that this field will be the unique identifier for this class when mapped to a database table

2) the presence of @Id lets the persistence layer know that all other fields within this class are to be mapped to database rows

Why use @GeneratedValue?

By marking the @Id field with @GeneratedValue we are now enabling id generation. Which means that the persistence layer will generate an Id value for us and handle the auto incrementing. Our application can choose 1 of 4 generations strategies:

1) AUTO

2) TABLE

3) SEQUENCE

4) IDENTITY

If not strategy is specified then AUTO is assumed

What is strategy = GenerationType.IDENTITY actually doing?

When we specify the generation strategy as GenerationType.IDENTITY we are telling the persistence provider(hibernate) to let the database handle the auto incrementing of the id. If you were to use postgres as an underling database and specified the strategy as IDENTITY, hibernate would execute this:

```<code>create table users (
       id  bigserial not null,
        primary key (id)
    )

</code>```

Notice that they type of the id is bigserial, what is bigserial? As per the postgres documentation, bigserial is a large autoincrementing integer.

Conclusion

By specifying:

```<code>@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;

</code>```

you have told the underlying persistence layer to use the id field as a unique identifier within the database. Also told the persistence layer to let the database handle the auto incrementing of the id with GenerationType.IDENTITY.

Body:
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)

Why we are using this annotations?
i need to know if this autoincrement my table id values.
(GenerationType.IDENTITY) is there any other types whats actually happening when we use this annotation

public class Author extends Domain
{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "id")
    private Integer id;

    @Basic(optional = false)
    @Column(name = "name")
    private String name;

    @Column(name = "address")
    private String address;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "authorId")
    private List<Book>
    bookList;

    public Author()
    {
        setServiceClassName("wawo.tutorial.service.admin.AuthorService");
    }
}

*Is it necessary to extend Domain abstract class?What is the use?

Body:
Why are we using this annotation?

First I would like to remind everyone that the annotations, such as @Id, are providing metadata to the persistence layer(I will assume hibernate).This metadata will most likely be stored in the .class file(but not stored in the database) and is used to tell hibernate how to recognize, interpret and manage the entity. So, Why are you using the annotation? To provide your persistence layer with the proper information about how to manage the entity.

Why use the @Id annotation?

The @Id annotation is one of the two mandatory annotations needed when creating an entity with JPA. The other one being @Entity. @Id does two things for us:

1) signifies that this field will be the unique identifier for this class when mapped to a database table

2) the presence of @Id lets the persistence layer know that all other fields within this class are to be mapped to database rows

Why use @GeneratedValue?

By marking the @Id field with @GeneratedValue we are now enabling id generation. Which means that the persistence layer will generate an Id value for us and handle the auto incrementing. Our application can choose 1 of 4 generations strategies:

1) AUTO

2) TABLE

3) SEQUENCE

4) IDENTITY

If not strategy is specified then AUTO is assumed

What is strategy = GenerationType.IDENTITY actually doing?

When we specify the generation strategy as GenerationType.IDENTITY we are telling the persistence provider(hibernate) to let the database handle the auto incrementing of the id. If you were to use postgres as an underling database and specified the strategy as IDENTITY, hibernate would execute this:

create table users (
       id  bigserial not null,
        primary key (id)
    )

Notice that they type of the id is bigserial, what is bigserial? As per the postgres documentation, bigserial is a large autoincrementing integer.

Conclusion

By specifying:

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;

you have told the underlying persistence layer to use the id field as a unique identifier within the database. Also told the persistence layer to let the database handle the auto incrementing of the id with GenerationType.IDENTITY.


问:
In Julia using StochasticPrograms.jl package how can I get the @sampler object as a n*m matrix not a vector?
In the julia programming language I use StochasticPrograms.jl package to model a two stage stochastic problem. I use @sampler object to develop scenarios and random values. The random variable follows a normal distribution. The @sampler output should be a 3*3 matrix to match the random variable dimension ( d[1:J,1:T], J=3, T=3) defined in the problem.

I have used a few different techniques to get the output as a 3*3 matrix (one of them is below) but no luck.

```<code>using StochasticPrograms
@sampler SimpleSampler = begin
        N::MvNormal

        SimpleSampler(µ, Σ) = new(MvNormal(µ, Σ))

    @sample Scenario begin

        x = rand(sampler.N)

        return @scenario d = reshape(x,3,3)
    end
end

μ=[4,4,4,4,4,4,4,4,4]

Σ=[
    1 0 0 0 0 0 0 0 0;
    0 1 0 0 0 0 0 0 0;
    0 0 1 0 0 0 0 0 0;
    0 0 0 1 0 0 0 0 0;
    0 0 0 0 1 0 0 0 0;
    0 0 0 0 0 1 0 0 0;
    0 0 0 0 0 0 1 0 0;
    0 0 0 0 0 0 0 1 0;
    0 0 0 0 0 0 0 0 1;
]

s = SimpleSampler(μ,Σ)
s()

</code>```

and the output is:

```<code>d: [3.2222636794881696 1.9732554309220443 3.0941572984285233; 3.421615040079402 3.145688781906985 2.856241404036557; 3.0571013553323985 4.24134467488927 5.800220182172864]
</code>```

答:
As @OscarDowson mentions in the comment, the output is a 3x3 matrix. The semi-colons in the output denote the end of one row and the beginning of the next.

It seems like you are outputting this with something like: print("d: ", d). Instead, try using display(d). As the documentation for print says:

Write ... a canonical (un-decorated) text representation

The
representation used by print includes minimal formatting

the output of a print call is pretty barebones. I haven't looked into the reasons, but my interpretation is that its priority is to be consistent and machine-readable. For human readability, display is better.

Edit: Oh, and please read through the Performance tips in the manual in case you haven't yet. Having everything as global variables like here will incur performance penalties once you start building this into anything more computationally intensive.

Body:
In the julia programming language I use StochasticPrograms.jl package to model a two stage stochastic problem. I use @sampler object to develop scenarios and random values. The random variable follows a normal distribution. The @sampler output should be a 3*3 matrix to match the random variable dimension ( d[1:J,1:T], J=3, T=3) defined in the problem.

I have used a few different techniques to get the output as a 3*3 matrix (one of them is below) but no luck.

using StochasticPrograms
@sampler SimpleSampler = begin
        N::MvNormal

        SimpleSampler(µ, Σ) = new(MvNormal(µ, Σ))

    @sample Scenario begin

        x = rand(sampler.N)

        return @scenario d = reshape(x,3,3)
    end
end

μ=[4,4,4,4,4,4,4,4,4]

Σ=[
    1 0 0 0 0 0 0 0 0;
    0 1 0 0 0 0 0 0 0;
    0 0 1 0 0 0 0 0 0;
    0 0 0 1 0 0 0 0 0;
    0 0 0 0 1 0 0 0 0;
    0 0 0 0 0 1 0 0 0;
    0 0 0 0 0 0 1 0 0;
    0 0 0 0 0 0 0 1 0;
    0 0 0 0 0 0 0 0 1;
]

s = SimpleSampler(μ,Σ)
s()

and the output is:

d: [3.2222636794881696 1.9732554309220443 3.0941572984285233; 3.421615040079402 3.145688781906985 2.856241404036557; 3.0571013553323985 4.24134467488927 5.800220182172864]


问:
How do I identify the lowest required visibility of methods?
As part of a large refactoring project, I need to identify methods that are no longer used, or where the visibility can be reduced.

Consider the following code:

```<code>program Project1;

type
  TMyClass = class(TObject)
  private
    function Method1 : integer;
  public
    function Method2 : integer;
    function Method3 : integer;
    function Method4 : integer;
  end;

var
  vMyObject : TMyClass;

function TMyClass.Method1: integer;
begin
  Result := Method2;
end;

function TMyClass.Method2: integer;
begin
  Result := 2;
end;

function TMyClass.Method3: integer;
begin
  Result := 3;
end;

function TMyClass.Method4: integer;
begin
  Result := 4;
end;

begin
  vMyObject := TMyClass.Create;
  try
    writeln(vMyObject.Method3);
  finally
    vMyObject.Free;
  end;
end.
</code>```

The Delphi compiler gives the warning "[DCC Hint] Project1.dpr(6): H2219 Private symbol 'Method1' declared but never used", which is very helpful. But there are other issues with this code that I would like to be warned about:

Method4 is never used, but I don't get a warning since it's public.

Method2 is declared public, but only used privately.

Are there any tools I can use to identify issues like these?

答: PAL from Peganza and/or CodeHealer might be able to help you.</p>

Body:
As part of a large refactoring project, I need to identify methods that are no longer used, or where the visibility can be reduced.

Consider the following code:

program Project1;

type
  TMyClass = class(TObject)
  private
    function Method1 : integer;
  public
    function Method2 : integer;
    function Method3 : integer;
    function Method4 : integer;
  end;

var
  vMyObject : TMyClass;

function TMyClass.Method1: integer;
begin
  Result := Method2;
end;

function TMyClass.Method2: integer;
begin
  Result := 2;
end;

function TMyClass.Method3: integer;
begin
  Result := 3;
end;

function TMyClass.Method4: integer;
begin
  Result := 4;
end;

begin
  vMyObject := TMyClass.Create;
  try
    writeln(vMyObject.Method3);
  finally
    vMyObject.Free;
  end;
end.

The Delphi compiler gives the warning "[DCC Hint] Project1.dpr(6): H2219 Private symbol 'Method1' declared but never used", which is very helpful. But there are other issues with this code that I would like to be warned about:

Method4 is never used, but I don't get a warning since it's public.

Method2 is declared public, but only used privately.

Are there any tools I can use to identify issues like these?


问:
Auto Join Nodes to Kubeadm Clusters In AWS
I'm having to build a demo Kubernetes cluster in AWS using Kubeadm.

Unfortunately, for several reasons, Kops, and EKS are out of the question in my current environment.

How do I deal with things such as auto-scaling and auto joining worker nodes back to the master if they get terminated for any reason? This is my main concern.

I've done this with Kops in the past and it's relatively straightforward, but I'm not sure how to manage using Kubeadm.

答: If you're using Ansible, you can set up your launch configuration to pull a git repo, and run a playbook to extract the join token from the Master and run on the worker nodes.</p>


问:
do not output specific div if something is null using jquery
I am making database query.

```<code>let link = something from the database;
let output = `
   <div>
      ...
   <div>
   <div>
      ...
   <div>
   <div>
      <iframe src="${link}"></iframe>
   </div>
   <div>
      <div>
         ...
      </div>
   <div>
`;
$('#table').html(output);
</code>```

The link could be empty then I do not want to output the highlighted div. I do not know a "cool" way of doing that.

答:
Consider the following.

$(function() {
  var links = [
    "Url 1",
    "",
    "Url 3",
    "Url 4",
    "Url 5"
  ];

  $.each(links, function(i, link) {
    if (link != "") {
      $("
").html($("", {
        src: link
      })).appendTo("#table");
    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="table">
</div></code>```

You will want to iterate your data and conditionally add the HTML.

See More:

https://api.jquery.com/jquery.each/

Body:
I am making database query.

let link = something from the database;
let output = `

      ...

      ...

         ...

`;
$('#table').html(output);

The link could be empty then I do not want to output the highlighted div. I do not know a "cool" way of doing that.

Body:
Consider the following.

$(function() {
  var links = [
    "Url 1",
    "",
    "Url 3",
    "Url 4",
    "Url 5"
  ];

  $.each(links, function(i, link) {
    if (link != "") {
      $("<div>").html($("<iframe>", {
        src: link
      })).appendTo("#table");
    }
  });
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="table">
</div>

You will want to iterate your data and conditionally add the HTML.

See More:

https://api.jquery.com/jquery.each/


问:
how to find ssl.conf file in apache
I am trying to install self signed ssl on IP address. I have apache in centos7. I have mod_ssl installed. I have been able to create self signed certificate with openssl req. Now I need to add this certificate to virtual hosts. I found two different files in tutorials for this purpose.
etc/apache2/sites-available/default-ssl.conf and second option is etc/httpd/conf.d/ssl.conf.
But I could find apache2 folder in etc but not sites-availabe and no httpd in etc. Where do I find the relevant file to edit virtual hosts?
Thank you.</p>

答: you can just create the folder sites-available if you want inside of the Apache folder. The important thing is to check the Main Apache Config file and make sure that it is loading up the default-ssl.conf file. Usually its done by putting an Include /*. That would load up everything in that folder.</p>

Title: how to find ssl.conf file in apache


问:
Laravel - Model Class not found
When starting to work with models I got the following error

Class Post not found`.

All I did:

- Created a Model with  the command php artisan make:model

- Tried to get all entries from table posts with echo Post::all()

I used the following code:

router.php

```<code>Route::get('/posts', function(){
    $results = Post::all();
    return $results;
});
</code>```

Post.php

```<code><?php
namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model {
    protected $table = 'posts';
}
</code>```

What I tried

- Renaming Class

- Dump-autoload (Laravel 4 Model class not found)

答:
I had the same issue.  It turned out my Post model was in a php file whose name was not Post.php

=> the filename must match the name of your class (Post class in Post.php file)

Title: Laravel - Model Class not found

Body:
When starting to work with models I got the following error

Class Post not found`.

All I did:

- Created a Model with  the command php artisan make:model

- Tried to get all entries from table posts with echo Post::all()

I used the following code:

router.php

Route::get('/posts', function(){
    $results = Post::all();
    return $results;
});

Post.php

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model {
    protected $table = 'posts';
}

What I tried

- Renaming Class

- Dump-autoload (Laravel 4 Model class not found)