text:
Q: Redis find pattern keys that match string I know that Redis has MATCH as a part of SCAN (as detailed here) to find keys that match a glob style pattern (i.e. sub.domain.com could be returned from scan 0 MATCH *.domain.com)
My question is if there is a way to perform the reverse operation. If my keys are glob style patterns (i.e. *.domain.com  is one of the keys) how can I search to see what keys have patterns that match sub.domain.com?
One thought was to use EVAL to write a Lua script to do this, but I would think that would be fairly resource intensive? Is there some other way to approach this?

To make things a little clearer, here are some example keys (seperated by commas) (I'm not going to worry about the values for now as they don't really apply to this question), queries and the responses that I would expect the queries to generate:
Keys:
*img.myserver.com*, *.mywebsite.com*, *www.example.com/images*
Queries -> expected responses (matched keys)
scan 0 REV-MATCH https://img.myserver.com/myimg.jpg -> *img.myserver.com*
scan 0 REV-MATCH http://www.myserver.com/otherimg.jpg -> No matches
scan 0 REV-MATCH http://www.mywebsite.com/blah/blah.jpg -> *.mywebsite.com*
scan 0 REV-MATCH https://www.example.com/images/old/a.jpg -> *www.example.com/images*
REV-MATCH (Reverse Match) is a function that doesn't exist - but I'm hoping that similar functionality can be found some other way. It is possible for there to be multiple matches if two keys had glob patterns that could match the same string in some scenarios (in my use case, however, this wouldn't happen as I would always ensure the glob patterns never overlapped)

A: Unless I'm wrong, I think that you're overthinking it. A GET *.domain.com (i.e. replace "sub" with "*") should do it. If unfound, continue with a GET *.com, and so forth until ending with GET *, which should be the "root" of all things.

Updated answer
Ok, I see. So, no, SCAN isn't the way but I know of at least two other paths you can try. Give me a shout or open a new question if you run into any dead ends ;)
The Path of Sorted Sets and Lexicographical Ranges
Go to https://redis.io/topics/indexes#lexicographical-indexes and read (may take more than one iteration, and I recommend reading the entire thing actually). Then, given your requirements, remember that you can do suffix matching by storing (and searching) the reverse in another Sorted Set.
The RediSearch Path
Take a look at http://redisearch.io, a Redis module that implements a full search engine (autocomplete included(tm)).
Disclaimer: I work at Redis Labs, home of the open source Redis and provider of commercial solutions that leverage on it, including the above mentioned module (open source, AGPL licensed).


text:
Q: Window events with pdf document via Chrome I would have made a minimal sample, but I couldn't get the Chrome PDF viewer to work in jsfiddle, so I wasn't sure how I would show it.
But essentially, I have a resizable div that has handles around it, and it works fine. However, when I added an Adobe PDF object that fills the screen, the resizers no longer work properly. The resizers I have relies on

*

*Each resizer's mousedown triggers adding window mousemove and mouseup event listeners

*That window mousemove event does all the resizing as needed

*Upon window mouseup, the window event listeners are removed

It appears that if I set display:none for the pdf object, the resizers work properly. Upon further testing, the resizers also appears to work as long as the cursor doesn't get beyond the div resizers too fast, which seems to indicate that the window mousemove mouseup events are suppressed somehow when the cursor moves beyond the resizer/div and is within the PDF object interface? So, I am trying to figure out how I can force the window events to trigger even when within Chrome's PDF viewer - how do I do that?
Edits:
1. Also tried making the window smaller than screen. The resizers allowed a size change outside Chrome's window when the cursor drag moves beyond the Chrome window, and it only doesn't work when the cursor is moving around the PDF object displayed by Chrome. That points towards the underlying code appearing to work properly, and that the issue is with how window events are handled when the cursor is on the Chrome pdf object.
2. I tried too with creating a dummy wrapper that spans the entire screen. Despite it being the bottom most layer with event bubbling (dummy div holds both the embedded object and the resizable div), event handling still doesn't get to it, making me think that Chrome somehow has some stop event propagation code within its viewer associated with embed. Wondering if there's a way to suppress the do not propagate there...

A: I am not aware of any methods to bypass Chrome's own viewer's event propagation controls, but PDF.js comes to rescue!
https://mozilla.github.io/pdf.js/
PDF.js comes with a viewer that will be able to take URL files as long as it's not X-domain. As long as you have administrative powers for the domain where you host the PDF files, you can put PDF.js under that same domain, and embed the viewer via iframe with the appropriate URL and query string via ?file=%FILENAME% and display the PDF file as needed. Events will then propagate through to something like a dummy div where window events will still work properly.

A: I was having similar problem but with 'keyup', 'keydown' events. I found out that by default the PDF file page has document.hasFocus() === false which means that there are no target nodes that can accept keyboard events. By different trial and errors I found that document.activeElement represents the  tag which renders the PDF inside its boundaries. If we execute document.activeElement.focus() then the keyboard events start to work. However, if I click over the PDF file then the events stop to work.
You can experiment with this snippet by pasting it into console on the PDF example file
window.addEventListener('keydown', (event) => {
  console.log('keydown', event)
})

setInterval(() => {
  console.log('focusing activeElement', document.activeElement);
  document.activeElement.focus()
}, 2000);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Way to access const from another component in react This is my first time to develop a react application.
I am encountering difficulties in retrieving const data from another component.
Here is the const I want to access to the other component.
TableComponent.js

export default function({ infinite }) {
const [checkedMap, setCheckedMap] = useState(new Map());

const viewDetails = () => {
    return (
      "url here" +
      Array.from(checkedMap.keys()).join() +
      "/details"
    );
  };
}

//other codes

Is there a way how to access viewDetails to a different component?
Thank you.

A: If you export the const:
export const viewDetails = () => {
    return (
      "url here" +
      Array.from(checkedMap.keys()).join() +
      "/details"
    );
  };
}

This must be in the module scope (on the same level as the default export):
export const viewDetails = () => {}
export default function({ infinite }) {}

You can then import from the other component:
import { viewDetails } from './TableComponent';

If you want to import both the default export and the named export:
import TableComponent, { viewDetails } from './TableComponent';

Finally, you can also access the named import from the default import:
import TableComponent from './TableComponent';
TableComponent.viewDetails();

A: you have to return your const viewDetails...either you need to self invoking function or return the function...e.g.
export default function({ infinite }) {
const viewDetails = () => {
    return (
      "url here" +
      Array.from(checkedMap.keys()).join() +
      "/details"
    );
  };
return viewDetails;
}

A: //TableComponent.js

export const viewDetails = () => {
  return (
    "url here" +
    Array.from(checkedMap.keys()).join() +
    "/details"
  );
};

And in another file you can access this const as below
import { viewDetails } from './TableComponent';

A: const viewDetails = () => {
  return (
    "url here" +
    Array.from(checkedMap.keys()).join() +
    "/details"
  );
};

export default viewDetails;


text:
Q: Where is a docs for Jupyter front-end extensions JavaScript API? I've read the docs about writing the Jupyter front-end extensions, and learn the examples, and now can build the simple extension by myself.
But - where is a complete docs for Jupyter extensions JavaScript API? How to find the JavaScript API for notebook properties and methods?

A: For newcomers it might be confusing that there are several projects with similar names for historical reasons:
a) Jupyter
https://github.com/jupyter
b) JupyterLab
https://github.com/jupyterlab/
The webpage https://jupyter.org/ references the newer b). However, the sub projects of a) do not include deprecation warnings.
=> If you find some documentation via search engine, you have to be careful if its related to a) or b).
Current documentation for JupyterLab extensions can be found here:

*

*General info:
https://jupyterlab.readthedocs.io/en/3.2.x/user/extensions.html

*Javascript API doc:
https://jupyterlab.readthedocs.io/en/stable/api/modules.html

*Examples:
https://github.com/jupyterlab/extension-examples

*Discussion forum:
https://discourse.jupyter.org/c/jupyterlab/extensions/
Related:
https://www.quora.com/What-is-the-difference-between-JupyterLab-and-Jupyter-Notebook-Is-there-a-use-case-for-one-over-the-other?share=1
https://github.com/jupyterlab/jupyterlab-plugin-playground

A: This answer is outdated. Also see answer below.
This might not be the answer you hoped for. However, it might help some readers being new to JavaScript development.
I also was looking for documentation on the Jupyter client API and could not find official docs.
The JavaScript source code can be found on the GitHub repository, for example:

*

*https://github.com/jupyter/notebook/blob/859ae0ac60456c0e38b44f06852b8a24f8a1cfb0/notebook/static/notebook/js/notebook.js

*https://github.com/jupyter/notebook/blob/4.2.2/notebook/static/services/kernels/kernel.js
What also helped was to
A. Use Google Chrome development tools, set a break point in the extension and type
Jupyter

in the console. Then you get a browsable tree structure that can be used to inspect the Jupyter object. That tree structure does not seem to contain methods.
B. Log all the properties of an object, including the methods. If you want to know about the methods of the notebook use for example
for(var property in Jupyter.notebook){ console.log(property)}

C. When typing in the console there is code completion. For example you might want to type
Jupyter.notebook.

and see the suggestions on how to complete the command:

Also see

*

*How to inspect Javascript Objects

*How to display all methods of an object?

*https://www.codeproject.com/Articles/24549/How-to-Inspect-a-JavaScript-Object

*Chrome Developer Tools console - inspect JavaScript object
Browsable tree structure in dev tools console:

How to list properties including methods:

...

A: Apparently, there are is no front-end API documentation, as there is an open GitHub issue that even references your SO question. Maybe a few +1s on the issue might change this, although I suspect that the answer (if any) will point to JupyterLab, which has a defined front-end API but has no common technical base with Jupyter Notebook front-end extensions.


text:
Q: How to start with SuperUser? What is the connection between SU and other Q&A sites from the group? If  got 1 badge will I have it also on 3 other Q&A sites?

A:
If got 1 badge will I have it also on
  3 other Q&A sites?

nope, you will have to earn your merits separately on each site :)
you will, however, receive a little bonus (100 reputation points IIRC) if you associate your account with any of the other web sites, so you can vote and leave comments right away.


text:
Q: C++ Template Classes, Inheritance and Writing Generic Code for Graph Drawing Background Info
I am writing a graph-drawing program. I have encountered a problem with templates and inheritance, and I do not know how to proceed. I do not know how I should design my code to enable me to do what I am trying to do. (Explanation below.)
Target
I have a template class, which represents "data". It looks something like the following:
template<typename T>
class GraphData
{
    std::vector<T> data_x;
    std::vector<T> data_y; // x and y should be held in separate vectors
}

This class is part of an inheritance hierarchy involving several classes.
The hierarchy looks something like this... (Sorry this is from my notes, awful diagram.)
Explanation

*

*There is a base class. No real reason to have it right now, but I anticipate using it later.

*Base_Legend adds functionality for legend drawing. New members added include a std::string, and Get/Set functions.

*Base_Drawable adds a pure abstract = 0 member. void Draw(...). This is to force overloading in all inherited objects which are drawable.

*GraphData_Generic adds functionality for adding/removing data points to a set of vectors. These are pure abstract methods, and must be overridden by any data classes which inherit.

*GraphData and HistogramData are 2 data types which have implementations of the functions from GraphData_Generic. (No implementation of Draw().)

*GraphData_GenericDrawable doesn't do anything. It is to be used as a base class pointer, so that a vector of these objects can be used as data (add/remove data points) and can be draw (using void Draw()). This class also can be used to call the Get()/Set() methods for the std::string to be used in the legend.

*Finally, at the bottom are GraphData_Drawable and HistogramData_Drawable which overload the void Draw() function. This code specifies exactly how the data should be drawn, depending on whether we have a Histogram or general set of data points.

Problem
Currently, I am using template types. The type of data for the datapoints / histogram bin values is specified by using a template.
For example, one can have a HistogramData<double, HistogramData_Drawable<double>, HistogramData_Drawable<int>, etc... Similarly, one can have GraphData<double>, GraphData<float>, GraphData_Drawable`, etc...
So hopefully it should be fairly obvious what's going on here without me uploading my ~ 10000 lines of code...
Right, so, in addition I have some class Graph, which contains a std::vector<GraphData_Generic_Drawable*>, hence the use of the base class pointer, as suggested above.
BUT! One has to decide what type of data should be used as the underlying type. I MUST choose either std::vector<GraphData_Generic_Drawable<double>*> or std::vector<GraphData_Generic_Drawable<float>*>.
This isn't useful, for obvious reasons! (I could choose double and force the user to convert all values manually, but that's just an easy way out which creates more work later on.)
A (very) ugly solution would be to have a std::vector<> for each possible type... int long unsigned long long double float unsigned char... etc...
Obviously this is going to be hideous and essentially repeat loads of code..
So, I intend to implement an AddData method which adds data to that vector, and I also currently have the following method:
// In class Graph

void DrawAll()
{
    for(std::vector<GraphData_Drawable*>::iterator it = m_data.begin(); it != m_data.end(); ++ it)
         (*iterator)->Draw(arguments);
} // Draw function takes arguments including a canvas to draw to, but this isn't directly relevant to the question

Which iterates over the vector and calls Draw for each set of data in there.
How to fix it?
My current thoughts are something along the lines of; I need to implement some sort of interface for an underlying data class, which retrieves values independent of the underlying type. But this is only a very vague initial idea and I'm not really sure how I would go about implementing this, hence the question... I'm not sure this is even what I should be doing...
If this isn't clear ask me a question and I'll update this with more details.


text:
Q: to duplicate vs to reproduce I am facing this

Try to duplicate the problem yourself.

But normally we use reproduce in place of duplicate.
Here http://www.thesaurus.com/browse/duplicate there is no synonym like reproduce.
So my question  isTry to reproduce the problem yourself. a correct sentence?
And why do  reproduce is not marked as a synonym for duplicate?

A: Duplicate means to take an existing X and make a copy of it.
For example, you duplicate a piece of paper by putting it through a copier.
Reproduce can be used to mean the above, but it can also mean make a new copy of X by building X from scratch.
So by saying reproduce a problem, we mean try to recreate it, i.e. start from where you do not experience the problem and perform the steps that create it again.


text:
Q: Gradle for Android: Why doesn't javaexec pick up my classpath? I have an Android project (on Windows) where I am trying to run cucumber-jvm as a non-instrumented "unit test". I.e. execute Cucumber features when I run gradlew test.
Here are the relevant bits of my app's build.gradle:
android {
    ...
    testOptions {
        unitTests.all {
            javaexec {
                main = "cucumber.api.cli.Main"
                classpath = getClasspath()
                args = ['--plugin', 'pretty', '--glue', 'gradle.cucumber', 'src/test/java/cucumber/assets']
            }
        }
    }
}
dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:28.0.0-rc02'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    testImplementation 'io.cucumber:cucumber-java:3.0.2'
    testImplementation 'io.cucumber:cucumber-junit:3.0.2'
}

When I run gradlew test --info at the command-line I get the following error:
Starting process 'command 'C:\Program Files\Java\jdk1.8.0_162\bin\java.exe''. Working directory: C:\dev\urig\android-cucumber\app Command: C:\Program Files\Java\jdk1.8.0_162\bin\java.exe -Dfile.encoding=windows-1252 -Duser.country=US -Duser.language=en -Duser.variant cucumber.api.cli.Main --plugin pretty --glue gradle.cucumber src/test/java/cucumber/assets
Successfully started process 'command 'C:\Program Files\Java\jdk1.8.0_162\bin\java.exe''
Error: Could not find or load main class cucumber.api.cli.Main

It looks to me like the command contains no classpath and my question is - Why?
PS - I've verified that at the time of the call to javaexec the call to getClasspath() indeed contains all the dependencies with this little bit of Groovy: println getClasspath().any { println it }
PPS - I know the intended use of cucumber-jvm is for instrumented tests using cucumber-android. I have a specific use case for running Cucumber  as a "local unit test" (Android terms, not mine) so the above doesn't quite help me.

A: I believe I've found a solution for my issue. Here's the code that works for me:
testOptions {
    unitTests.all {
        def classpath2 = getClasspath()
        javaexec {
            main = "cucumber.api.cli.Main"
            classpath = classpath2
            args = ['--plugin', 'pretty', '--glue', 'gradle.cucumber', 'src/test/java/cucumber/assets']
        }
    }
}

It seems to me that my original call to getClassPath() inside the javaexec closure was returning an empty file collection. At the same time, in the closure for unitTests.all, getClassPath() contains the correct classpath.
By passing the classpath from the external closure into the internal closure via a variable, cucumber.api.cli.Main now runs successfully and my Cucumber features run as part of the Gradle test task.


text:
Q: Is WebRTC's desktop sharing without calling chooseDesktopMedia possible? I am developing a chrome extension that I can use for desktop sharing using WebRTC. I need to use this extension in a sort of automation mode i.e. without user interaction. This extension is to be used as a child process of the main application and for that any permission and/or media selection dialogs shown by 'chooseDesktopMedia' has to be avoided. As far as I have read about desktop sharing using WebRTC, I have reached to a conclusion that 'chooseDesktopMedia' is must to call api for desktop sharing thus there is no way that the selection dialog can be by passed. But one thing confused me. While reading another post at Stackoverflow i.e. Desktop capture chrome plugin I found a claim that the person managed to do the above task without showing desktop/screen selection dialog. It confused me as no proper solution was provided with the claim in this thread.
So I want to ask one simple question now. Is WebRTC's desktop sharing without calling chooseDesktopMedia possible?

A: During my research I found the below given thread:
https://groups.google.com/forum/#!msg/discuss-webrtc/j6jmyBFt9QI/6cjiksWiYaEJ
After reading this thread, I thought of answering "NO" to my own question. In the thread, it has been clearly mentioned that 'chooseDesktopMedia' is the new API designed as an extension API and has to be used for screen sharing as a recommended practice.
The conclusion till date is that you have to call 'chooseDesktopMedia' from your chrome extension in order to select a media source before starting screen sharing.


text:
Q: Proverb, quote or phrase which convey that the approach, ideas that are meant to improve the system or process are the onces which fail them I am looking for a proverb, quote or phrase describing the  processes (or structures or ideas) which are supposed to bring in efficiency, enhance the gaps and increases in-efficiencies, but instead prove to be the reason for the decline of a system.
Explanation with example

Big external agencies were hired in order to define the efficient way to improve the system. However, these agencies do not understand the system and do all sorts of
trial and error methods to innovate the process for years, yet not only
do they waste company resources but are paid a ton of money so as to fix what can be done internally.

A: The road to hell is paved with good intentions? Is 'devil in diguise' too harsh? Neither of those are a great fit. Of course the Germans have a single word for it, but this is the 'English' stack exchange. Here it is in German, if that helps: Verschlimmbesserung.
That which protects, sometimes infects.

A: "The cure is worse than the disease" might be what you're looking for.


text:
Q: Is it possible to get the host in Application _Start? I have a website with multiple host names bound to it. Is it possible to find out in Application_Start() which host is being used?
I understand that I don't have a request at this point so I'm thinking probably not, however I know that each host through which the application is accessed will run under a new app pool. So just wondering if there's anything I can query in IIS that might tell me what hostname is being used with the current app pool?

A: Well, IIS isn't the domain authority, so it will only work to read IIS settings if you manually keep your local settings and DNS settings in sync. But there is a way to read the IIS bindings. So, if you use host header names in your IIS configuration you can effectively read the domain name.
// Get the current Site Name
var siteName = HostingEnvironment.SiteName;

// Get the sites section from the AppPool.config
var sitesSection = WebConfigurationManager.GetSection(null, null, "system.applicationHost/sites");

var site = sitesSection.GetCollection().Where(x => string.Equals((string)x["name"], siteName, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();

if (site != null)
{
    foreach (var iisBinding in site.GetCollection("bindings"))
    {
        var protocol = iisBinding["protocol"] as string;
        var bindingInfo = iisBinding["bindingInformation"] as string;

        string[] parts = bindingInfo.Split(':');
        if (parts.Length == 3)
        {
            //string ip = parts[0]; // May be "*" or the actual IP
            //string port = parts[1]; // Always a port number (even if default port)
            string hostHeader = parts[2]; // May be a host header or "". This will only be the domain name if you keep it in sync with the DNS.

            // Use the hostHeader as the domain name
        }
    }
}

For this to work, you need to set a reference to Microsoft.Web.Administration.dll, which is available via NuGet.
Reference: http://blogs.msdn.com/b/carlosag/archive/2011/01/21/get-iis-bindings-at-runtime-without-being-an-administrator.aspx

A:
Is it possible to find out in Application_Start() which host is being used?

AFAIK no, it is not.
Based on your comments, I would say the persistence mechanism you are after is one of the server-side caching options (System.Runtime.Caching or System.Web.Caching).
System.Runtime.Caching is the newer of the 2 technologies and provides the an abstract ObjectCache type that could potentially be extended to be file-based. Alternatively, there is a built-in MemoryCache type.
Unlike using a static method, caches will persist state for all users (and all domains) based on a timeout (either fixed or rolling), and can potentially have cache dependencies that will cause the cache to be immediately invalidated. The general idea is to reload the data from a store (file or database) after the cache expires. The cache protects the store from being hit by every request - the store is only hit after the timeout is reached or the cache is otherwise invalidated.
You can populate the cache the first time it is accessed (presumably after the request has already been populated, not in the Application_Start event), and use the domain name as part of (or all of) the cache key that is used to look up the data.
public DataType GetData(string domainName)
{
    // Use the domain name as the key (or part of the key)
    var key = domainName;

    // Retrieve the data from the cache (System.Web.Caching shown)
    DataType data = HttpContext.Current.Cache[key];
    if (data == null)
    {
        // If the cached item is missing, retrieve it from the source
        data = GetDataFromDataSource();

        // Populate the cache, so the next request will use cached data

        // Note that the 3rd parameter can be used to specify a
        // dependency on a file or database table so if it is updated,
        // the cache is invalidated
        HttpContext.Current.Cache.Insert(
            key,
            data,
            null,
            System.Web.Caching.Cache.NoAbsoluteExpiration,
            TimeSpan.FromMinutes(10),
            System.Web.Caching.CacheItemPriority.NotRemovable);
    }

    return data;
}

// Usage
var data = GetData(HttpContext.Current.Request.Url.DnsSafeHost);

If it is important, you can use a locking strategy similar to Micro Caching in ASP.NET (or just use that solution wholesale) so the data source does not receive more than one request when the cache expires.
In addition, you can specify that items are "Not Removable", which will make them survive when an application pool is restarted.
More info: http://bartwullems.blogspot.com/2011/02/caching-in-net-4.html


text:
Q: Put CSS and JavaScript in files or main HTML? Although it is always recommended to put JavaScript and CSS code into appropriate files (as .js and .css), most of major websites (like Amazon, facebook, etc.) put a significant part of their JavaScript and CSS code directly within the main HTML page.
Where is the best choice?

A: http://developer.yahoo.com/performance/rules.html#external
Yahoo (even though they have many inline styles and scripts), recommends making them external. I believe google page speed used to (or still does?) do the same as well.
It's really a logical thing to have them separate. There are so many benefits to keeping CSS and JS separate to the HTML. Things like logical code management, caching of those pages, lower page size (would you rather a ~200ms request for a 400kb cached resource, or a 4000ms delay from having to download that data on every page?), SEO options (less crap for google to look through when scripts/styles are external), easier to minify external scripts (online tools etc), can load them synchronously from different servers....
That should be your primary objective in any website. All styles that make up your whole website should be in the one file (or files for each page, then merged and minified when updated), the same for javascript.
In the real world (not doing a project for yourself, doing one for a client or stakeholder that wants results), the only time where it doesn't make sense to load in another javascript resource or another stylesheet (and thus use inline styles/javascript) is if there's some kind of dynamic information that is on a kind of per-user, per-session or per-time-period that can't be accomplished as simply any other way. Example: when my website has a promotion, we dump a script tag with a small JSON object of information. Because we don't minify and merge multiple files, it makes more sense to just include it in the page. Sure there are other ways to do this, but it costs $20 to do that, whereas it could cost > $100 to do it another way.
Perhaps Amazon/Facebook/Google etc use so much inline code is so their servers aren't taxed so much. I'm not too sure on the benchmarking between requesting a 1MB file in one hit or requesting 10 100KB files (presuming 1MB/10 = 100KB for examples' sake), but what would be faster? Potentially the 1MB file, BUT smaller requests can be loaded synchronously, meaning each one of those 10 requests could come from a separate server/domain potentially, thus reducing overall load time.
Further, google homepages for example seem to dump a JSON array of information for the widgets, presumably because it compiles all that information from various sources, minifies it, caches it, then puts in on the page, then the javascript functions build the layout (client side processing power rather than server-side).

A: Place your .js in multiple files, then package, minify and gzip that into one file.
Keep your HTML into multiple seperate files.
Place your .css in multiple files, then package, minify and gzip that into one file.
Then you simply send one css file and one js file to the client to be cached.
You do not inline them with your HTML.
If you inline them then any change to the css or html or js forces to user to download all three again.
The main reason major websites have js & cs in their files, is because major websites code rot. Major companies don't uphold standards and best practices, they just hack it until it works then say "why waste money on our website, it works doesn't it?".
Don't look at examples of live websites, because 99% of all examples on the internet show bad practices.
Also for the love of god, Separation of concerns please. You should never ever use inline javascript or inline css in html pages.

A: An interesting investigation might be whether they include various .css files regardless of the style blocks you're also seeing. Perhaps it's overhead or perhaps it's convenience.
I've found that while working with different styles of interface developer (and content deployers) that convenience/authority often wins in the face of deadlines and "getting the job done". In a project of a large scale there could be factors involved like "No, you ain't touching our stylesheets", or perhaps if there isn't a stylesheet using an http request already then convenience has won a battle against good practice.

A: If your css and javascript code is for a global usage, then it is best to put them into appropriate files.
Otherwise, if the code is used just by a certain page, like the home page, put them directly  into html is acceptable, and is good for maintenance.

A: Our team keeps it all seperate. All resources like this goes into a folder called _Content.
CSS goes into _Content/css/xxx.js
JS goes into _Content/js/lib/xxx.js (For all the library packages)
Custom page events and functions get called from the page, but are put into a main JS file in _Content/js/Main.js
Images will go into the same place under _Content/images/xxx.x
This is just how we lay it out as it keeps the HTML markup as it should be, for markup.

A: I think putting css and js into the main html makes the page loads fast.


text:
Q: Are the generated AWS API Gateway URL's safe to hard-code into applications? Are the generated API Gateway URL's safe to hard-code into applications?
I looked into creating a custom domain, and it seems like a decent amount of work in order to get a custom domain running through API Gateway. I really didn't want to have to dive into certificates, SSL and all that in order to get a consistent endpoint.
If I was to say, code a distributed application to point to the URL that is generated when I deploy the API, could I safely add end points and deploy other versions of the API without breaking the apps that are pointed to that URL?
Thanks.

A: In terms of security, they are safe to hard-code as long as you require authorization. However API Gateway is deployed in different stages that you specify. You can create multiple stages like dev, test, prod. You can redeploy these stages with new changes. If you were to make a prod2 stage then the url would change. The base url format is: https://xxxxxxx.execute-api.[region].amazonaws.com/[stage].

A: Yes, the API id will remain then same once it has been given.
As long as you do not delete the API you can rely on the base uri to remain the same.


text:
Q: Is it possible to create a workspace with an Xcode Project Template? Is it possible to create a workspace using a TemplateInfo.plist option? I haven't found any documentation1, so I suspect that it's not possible.
However, if it is possible, how are multiple projects added to that workspace please?

1. Project templates aren't officially documented anywhere. The "documentation" I refer to is community based.


text:
Q: GET request with thousands of parameters I am building some JSON API endpoints which could take potentially thousands of query string parameters.  Something which concerns me is the artificial limits set per browser, highlighted in this answer:
https://stackoverflow.com/a/812962/1001408
I know I could convert my GET endpoints to POST endpoints, but this is breaking the JSON API specification as far as I can tell.  Has anyone else had to work around this restriction?


text:
Q: "Related Field got invalid lookup: contains" when attempting to search a ManyToMany field in Django I'm using Django 3.2 and Python 3.9.  I have this model with a ManyToMany field
class Account(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    active = models.BooleanField(default=True)
    ...
    crypto_currencies = models.ManyToManyField(CryptoCurrency)

Then I have created this query to find an account if it contains an item from teh many-to-man field
class AccountManager(models.Manager):
    def get_active(self, crypto_currency=None):
        q = Q()
        q &= Q(active=True)
        if crypto_currency != None:
            q &= Q(crypto_currencies__contains=crypto_currency)
        return Account.objects.filter(q)

but this doesn't seem to be working.  I get this error
 line 1184, in build_lookup
    raise FieldError('Related Field got invalid lookup: {}'.format(lookup_name))
django.core.exceptions.FieldError: Related Field got invalid lookup: contains

What's the right way to construct a Django query to search a ManyToMany field?

A: If I understand your problem so this is:-
class Account(models.Model):
     crypto_currencies = models.ManyToManyField(CryptoCurrency)

Solution :-
class Account(models.Model):
         crypto_currencies = models.ManyToManyField('CryptoCurrency',related_name='cryptoCurrency')

A: If crypto_currency is a CryptoCurrency instance you do not need to include the lookup
    if crypto_currency is not None:
        q &= Q(crypto_currencies=crypto_currency)


text:
Q: How do I choose the number of digits in a variable in my scripts? Essentially, I am running a script that grabs a bunch of numbers from other files and puts them together in a useful way.
It currently works well, but it is printing every single digit from the numbers it is grabbing (grepping? is that a word?) and I would like to round it much earlier.
an example of the main idea is:
var1=$(grep.....)

echo $var1 >> output.dat

but this gives me something like 1.235215233462345345362 and I want many less digits.
Bonus question:
Some of the numbers returned are in scientific notation. Is there any way to change that as well?
ssh putty
Distributor ID: RedHatEnterpriseServer Description: Red Hat Enterprise Linux Server release 6.5 (Santiago) Release: 6.5 Codename: Santiago

A: Use printf instead of echo :
$ echo "$a"
1.235215233462345345362

$ LC_ALL=C printf '%.1f\n' "$a"
1.2
$ LC_ALL=C printf '%.3f\n' "$a"
1.235

(LC_ALL=C is to make sure the decimal mark is always . (on input and output) regardless of the locale of the user (where it may be , instead)).


text:
Q: How do I filter a string object based on the partial string matches in JavaScript? I have a string object with values:
dictionary={
 1: ["a1+b+c"],
 2: ["a1+c+v"],
 3: ["a1+z+e"],
 4: ["a2+p+a"],
 5: ["a2+z+v"],
 6: ["a3+q+v"],
 ...};

I have a page with checkboxes for each partial string value in an object, e.g. checkboxes "a","b","c",... etc. On the page, the checkboxes are located in groups a1, a2, a3, etc.

              a1
              a2
              a3
              a4
              a5

              <input type="checkbox" name="selected" value="a" class="a1" />a
              <input type="checkbox" name="selected" value="a" class="a2" />a
              <input type="checkbox" name="selected" value="a" class="a3" />a
              <input type="checkbox" name="selected" value="a" class="a4" />a
             <input type="checkbox" name="selected" value="a" class="a5" />a

              <input type="checkbox" name="selected" value="b" class="a1" />b
              <input type="checkbox" name="selected" value="b" class="a2" />b
              <input type="checkbox" name="selected" value="b" class="a3" />b
              <input type="checkbox" name="selected" value="b" class="a4" />b
             <input type="checkbox" name="selected" value="b" class="a5" />b

      ...

I need to filter the dictionary by the partial values based on the values of the selected checkboxes, for example, when selecting "c" in group a1, it would return:
 1: a1+b+c
 2: a1+c+v

When selecting "z" from group a2, it would return:
 5: "a2+z+v"

The code I have (a function for each group) is:
$(function(){
$(".a1").on("click", function(){
  var arr = $(".a1:checked").map(function(){
      return $(this).val();
    }).get();
  $('#displayString').html(arr);
})
})

This code only shows the values selected. What is a way to create a partial lookup and list all matches one under the other?

A: Try something like this. Does this help you?
So essentially, we are searching the dictionary elements based on the values of the checkboxes using the join, filter and map methods to find valid matches.
We can also do the same thing using reduce, but it would be harder to explain, I thought.
First, we split the strings using the split method. So a1+b+v becomes ['a1','b','v']. This is a necessary step because if we just search directly within the string without splitting, a1 a will match the string. Because both of those are present in the string. Instead we split them up and do an exact match. So only a1 and b will match the said string.
Then, we use the indices of those matches and get the original strings in the last step. Hope it helped you.

var dictionary=[
  "a1+b+c",
  "a1+c+v",
  "a1+z+e",
  "a2+p+a",
  "a2+z+v",
  "a3+q+v",
 ];

var splitDictionary = dictionary.map(item => item.split("+"))

$("#my-table [type='checkbox']").change(function(){
  if(this.checked){
     const value = this.value;
     const className = $(this).attr('class');
     const filteredDictionary = splitDictionary.map((item,index) => item.includes(value) && item.includes(className) ? index : null);
     const values = filteredDictionary.filter(item => item !== null).map(index => dictionary[index]);
    console.log(values);
  }
})

              a1
              a2
              a3
              a4
              a5

              <input type="checkbox" name="selected" value="a" class="a1" />a
              <input type="checkbox" name="selected" value="a" class="a2" />a
              <input type="checkbox" name="selected" value="a" class="a3" />a
              <input type="checkbox" name="selected" value="a" class="a4" />a
             <input type="checkbox" name="selected" value="a" class="a5" />a

              <input type="checkbox" name="selected" value="b" class="a1" />b
              <input type="checkbox" name="selected" value="b" class="a2" />b
              <input type="checkbox" name="selected" value="b" class="a3" />b
              <input type="checkbox" name="selected" value="b" class="a4" />b
             <input type="checkbox" name="selected" value="b" class="a5" />b

              <input type="checkbox" name="selected" value="c" class="a1" />c
              <input type="checkbox" name="selected" value="c" class="a2" />c
              <input type="checkbox" name="selected" value="c" class="a3" />c
              <input type="checkbox" name="selected" value="c" class="a4" />c
             <input type="checkbox" name="selected" value="c" class="a5" />c


text:
Q: How to check whether day satisfies the recurrence condition using google sheet formula I have a Google sheet where it has startdate, frequency, count. I need to check whether the todays date is satisfying the recurrence and display TRUE if today() is satisfied and false if not satisfied.
This will help me determine each time, the sheet is opened I can find out from TODAY() date is satisifed or not?
https://docs.google.com/spreadsheets/d/142od5eUib5nHmdi4mnENuPbh-Yn485NzUSt90p84QE0/edit?usp=sharing

A: Like @Scott Craner said, just compare the result of the formula from the previous question with TODAY():
={
  "Today is the day?";
  ARRAYFORMULA(
    IF(
      A2:A = "",
        ,
        IFS(
          A2:A >= TODAY(),
            A2:A,
          B2:B = "Daily",
             TODAY() + MOD(TODAY() - A2:A, C2:C),
          B2:B = "Weekly",
            TODAY() + MOD(TODAY() - A2:A, 7 * C2:C),
          B2:B = "Monthly",
            EDATE(A2:A, ROUNDUP((12 * (YEAR(TODAY()) - YEAR(A2:A)) + (MONTH(TODAY()) - MONTH(A2:A)) - IF(DAY(TODAY()) < DAY(A2:A), 1, 0)) / C2:C, 0) * C2:C),
          True,
            ""
        ) = TODAY()
    )
  )
}


text:
Q: Print String Without Padded 0 At The End I am trying to print the string "Hello" in binary.
I get it to work, however, I would like it to print without the padded at the end
so
  01001000 01100101 01101100 01101100 01101111

instead of
  01001000 01100101 01101100 01101100 01101111 00000000

Here is my code:
char t[] = "Hello";

for (int j = 0; j < sizeof(t); j++)
{
    unsigned char c = t[j];

    for (int i = 7; i >= 0; i--) {
        printf("%d", (c >> i) & 1 ? 1 : 0);
    }

    printf(" ");

}

A: You can modify your loop condition as:
for (int j = 0; t[j] != '\0'; j++)
/*              ^^^^^^^^^^^^     */

Currently you loop for all characters in t[] that even include the trailing nul character. With modified condition you exit the loop on seeing the nul character responsible for trailing zeros.
+---+---+---+---+---+---+
| H | e | l | l | o |\0 |
+---+---+---+---+---+---+
  T   T   T   T   T   F   t[i] != '\0'

sizeof(t) = 6
strlen(t) = 5

A: Or just:
 for (int j = 0; j < (sizeof(t)-1); j++)

to avoid printing the trailing character nul.

A: Logically, you should just do:
for (int j = 0; j < sizeof(t) - 1; j++)

When you do sizeof(t) the null character at the end of the string is also counted and therefore printed.
Another fix would be:
for (int j = 0; t[j] != '\0'; j++)

A: This j < sizeof(t); rotates loop number of character plus one more(nul character) times). Instead of this rotate loop until \0 character not occur. For e.g
for (int j = 0; t[j]; j++) { }

Sample working code
char t[] = "Hello";
for (int j = 0; t[j] != '\0'; j++) /* using t[j]!='\0'  is much quicker than using strlen(t) */
{
    unsigned char c = t[j];
    for (int i = 7; i >= 0; i--) {
        printf("%d", (c >> i) & 1); /* No need to use ternary operator */
    }
    printf(" ");
}

Find a good read regarding not to use strlen() in for loop condition : Is using strlen() in the loop condition slower than just checking for the null character?


text:
Q: Writing a Prototype Constructor in C++ I am taking a quadratic expression, where y=ax^2 + bx + c with a,b,c are constants and x is a variable. Here is my class:
class quadratic {
public:
double evaluate(const double x);
void getCoefficients (double &A, double &B, double &C);
void setCoefficients (const double A, const double B, const double C);

private:
double a;
double b;
double c;
};

I am to create TWO constructors for the class so that the following is legal
quadratic y1 = quadratic(1.0, -5.0, 7.0);
quadratic y2 = quadratic(-3.0, -2.0, 10.0);
quadratic y3;

The default constructor should be set to zero while the parameters in the second constructor indicate initial values for the coefficients.
Here is how I believe I should do that:
quadratic()   //default values
{
double A, double B, double C = 0.0;
}

quadratic(double A, double B, double C)   //initial values
{
double A = double a;
double B = double b;
double C = double c;
}

However I'm not fully understanding how to set this up and would appreciate any gurus help in figuring this out.

A: The direct and simple way of doing this would be:
class quadratic {
 public:
  explicit quadratic(double A=0,double B=0,double C=0): a(A),b(B),c(C) { }
  double evaluate(const double x);
  void getCoefficients (double &A, double &B, double &C);
  void setCoefficients (const double A, const double B, const double C);

 private:
  double a;
  double b;
  double c;
};

Declaring a second constructor with no parameters and assigning all values to 0 is also acceptable but uses more code, for me the default values in the constructor are preferable.
This is the alternate solution identical except for the fact that using only 1 or 2 parameters in the constructor is no longer valid:
class quadratic {
 public:
  quadratic(double A,double B,double C): a(A),b(B),c(C) { }
  quadratic(): a(0), b(0), c(0) { }
  double evaluate(const double x);
  void getCoefficients (double &A, double &B, double &C);
  void setCoefficients (const double A, const double B, const double C);

 private:
  double a;
  double b;
  double c;
};

A: You should probably use the constructors' initializer list instead:
quadratic() : a(0), b(0), c(0)
{
}

quadratic(double A, double B, double C) : a(A), b(B), c(C)
{
}

The above uses a part of the C++ language to initialize member variables called an initializer list.

What you did for the constructor with parameters:
double A = double a;
double B = double b;
double C = double c;

First of all won't compile, but even if you simplify what you did to:
double A = a;
double B = b;
double C = c;

Then it is still won't compile because A, B, and C are already defined.  When you put a type name followed by a variable name like the above, it will try to create a new variable.
So if we simplify again to:
A = a;
B = b;
C = c;

Then this is still wrong again but at least it will compile.  It's wrong because you are setting the parameters to the value of the uninitialized class variables.
Instead you want:
a = A;
b = B;
c = C;

What you did for the constructor without parameters:
 double A, double B, double C = 0.0;

This won't compile.  The right syntax to declare many variables in a single line is as follows:
 double A = 0, B = 0, C = 0;

But this is still not correct, it will simply create 3 new variables A, B, and C and initialize them to 0.  What you really want is to set your member variables a,b, and c.
So you want:
a = b = c = 0;

A: Use the member initializer list:
quadratic():
    a(0),b(0),c(0)
{}

quadratic(double a_,double b_,double c_):
    a(a_),b(b_),c(c_)
{}

A: Use initialization lists to initialize class member variables. What you have written is assignment.
Also the code in OP assigns to local variables defined within the constructor and not the class member variables. I guess the intention was to initialize the member variables of the class
quadratic() : a(0.0), b(0.0), c(0.0)
{
}

quadratic(double A, double B, double C)  : a(A), b(B), c(C)
{
}


text:
Q: Token configuration for multiple workspace slack app If I want my app to be distributed to multiple workspaces, how will I then manage my tokens? I cannot hard-code the same token as it is unique for each workspace.

A:
You'll make use of the 'redirect url' to capture generated token and store it in a cache or db depending on your implementation.
Following documentation may help:

*

*https://slack.dev/java-slack-sdk/guides/app-distribution

*https://api.slack.com/authentication/oauth-v2


text:
Q: What is the order of the midpoint rule? If the Trapezoidal-Rule has the order $n=1$, and Simpson's has order $n=2$, what is the order $n$ of the midpoint rule?
And if the weights of the Trapeziumrule are ($1/2, 1/2$) and those of the Simpson-Rule are ($1/6, 4/6, 1/6$), what are the weights of the midpoint-rule?
Thank you in advance!

A: The error of the Midpoint rule is
$Error_m \leq \frac{k(b-a)^3}{24n^2 } = k(b-a)h^2/24$. So it equals to $O(h^2)$, where $k = max|f"|$.

A: The order of the midpoint rule is $n=2$. For examples, you can see Why does Trapezoidal Rule have potential error greater than Midpoint?


text:
Q: Excel Pivotchart not showing end of data labels I have a pivot chart which draws a line chart for a particular set of data, which can range from 2000-6000 values, all timestamped. For example:
01/04/2019 07:00    1.658478141
01/04/2019 07:14    1.713099122
01/04/2019 07:30    1.76636517
01/04/2019 07:44    1.815220237
01/04/2019 07:59    1.865214229
01/04/2019 08:15    1.915204883
01/04/2019 08:30    1.986165404

Where 01/04/2019 08:30 is the last value.
The actual line changes to represent all of the points within my table, however the x axis label never accurately shows the last data item. I do not mind what is shown inbetween the start and end, but it is imperative that the end time on the chart label reflects the end time of the data.
For example, for the above data, this is what the chart shows:

So far I have tried various methods found, such as changing the axis type to "text" as opposed to automatic, and this didn't work. I also tried to have a chart that referenced a "named" range, but this didn't work either.
If I resize the chart then the labels change, but it wouldn't be possible to have a chart wide enough for all 6000 labels to fit in the screen.

It seems like this should be easily achieved, but I can't figure out any other configurations to try.


text:
Q: How does global variable in package body work for multiple users
I have written a program in which SQL queries & query ID is saved in a table. User will select the query ID and program will generate its output to specified UNIX directory.

Right now I am saving the query in global variable of package body after fetching it from the table.

My concern is that when multiple users will run the program at same time, will my global variable (which is storing the SQL query) will update accordingly?
for example:
    create or replace package test
    is
    global_sql varchar2(40000);

       procedure get_sql(p_sql_id number)
        is
       begin

         select sql into global_sql from query_table where sql_id = p_sql_id;
         //more code
       end;

    end;

now when multiple users run this program at the same time for different sql_id, will my global_sql will be different for all users accordingly?

A: I suppose you mean package variables?
In that case any user in any different connection will get his own value in his own copy of variable. All this values will be stay in UGA(user global area).
For example i create package without body to hold one variable:
connect test/test

create or replace package test_var is
   v_sql_text varchar2(4000);
end test_var;
/

exec test_var.v_sql_text := 'FIRST_QUERY:select * from dual';

open another session
connect test/test
set serveroutput on

exec dbms_output.put_line( test_var.v_sql_text);

/*result is empty*/

exec test_var.v_sql_text := 'TEXT_QUERY:select * from all_tables';

exec dbms_output.put_line( test_var.v_sql_text);

--
TEXT_QUERY:select * from all_tables

return to the first session
exec dbms_output.put_line( test_var.v_sql_text);

--
FIRST_QUERY:select * from dual


text:
Q: How to disable scheduled task services As I am still fighting with Conficker  infection on my Win Server 2003.
I will like to temporarily disable scheduled task services on server.
Until I can be sure that infection of network is over.

A: How about opening services.msc and stopping the Task Scheduler service? Or net stop schedule from the command prompt. Or sc stop schedule. sc gives you a lot of other options too.


text:
Q: UTL_FILE.FGETATTR returns 0 for the block size When I use UTL_FILE.FGETATTR, the block size returns 0 each time. I can get file length etc, but block size returns 0. What can be the reason for that and how can I solve this?
OS : Windows 10
DB : 19c
DECLARE
    v_fexists       BOOLEAN;
    v_file_length   NUMBER;
    v_block_size    BINARY_INTEGER;
BEGIN
    UTL_FILE.FGETATTR ('TEST_DIR','temp file.txt',v_fexists,v_file_length,v_block_size);
    IF v_fexists THEN
        DBMS_OUTPUT.PUT_LINE('The file exists');
        DBMS_OUTPUT.PUT_LINE('Its length is     :'||v_file_length);
        DBMS_OUTPUT.PUT_LINE('Its block size is :'||v_block_size);
    ELSE
        DBMS_OUTPUT.PUT_LINE('The file does not exist!');
    END IF;
END;

PL/SQL procedure successfully completed.

The file exists
Its length is     :2794
Its block size is :0

A: I just post the answer that everybody is aware and you can mark the question as answered. It is more or less a recollection of everything we've been talking about on the comments section.

On Windows platforms, UTL_FILE.FGETATTR procedure returns 0 instead of
the correct block size even if the file exists. Windows platform does not provide any system sub-routine to obtain the filesystem I/O block size, as a result it returns 0, which is the expected behaviour.

Although it is predicted and documented for 9i/10g, the problem is reproducible on 12c, 18c and 19c as well.
Link to Support Note


text:
Q: C Program to count comment lines (// and /* */) I need a program to count the lines of a .txt or .c file and return me the following things:
File:
Simple Comment: N lines
Multiline Comment: N lines
Total Lines: N lines
I have this:
if (pFile != NULL)
{
    do {
    c = fgetc(pFile);

    if (c == '\n') n++;

    } while (c != EOF);

And I don't know how to implement the rest of it.
I tried with the strstr() function as well, didn't get it neither.

A: You can write a state machine that should handle most cases.
As you scan the file, you'll be in one of the following states:

*

*TEXT - regular (non-commented) text; this is the state you'll start in.  Any newline seen in this state will cause the total-lines counter to be incremented.

*SAW_SLASH - You've seen a single /, which may be the start of a single- or multi-line comment.  If the next character is a /, you'll go into the SINGLE_COMMENT state.  If the next character is a *, you'll go into the MULTI_COMMENT state.  For any other character, you go back into the TEXT state.

*SINGLE_COMMENT - you've seen the // token; you will stay in this state until you see a newline character; once you see the newline character you'll increment the number of single-line comments as well as total lines, and go back to the TEXT state.

*MULTI_COMMENT - you've seen the /* token; you will stay in this state until you see the next */ token.  Any newline you see in this state will cause the multi-comment line counter to be incremented along with the total lines.

*SAW_STAR - While in the MULTI_COMMENT state, you've seen a single *.  If the next character is /, you'll go back to the TEXT state.  If the next character is *, you'll stay in the SAW_STAR state.  Otherwise you'll go back to the MULTI_COMMENT state.

There are edge cases that I'm not dealing with (such as encountering an EOF while in a comment state), but the following should be a reasonable example of how you can do stuff like this.
Note that nested comments won't be counted; i.e., if a //-delimited comment appears within a /* */-delimited comment, only the multi-comment counter will be updated.
You will probably want to factor the counting logic into its own function; just trying to keep the example as straightforward as I can.
#include <stdio.h>
#include <stdlib.h>

/**
 * Count up the number of total lines, single-comment lines,
 * and multi-comment lines in a file.
 */
int main(int argc, char **argv)
{
  FILE *fp;
  int c;
  unsigned int chars  = 0;
  unsigned int total  = 0;
  unsigned int multi  = 0;
  unsigned int single = 0;

  enum states { TEXT,
                SAW_SLASH,
                SAW_STAR,
                SINGLE_COMMENT,
                MULTI_COMMENT } state = TEXT;

  if ( argc < 2 )
  {
    fprintf(stderr, "USAGE: %s <filename>\n", argv[0]);
    exit(0);
  }

  fp = fopen( argv[1], "r" );
  if ( !fp )
  {
    fprintf(stderr, "Cannot open file %s\n", argv[1] );
    exit(0);
  }

  while ( (c = fgetc( fp )) != EOF )
  {
    chars++;
    switch( state )
    {
      case TEXT :
        switch( c )
        {
          case '/'  : state = SAW_SLASH; break;
          case '\n' : total++; // fall-through
          default   : break;
        }
        break;

      case SAW_SLASH :
        switch( c )
        {
          case '/'  : state = SINGLE_COMMENT; break;
          case '*'  : state = MULTI_COMMENT; break;
          case '\n' : total++; // fall through
          default   : state = TEXT; break;
        }
        break;

      case SAW_STAR :
        switch( c )
        {
          case '/'  : state = TEXT; multi++; break;
          case '*'  : break;
          case '\n' : total++; multi++; // fall through
          default   : state = MULTI_COMMENT; break;
        }
        break;

      case SINGLE_COMMENT :
        switch( c )
        {
          case '\n' : state = TEXT; total++; single++; // fall through
          default   : break;
        }
        break;

      case MULTI_COMMENT :
        switch( c )
        {
          case '*'  : state = SAW_STAR; break;
          case '\n' : total++; multi++; // fall through
          default   : break;
        }
        break;

      default: // NOT REACHABLE
        break;
    }
  }

  fclose(fp);

  printf( "File                 : %s\n", argv[1] );
  printf( "Total lines          : %8u\n", total );
  printf( "Single-comment lines : %8u\n", single );
  printf( "Multi-comment lines  : %8u\n", multi );
  return 0;
}

EDIT
Here's a table-driven equivalent to the program above.  I create a state table to control state transitions and an action table to control what happens when I change state.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

/**
 * Using preprocessor macros instead of enums, per request; normally
 * I would use enums, since they obey scoping rules and
 * show up in debuggers.
 */
#define TEXT           0
#define SAW_SLASH      1
#define SAW_STAR       2
#define SINGLE_COMMENT 3
#define MULTI_COMMENT  4

#define TOTAL_STATES   5

#define NO_ACTION      0
#define INC_TOTAL      1
#define INC_SINGLE     2
#define INC_MULTI      4

/**
 * This example assumes 7-bit ASCII, for a total of
 * 128 character encodings.  You'll want to change this
 * to handle other encodings.
 */
#define ENCODINGS    128

/**
 * Need a state table to control state transitions and an action
 * table to specify what happens on a transition.  Each table
 * is indexed by the state and the next input character.
 */
static int  state[TOTAL_STATES][ENCODINGS]; // Since these tables are declared at file scope, they will be initialized to
static int action[TOTAL_STATES][ENCODINGS]; // all elements 0, which correspond to the "default" states defined above.

/**
 * Initialize our state table.
 */
void initState( int (*state)[ENCODINGS] )
{
  /**
   * If we're in the TEXT state and see a '/' character, move to the SAW_SLASH
   * state, otherwise stay in the TEXT state
   */
  state[TEXT]['/'] = SAW_SLASH;

  /**
   * If we're in the SAW_SLASH state, we can go one of three ways depending
   * on the next character.
   */
  state[SAW_SLASH]['/'] = SINGLE_COMMENT;
  state[SAW_SLASH]['*'] = MULTI_COMMENT;
  state[SAW_SLASH]['\n'] = TEXT;

  /**
   * For all but a few specific characters, if we're in any one of
   * the SAW_STAR, SINGLE_COMMENT, or MULTI_COMMENT states,
   * we stay in that state.
   */
  for ( size_t i = 0; i < ENCODINGS; i++ )
  {
    state[SAW_STAR][i] = MULTI_COMMENT;
    state[SINGLE_COMMENT][i] = SINGLE_COMMENT;
    state[MULTI_COMMENT][i] = MULTI_COMMENT;
  }

  /**
   * Exceptions to the loop above.
   */
  state[SAW_STAR]['/'] = TEXT;
  state[SAW_STAR]['*'] = SAW_STAR;

  state[SINGLE_COMMENT]['\n'] = TEXT;
  state[MULTI_COMMENT]['*'] = SAW_STAR;
}

/**
 * Initialize our action table
 */
void initAction( int (*action)[ENCODINGS] )
{
  action[TEXT]['\n'] = INC_TOTAL;
  action[SAW_STAR]['/'] = INC_MULTI;
  action[MULTI_COMMENT]['\n'] = INC_MULTI | INC_TOTAL;   // Multiple actions are bitwise-OR'd
  action[SINGLE_COMMENT]['\n'] = INC_SINGLE | INC_TOTAL; // together
  action[SAW_SLASH]['\n'] = INC_TOTAL;
}

/**
 * Scan the input file for comments
 */
void countComments( FILE *stream, size_t *totalLines, size_t *single, size_t *multi )
{
  *totalLines = *single = *multi = 0;

  int c;
  int curState = TEXT, curAction = NO_ACTION;

  while ( ( c = fgetc( stream ) ) != EOF )
  {
    curAction = action[curState][c]; // Read the action before we overwrite the state
    curState = state[curState][c];   // Get the new state (which may be the same as the old state)

    if ( curAction & INC_TOTAL )     // Execute the action.
      (*totalLines)++;

    if ( curAction & INC_SINGLE )
      (*single)++;

    if ( curAction & INC_MULTI )
      (*multi)++;
  }
}

/**
 * Main function.
 */
int main( int argc, char **argv )
{
  /**
   * Input sanity check
   */
  if ( argc < 2 )
  {
    fprintf( stderr, "USAGE: %s <filename>\n", argv[0] );
    exit( EXIT_FAILURE );
  }

  /**
   * Open the input file
   */
  FILE *fp = fopen( argv[1], "r" );
  if ( !fp )
  {
    fprintf( stderr, "Cannot open file %s\n", argv[1] );
    exit( EXIT_FAILURE );
  }

  /**
   * If input file was successfully opened, initialize our
   * state and action tables.
   */
  initState( state );
  initAction( action );

  size_t totalLines, single, multi;

  /**
   * Do the thing.
   */
  countComments( fp, &totalLines, &single, &multi );
  fclose( fp );

  printf( "File                 : %s\n", argv[1] );
  printf( "Total lines          : %zu\n", totalLines );
  printf( "Single-comment lines : %zu\n", single );
  printf( "Multi-comment lines  : %zu\n", multi );

  return EXIT_SUCCESS;
}

Running the file on itself gives us
$ ./comment_counter comment_counter.c
File                 : comment_counter.c
Total lines          : 150
Single-comment lines : 7
Multi-comment lines  : 42

which I think is right.  This has all the same weaknesses as the first version, just in a different form.

A: So n == # of lines in the file.
You'll need another variable that counts every time you see the character / followed by another / (this is easy, same way that you're doing n++ basically, but it should look like
 if( c == '/') c = fgetc(pFile); if(c == '/') comments++; else break;

And then for multiline comments, you do the same thing, and just count /, just like above.  You'll just have to keep an eye on when n gets incremented (every line), and when the other ones get incremented (Once for every line with // and once for every line that starts with / and until you hit a */).


text:
Q: WPF Dependency Property for Custom Control I'm a bit in a mess with how to set a Dependency Property for Custom Control.
I created Custom Control, so it derives from Control class.
public class CustControl : Control
    {
      static CustControl()
       {
         DefaultStyleKeyProperty.OverrideMetadata(typeof(CustControl), new FrameworkPropertyMetadata(typeof(CustControl)));
       }
    }

In order to set Dependency Property I have to register it inside a class which must be derived from DependencyObject. So it should be another class:
class CustClass : DependencyObject
{
    public readonly static DependencyProperty MyFirstProperty = DependencyProperty.Register("MyFirst", typeof(string), typeof(CustControl), new PropertyMetadata(""));

    public string MyFirst
    {
        get { return (string)GetValue(MyFirstProperty); }
        set { SetValue(MyFirstProperty, value); }
    }
}

How now I could set MyFirst property as dependency property for CustControl?

A:
In order to set Dependency Property I have to register it inside a class which must be derived from DependencyObject. So it should be another class:

No, it shouldn't. Control already derives from DependencyObject. Since inheritance is transitive, this makes CustControl a subtype of DependencyObject as well. Just put it all into CustControl:
public class CustControl : Control
{
      static CustControl()
      {
          DefaultStyleKeyProperty.OverrideMetadata(typeof(CustControl), new FrameworkPropertyMetadata(typeof(CustControl)));
      }

    public readonly static DependencyProperty MyFirstProperty = DependencyProperty.Register("MyFirst", typeof(string), typeof(CustControl), new PropertyMetadata(""));

    public string MyFirst
    {
        get { return (string)GetValue(MyFirstProperty); }
        set { SetValue(MyFirstProperty, value); }
    }
}


text:
Q: Python BS4 append extraSoup after a TEXT I have a file and I need to modify it with Python. there is a text inside of the file which is not included in any tag. it is like this:
===TEXT===

I need to append data after this text. I have a python script with BS4:
for index, row in df.iterrows():
        with open("template.html", 'r') as inf:
            html = inf.read()
            soup = bs4.BeautifulSoup(html, features="html.parser")

            extraSoup = bs4.BeautifulSoup("""
            {{transclude name="link" }}
            """, "html.parser")

            for container in soup.find(text="===TEXT==="):
                container.append(extraSoup)
        prettyHTML = soup.prettify()
        with open("template.html", 'w') as outf:
            outf.write(str(prettyHTML))

I am trying to find the text and append the extraSoup. But I get error
AttributeError: 'NoneType' object has no attribute

Is it even possible to do this with BS4? cause I think BS4 only work with tags? is there any way to achieve this?

A:
I think BS4 only work with tags?

It's not clear where you got this idea. BS4, like any spec-compliant HTML parser, will parse otherwise unbound text into a text node. Use find_all() and check its contents for your templating constant (===TEST===) before using insert_after to insert the content you're after into the DOM.
Test HTML:

 test

===TEXT===

 test

Updated Python script:
import bs4
with open("template.html", 'r') as inf:
  html = inf.read()
  soup = bs4.BeautifulSoup(html, features="html.parser")

  for container in soup.findAll(text=True):
    print(container.text)
    if container.text.strip() == "===TEXT===":
      container.insert_after('{{transclude name="link" }}')
  prettyHTML = soup.prettify()
with open("template2.html", 'w') as outf:
  outf.write(str(prettyHTML))

Output:

 test

===TEXT===
{{transclude name="link" }}

 test

Repl.it


text:
Q: Naming words inside square brackets in Dictionaries and Lists We are having a naming issue. if we have dictionary:
dictionary[key]

or a list
list[1]
list[3:4]
list[:3]

what are the names of the words inside "[" "]", accessors? parameters? keys?

A: Regarding a dictionary, the name given to the value within the square brackets is a key. This is because a Dictionary is a key-value pair repository. An example of this use can be found in Microsoft's definition of a Dictionary item property here.
For a list, the name given to the value within the square brackets is an index. This is because it is used to select an item from the list at the specified (usually zero-based) index. Again, an example of this naming convention can be found here.
Note that whilst I have included links to Microsoft documentation in this answer, the use of "key" and "index" for dictionaries and lists (respectively) is a convention used through most, if not all, programming languages.


text:
Q: How to use jest with node_modules using es6 within NX project I have a project with NX structure(apps + libs). And I am writing tests for react + typescript lib. I faced the issue when I try to use suneditor + suneditor-react:
Jest encountered an unexpected token

    Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

    Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

    By default "node_modules" folder is ignored by transformers.

    Here's what you can do:
     • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     • If you need a custom transformation specify a "transform" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/configuration
    For information about custom transformations, see:
    https://jestjs.io/docs/code-transformation

    Details:

   ...\node_modules\suneditor\src\plugins\index.js:4
    import blockquote from './command/blockquote';

I found the files are not transformed when they are in node_modules and made this change to jest config:
transformIgnorePatterns: [
     "<rootDir>/node_modules/(?!suneditor|suneditor-react)"
  ]

After this I am continuously getting the error for all tests:
● Test suite failed to run
    Cannot find module 'babel-preset-es2015'

 at resolveStandardizedName (../../node_modules/@babel/core/lib/config/files/plugins.js:100:7)
      at resolvePreset (../../node_modules/@babel/core/lib/config/files/plugins.js:48:10)
      at loadPreset (../../node_modules/@babel/core/lib/config/files/plugins.js:67:20)
      at createDescriptor (../../node_modules/@babel/core/lib/config/config-descriptors.js:154:9)
      at ../../node_modules/@babel/core/lib/config/config-descriptors.js:109:50
          at Array.map (<anonymous>)
      at createDescriptors (../../node_modules/@babel/core/lib/config/config-descriptors.js:109:29)
      at createPresetDescriptors (../../node_modules/@babel/core/lib/config/config-descriptors.js:101:10)

Jest config:
module.exports = {
  displayName: 'component',
  preset: '../../jest.preset.js',
  transform: {
    '^.+\\.[tj]sx?$': 'babel-jest',
  },
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'],
  coverageDirectory: '../../coverage/libs/pbc-client-journal',
  transformIgnorePatterns: [
     "<rootDir>/node_modules/(?!suneditor|suneditor-react)"
  ]
};

And jest.preset.js:
const nxPreset = require('@nrwl/jest/preset');
module.exports = { ...nxPreset };

.babelrc:
{
  "presets": [
    [
      "@nrwl/react/babel",
      {
        "runtime": "automatic",
        "useBuiltIns": "usage"
      }
    ]
  ]
}

Could someone please help me with this issue?

A: You need to switch to babel.config.js in your lib to be able to transform files from node_modules. Here is what worked in my project:
babel.config.js
module.exports = {
  presets: [
    [
      "@nrwl/react/babel",
      {
        runtime: "automatic",
        useBuiltIns: "usage"
      }
    ]
  ],
  plugins: []
}

jest.config.js
module.exports = {
  displayName: 'mylib',
  preset: '../../jest.preset.js',
  transform: {
    '^.+\\.[tj]sx?$': ['babel-jest', { cwd: __dirname }],
  },
  transformIgnorePatterns: [
    "node_modules/(?!(@asyncapi)/)"
  ],
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'],
  coverageDirectory: '../../coverage/libs/mylib',
};


text:
Q: bases of a function field I read this example

Example 3.33: Consider the Hermitian curve with equation $x^{r+1}=y^r+y$ over the field $\mathbb{F}_{r^2}$.  Here $Q = (0:1:0)$ and $X = x/z$, $Y=y/z$ is a monomial generating set for
  $$R = \bigcup_{m=0}^\infty {L}(mQ).$$
  It is obvious that the sets $\{X^iY^j\mid 0 \le i < r\}$ and $\{X^iY^j\mid 0 \le i < r+1\}$ each describes bases for $R$.

but I can't understand that why did the sets describe bases for $R$?
Why are there two bases for $R$? But we know that base should be unique.


text:
Q: android edittext keyboard not showing after dialog dismissal I have an edit text that is working fine but after dismissing a dialog the keyboard is not showing despite the edit text is focused and the cursor is shown
I searched a lot and tried many solutions that didn't fix my issue
i tried these methods but they didn't work
public void showKeyboard(){
    InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
    inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}

public void closeKeyboard(){
    InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
    inputMethodManager.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
}

and also tried adding them inside a runnable

A: here is the method I use to show keyboard for an edittext.
kotlin code:
below is an extension function for kotlin just need to call edittext.showKeyboard()
fun EditText.showKeyboard() {
  post {
    requestFocus()
    val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
  }
}

the java code:
public static void showKeyboard(EditText editText) {
    editText.post(new Runnable() {
      @Override
      public void run() {
        editText.requestFocus();
        InputMethodManager imm = (InputMethodManager) editText.getContext()
            .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
      }
    });
  }


text:
Q: Change last logon for user(s) in Active Directory Is there any way to artificially change the "lastLogon" and/or "lastLogonTimestamp" for a user?
I have a script that disables and/or deletes old users and I want to make sure it is getting the dates correctly with test users before I put it into production.
I have tried using an LDAP tool, but I am seemingly not allowed to alter that user property - I get the error "Unwilling to perform".
All suggestions are welcome.

A: you can accomplish that using adsi edit, it's a very powerful tool, so be careful.

*

*start->run->"adsiedit.msc"
if you get "command not found" this should help

*browse to the user

*right click, properties

*there you are :)

A: There is also a sysinternals app called ADExplorer that you might want to check out.
Download here - http://technet.microsoft.com/en-us/sysinternals/bb963907.aspx
Once you connect to your domain, you can browse down to the user and see the specific attributes.  Then right click and Modify the selected attribute.

A: Note that lastLogonTimestamp is not replicated - each DC holds its own value.  To get a true picture of a person's last logon, you'll need to gather the value from each DC and determine which is the latest.


text:
Q: Converting division of int to int to a decimal is giving 0 I came up with a formula to keep numbers a simple int and was surprised to see that the following was producing a 0.
var x = 45;
var y = 100;
var z = Convert.ToDecimal(x / y * 100);

In the above example, it almost seems ridicilous that I'm dividing by 100, then multiplying by 100 but in most cases, the x and y values are not nice integers.
When my x and y values end up being integers, the above conversion produces a 0. Why is that?

A: X / Y = 0.45
Int conversion of 0.45 is 0.
Therefore 0 * 100 = 0.
Therefore Convert.ToDecimal(0) is 0.

A: This does look a bit odd, but the problem there is with the order the expressions are evaluated: first the arguments of Convert are evaluated, and that is done inintegers. That's why the result is truncated.
You should replace the conversation with an expression that forces evaluation in decimals:
var z = 100M * x / z;


text:
Q: Android ViewPager custom TabIndicator not working I have Googled around for a couple of hours now, for a solution on how to change the color of the TabIndicator in a ViewPager. From the documentation i get, that I should add a PagerTabStrip as the child to my ViewPager in XML. But this is not working as intended. Any suggestions on a solution?
Here is my code:
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.adrissa.klea.MainActivity" >

<FrameLayout
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

<android.support.v4.view.ViewPager
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#934932"
    tools:context="com.adrissa.klea.MainActivity" >

    <android.support.v4.view.PagerTabStrip
        android:id="@+id/pager_title_strip"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </android.support.v4.view.PagerTabStrip>
</android.support.v4.view.ViewPager>

<fragment
    android:id="@+id/navigation_drawer"
    android:name="com.adrissa.klea.NavigationDrawerFragment"
    android:layout_width="@dimen/navigation_drawer_width"
    android:layout_height="match_parent"
    android:layout_gravity="start" />

</android.support.v4.widget.DrawerLayout>

And this is what it looks like:

Obviously what I thought would be the end result is that the light blue tabIndicator was black, but it somehow gets underneath?

A: You Just need to do this with these magic lines.
 PagerTabStrip pagerTabStrip = (PagerTabStrip) findViewById(R.id.pager_title_strip);
 pagerTabStrip.setDrawFullUnderline(true);
 pagerTabStrip.setTabIndicatorColor(Color.Black);

A: In the themes.xml file i added this code
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android">
    <style name="CustomActionBarTheme" parent="@style/Theme.AppCompat.Light.DarkActionBar">
        <item name="android:actionBarTabStyle">@style/MyActionBarTabs</item>
        <item name="actionBarTabStyle">@style/MyActionBarTabs</item>
    </style>

<style name="MyActionBarTabs" parent="@style/Widget.AppCompat.ActionBar.TabView">

    <!-- tab indicator -->
    <item name="android:background">@drawable/actionbar_tab_indicator</item>

    <!-- Support library compatibility -->
    <item name="background">@drawable/actionbar_tab_indicator</item>
</style>

Then this is the actionbar_tab_indicator.xml file in the drawable folder:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

<!-- STATES WHEN BUTTON IS NOT PRESSED -->

<!-- Non focused states -->
<item android:state_focused="false" android:state_selected="false"
      android:state_pressed="false"
      android:drawable="@drawable/tab_unselected" />
<item android:state_focused="false" android:state_selected="true"
      android:state_pressed="false"
      android:drawable="@drawable/tab_selected" />

<!-- Focused states (such as when focused with a d-pad or mouse hover) -->
<item android:state_focused="true" android:state_selected="false"
      android:state_pressed="false"
      android:drawable="@drawable/tab_unselected_focused" />
<item android:state_focused="true" android:state_selected="true"
      android:state_pressed="false"
      android:drawable="@drawable/tab_selected_focused" />

<!-- STATES WHEN BUTTON IS PRESSED -->

<!-- Non focused states -->
<item android:state_focused="false" android:state_selected="false"
      android:state_pressed="true"
      android:drawable="@drawable/tab_unselected_pressed" />
<item android:state_focused="false" android:state_selected="true"
    android:state_pressed="true"
    android:drawable="@drawable/tab_selected_pressed" />

<!-- Focused states (such as when focused with a d-pad or mouse hover) -->
<item android:state_focused="true" android:state_selected="false"
      android:state_pressed="true"
      android:drawable="@drawable/tab_unselected_pressed" />
<item android:state_focused="true" android:state_selected="true"
      android:state_pressed="true"
      android:drawable="@drawable/tab_selected_pressed" />
</selector>

Then for the tab_selected state i create this xml file.
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:top="-6dp"
        android:left="-6dp"
        android:right="-6dp"
        android:bottom="0dp">

        <shape android:shape="rectangle">
            <solid android:color="#ffffff"/>
            <stroke
                android:width="5dp"
                android:color="#07368e"/>
        </shape>
    </item>
</layer-list>

Then for my layout i get this tab indicator.


text:
Q: Forward Declaration of a Base Class I'm trying to create proper header files which don't include too many other files to keep them clean and to speed up compile time.
I encountered two problems while doing this:

*

*Forward declaration on base classes doesn't work.
class B;

class A : public B
{

    // ...
}

*Forward declaration on STD classes doesn't work.
namespace std
{
    class string;
}

class A
{
    string aStringToTest;
}

How do I solve these problems?

A: As answered before by Earwicker, you can not use forward declarations in any of those cases as the compiler needs to know the size of the class.
You can only use a forward declaration in a set of operations:

*

*declaring functions that take the forward declared class as parameters or returns it

*declaring member pointers or references to the forward declared class

*declaring static variables of the forward declared type in the class definition

You cannot use it to

*

*declare a member attribute of the given type (compiler requires size)

*define or create an object of the type or delete it

*call any static or member method of the class or access any member or static attribute

(did I forget any?)
Take into account that declaring an auto_ptr is not the same as declaring a raw pointer, since the auto_ptr instantiation will try to delete the pointer when it goes out of scope and deleting requires the complete declaration of the type. If you use an auto_ptr in to hold a forward declared type you will have to provide a destructor (even if empty) and define it after the full class declaration has been seen.
There are also some other subtleties. When you forward declare a class, you are telling the compiler that it will be a class. This means that it cannot be an enum or a typedef into another type. That is the problem you are getting when you try to forward declare std::string, as it is a typedef of a specific instantiation of a template:
typedef basic_string<char> string; // aproximate

To forward declare string you would need to forward declare the basic_string template and then create the typedef. The problem is that the standard does not state the number of parameters that basic_string template takes, it just states that if it takes more than one parameter, there rest of the parameters must have a default type so that the expression above compiles. This means that there is no standard way for forward declaring the template.
If, on the other hand you want to forward declare a non-standard template (non STL, that is) you can do it for as long as you do know the number of parameters:
template <typename T, typename U> class Test; // correct
//template <typename T> class Test; // incorrect even if U has a default type

template <typename T, typename U = int> class Test {
   // ...
};

At the end, the advice that was given to you by Roddy: forward declare as much as you can, but assume that some things must be included.

A: In both cases the compiler needs to know the size of the type. Therefore, a forward declaration will not suffice. A base class could add members or require a virtual table. The string member would require the size of the class to be increase to store the size of the STL string class.
Forward declaring STL classes is often inadvisable since the implementations commonly include explicit template instantiations that speed up compilation.

A: The first problem you can't solve.
The second problem is not anything to do with standard library classes. It's because you declare an instance of the class as a member of your own class.
Both problems are due to the requirement that the compiler must be able to find out the total size of a class from its definition.
However, the compiler can work out the size of a pointer to a class, even if it doesn't yet have the full definition of it. So a possible solution in such cases is to have a pointer (or reference) member in the consuming class.
Not much help in the base class case, because you won't get an 'is a' relationship.
Nor is it worth doing for something like std::string. Firstly, it's supposed to be a convenient wrapper around a character buffer, to save you from doing memory management on something so simple. If you then hold a pointer to it, just to avoid including the header, you're probably taking a good idea too far.
Secondly (as pointed out in a comment), std::string is a typedef to std::basic_string<char>. So you need to forward declare (and then use) that instead, by which time things are getting very obscure and hard to read, which is another kind of cost. Is it really worth it?

A: You're trying too hard to solve something that isn't actually a problem. Use the header files you need, and reduce - WHERE POSSIBLE - the requirement for them. But don't try and take it to extremes because you'll fail.
In some cases, the PIMPL idiom may help you, but not here.

A: For your base classes, you need to have the full type definition, not just a declaration. Derived type headers will need to #include the header for their base classes.
For classes in the std namespace, you must include the proper header - <string> in this case - and then do one of 3 things:

*

*Fully qualify the type: std::string
aStringToTest

*Put a using declaration for just
that type: using std::string;

*Put in a using declaration for the
std namespace: using namespace std;

A: > Seems that forward declaration is useless for base classes and stl classes.
Correction...
Forward declaration is INAPPROPRIATE for base classes and object member.  (It's not "useless", it is "inapplicable".)
A base class MUST be declared (not forward declared) when being declared as a based class of another class.
An object member MUST be declared (not forward declared) when being declared by another class, or as parameter, or as a return value.  NOTE: by-reference or by-pointer does not have that constraint.
Correction...
Forward declaration of STL classes is -- as per ISO 14882 -- undefined behavior.
http://www.gotw.ca/gotw/034.htm


text:
Q: Is it possible to restrict branching and tagging in CVS at the server? We need to convert a production CVS respository to SVN. We are using CVS2SVN for the raw conversion process as well as some other tools.
Because this is a live development repository, the downtime at the repository switchover point is fairly important. Our test runs of the base CVS2SVN conversion are taking approximately 5 days at present, which is too long.
I'm looking some alternative approaches for making the process somewhat incremental. One of the approaches requires that tagging and branching be restricted on the CVS repository.
Is it possible to restrict tagging and branching, but allow normal commits at the CVS repository?

A: So it turns out that this is possible using the taginfo pre-commit script as detailed in the admin section of the manual here.
The taginfo File
What loginfo does for log messages, taginfo does for tags. The left side of taginfo is regular expressions, as usual, and the right side is programs. Each program is automatically handed arguments when CVS tag is invoked, in this order:
arg 1:          tag name
arg 2:          operation ("add" => tag, "mov" => tag -F, "del" => tag -d)
arg 3:          repository
arg 4, 5, etc:  file revision [file revision ...]

If the program returns nonzero, the tag is aborted.


text:
Q: "Connection in use" error in GCP app engine I am new to GCP App engine. I am trying to make web server using flask on App engine. I tested the version of my code on localhost and it is working fine. But when I am trying to deploy it in the App Engine of GCP it is giving me this strange error "app logs".
error logs
Here is my code for the flask
app.run(threaded = True, host='127.0.0.1', port=80)

Thanks!!

A: You don't need to call app.run() in your main.py file -- App Engine will do that for you. Simply initialize the app variable in this file instead.


text:
Q: Deep link to my app does not open from web app or email using expo and react navigation Deep Links I can't open my deep link: exp://127.0.0.1:19000/ from web or email but works if I use this command line on my VM:
adb shell am start -W -a android.intent.action.VIEW -d "exp://127.0.0.1:19000/--/settings"
is there any possibility to make this deep link behave like an url, in order to be able to open it from web and mail ?
Thank you for your help

A: May be this is late answer but if helpful to someone.
Here are some steps to follow to add deep-links into your expo project.
Please follow this documentation to add data into your app.json file to configure you app from client end Linking
Add assetlinks.json file for android / apple-app-site-association for ios in .well-known folder into you server-side so that when you open link in browser it can remember your app in mobile.


text:
Q: JQuery use mouseover dynamically on an HTML list I'm sorry if I didn't word the title the best way, but here's the problem I'm attempting to solve. I have an audio player that allows you to select songs from an list index. With that index I also have a description that pops up when you click on the song. I'm looking to transfer that into a hover so that whenever any song in the list is hovered, the description will appear and when you move the mouse away it will go away as well.
The JS -
function audioPlayer(){
        var descriptions = ["Sad Man's Tongue. . .Description to follow",
        "Breed. . .Description to follow",
        "Everything Zen. . .Description to follow",
        "Ain't It Funky Now Pt2. . .Description to follow",
        "Killing All The Joy. . .Description to follow",
        "OWS. . .Description to follow",
        "X1 Alpha. . .Description to follow",
        "Low. . .Description to follow",
        "Reconsider Baby. . .Description to follow",
        "4Lee. . .Description to follow",
        "Show Biz Kids. . .Description to follow"
    ];

        var currentSong = 0;
        $("#audioPlayer")[0].src = $("#playlist li a")[0];
        $("#playlist li a").click(function(e){
            e.preventDefault();
            $("#audioPlayer")[0].src = this;
            $("#audioPlayer")[0].play();
            $("#playlist li").removeClass("current-song");
            currentSong = $(this).parent().index();
            $(this).parent().addClass("current-song");
            let currentDescription = descriptions[currentSong]
            $('#song-info').css('display', 'inline');
            $('#song-info').text(currentDescription);
         });

    $("#audioPlayer")[0].addEventListener("ended", function(){
  $("#playlist li").removeClass("current-song");
        $('#song-info').css('display', 'inline');
        $('#song-info').text("Time for the next song ...turn it up LOUDER");
        $("#audioPlayer")[0].src = $("#playlist li a")[currentSong].href;
        $("#audioPlayer")[0].play;
    });

    $("#audioPlayer")[0].addEventListener("mouseover", function(){
        let hoverDescription = description[$(this).index()];
        document.getElementById("song-hover-info").style.zIndex = "11";
        $('#song-hover-info').css('display', 'inline');
        $('#song-hover-info').text(hoverDescription);
    });
    $("#audioPlayer")[0].addEventListener("mouseleave", function(){
        document.getElementById("song-hover-info").style.zIndex = "9";
    });

    }// JavaScript Document

The CSS -
.current-song{
            color:aqua;
}
    .footer{
        position: fixed;
        text-align: center;
        bottom: 0px;
        width: 100%;
    }
    .blacktextbg{
        background-color: #000000;
    }
    #playlist{
        font-size: 24;
    }
    .fader{
        position: absolute;
        height: 100%;
        width: 100%;
        z-index: -1;
        background-size: 100% 100%;
        background-repeat : no-repeat;
    }
    #song-info{
        padding: 10px;
        color: black;
        background-color: white;
        border: black 2px;
        width: 25%;
        z-index: 10;

    }
    #song-hover-info{
        padding: 10px;
        color: black;
        background-color: white;
        border: black 2px;
        width: 25%;
        z-index: 9;
    }

Relevant HTML
<audio src="" controls id="audioPlayer">
    Sorry, your browser doesn't support html5!
</audio>

Sad Man's Tongue

Breed

Everything Zen

Ain't It Funky Now Pt 2

Killing All The Joy

OWS

X1 Alpha

Low

Reconsider Baby

4LEE

Show Biz Kids

    Select a song above and turn it up LOUD

The array descriptions holds the individual song descriptions.
The z-index is because I don't want to get rid of song-info, it serves a purpose for after a song has ended. I want the hover information to appear when there is a hover so that was the first solution that came to mind.

A: If your UL LI html syntax is the area of your code that users will be hovering on, the code below should give you the ability to detect when someone is hovering over one of your LI elements.
$('#playlist').on({
    mouseenter: function() {
        alert('mouseenter - hovered');
    },
    mouseleave: function() {
        alert('mouseleave - no hover');
    }
}, 'li');

A: Try this code
    var descriptions = ["Sad Man's Tongue. . .test1",
    "Breed. . .test2",
    "Everything Zen. . .test3",
    "Ain't It Funky Now Pt2. . .test4",
    "Killing All The Joy. . .test5",
    "OWS. . .test6",
    "X1 Alpha. . .test7",
    "Low. . .test8",
    "Reconsider Baby. . .test9",
    "4Lee. . .test10",
    "Show Biz Kids. . .test11"]

  $( "li" ).hover(function() {
      var i=0;
      while (i<descriptions.length)
      {
        if($(this).text() == descriptions[i].split(". . .")[0].toString())
        {
            document.getElementById("song-hover-info").innerHTML = descriptions[i].split(". . .")[1];
        }
        i+=1;
      }

        });


text:
Q: Armadillo eigs_sym: decomposition failed I am writing C++ code within Visual Studio and using Armadillo 7.900.1
I am having no luck getting eigs_sym function working under Armadillo (I am using the lapack and blas versions that came with Armadillo). The typical error message is as below:
error: lapack::stedc(): failed to compute all eigenvalues
warning: eigs_sym(): decomposition failed

The code that is producing this output is:
sp_mat T(locations, values);
arma::eigs_sym(eigval, eigvec, T, num_eigs_wanted, "sm", tol);

where
T is a 480,000x480,000 sparse matrix.

I can get the code working if T is small (ie. 2000x2000) and tol is high (tol = 5). But once T is about 20000x20000, then no matter what values of tol or num_eigs_wanted are used then the above error occurs. (I obviously change "values" and locations" to alter the size of T).
The matrix T is symmetric, real, positive definite.
The exact same matrix has no problems when I call the eigs function within Matlab.
Any ideas? To me it seems that eigs_sym in Armadillo is broken...any alternatives that people have used?
Cheers

A: Not an answer but way too long for a comment.  I can reproduce with the code below.  The matrix is just a diagonal matrix with ascending values on the diagonal starting at 1.  The eigenvalues are obviously 1,2,3,... and the matrix is positive definite and symmetric.
#include <iostream>
#include <armadillo>

int main()
{
  constexpr int N = 20000;
  arma::umat locations(2,N);
  arma::vec values(N);

  for (int i = 0; i < N; ++i)
  {
    locations(0,i) = i;
    locations(1,i) = i;
    values(i) = i+1;
  }

  arma::sp_mat T(locations, values);

  int num_eigs_wanted = 1;
  arma::vec eigval(num_eigs_wanted);
  arma::mat eigvec(N,num_eigs_wanted);
  double tol = 1e-6;
  arma::eigs_sym(eigval, eigvec, T, num_eigs_wanted, "sm", tol);

  std::cout << eigval << '\n';
}

Compiler flags are
clang++-5.0 -std=c++11 test.cpp -larmadillo

I'm using Armadillo with MKL backend and I receive:
warning: eigs_sym(): decomposition failed
[matrix size: 0x1]

It seems to be a problem of Armadillo, because when I use the unsupported Arpack support of Eigen it works just fine.
#include <iostream>
#include <Eigen/Sparse>
#include <unsupported/Eigen/ArpackSupport>

int main()
{
  constexpr int N = 20000;

  std::vector< Eigen::Triplet<double> > triplets;
  triplets.reserve(N);
  for (int i = 0; i < N; ++i)
    triplets.push_back( {i,i,i+1} );

  Eigen::SparseMatrix<double> T(N,N);
  T.setFromTriplets(triplets.begin(), triplets.end());

  int num_eigs_wanted = 1;
  double tol = 1e-6;
  Eigen::ArpackGeneralizedSelfAdjointEigenSolver< Eigen::SparseMatrix<double> > eigs_sym;
  eigs_sym.compute(T, num_eigs_wanted, "SM", Eigen::ComputeEigenvectors, tol);
  std::cout << eigs_sym.eigenvalues() << '\n';
}

You might also want to take a look at https://github.com/yixuan/spectra/

A: Thanks @Henri for all your help! Spectra (https://spectralib.org) is the way to go!
The eigenvalue/vestor decomposition using SymEigsSolver on a sparse matrix of size 480,000 x 480,000 takes me 3 mins 50 sec (i7/16GB RAM).
A sparse matrix of size 120,000x120,000 takes 20 seconds.
No stability problems and the programmer has direct access to the Arnoldi Algorithm, Ritz values and tolerance threshold.
Easy to use as well since Spectra is purely header based. Just #include the header files - simple. You'll need Eigen as well which is also available at the above address (and it's also header based).