text:
Q: How to Take the correct time zone and location and date time from user I am using this code to detect the location of the user:
 // Acquire a reference to the system Location Manager
         locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

         // Define a listener that responds to location updates
         locationListener = new LocationListener() {
             public void onLocationChanged(Location location) {
               // Called when a new location is found by the network location provider.
               longitude=location.getLongitude();
               latitude=location.getLatitude();

             }

             public void onStatusChanged(String provider, int status, Bundle extras) {}

             public void onProviderEnabled(String provider) {}

             public void onProviderDisabled(String provider) {}
           };

         //Or use LocationManager.GPS_PROVIDER
         String locationProvider = LocationManager.NETWORK_PROVIDER;

         // Register the listener with the Location Manager to receive location updates
         locationManager.requestLocationUpdates(locationProvider, 0, 0, locationListener);

         Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);

         if(lastKnownLocation!=null){
             longitude=lastKnownLocation.getLongitude();
             latitude=lastKnownLocation.getLatitude();

         }

and I am getting his time zone and datetime to add these in a url and get some info from the inetrnet but if the user has the checkboxes of automatic timezone, automatic date time unchecked I get incorrect data. So how can I fix this?
Do you think that I should mention this as a note on my app or what should I do?
thanks.

A: You can call out to a web service with the latitude and longitude to retrieve the time zone.
See: How to get a time zone from a location.


text:
Q: Typescript call function that may not exist at compile time I am trying to write a library that checks for a callback function and then calls it when it is ready. The idea being that you can include the JS asynchronously and then when it's loaded it will check for the callback and execute it.
I'm using typescript. The following JS works but wont compile in TS
if(typeof myFramework.ready === 'function') {
    myFramework.ready();
}

Then the developer using the library could do the following:
var myFramework = myFramework || {}; // As the framework wont exists
myFramework.ready = function(){//Execute developer's code};

However, using TypeScript I'm getting a type error: Property 'ready' does not exist on type 'typeof myFramework' - which is not a surprise. It does compile if I do the following:
interface Window {
    ready(): void;
}

if(typeof window.ready === 'function') {
    window.ready();
}

But that would mean adding more crud to the window object. And I imagine calling a global ready() method could well be a point of failure!
How would you go about achieving this?

Thanks to @james-crosswell - as I have classes in separate files the file that had the Ajax handling bit in looked something like:
module MyFramework {
    export interface IMyFramework {
        ready? : () => any;
    }

    export class HasLoaded implements IMyFramework {
        doReady = (framework: IMyFramework) => {
            if(typeof framework.ready === 'function') {
                framework.ready();
            }
        }
    }

    var newHost: HasLoaded = new HasLoaded();
    newHost.doReady(MyFramework);
}

I may be rethinking the logic that got me here but that's a separate issue!

A: myFramework.ready?.();

I think is the most compact and resembles C# syntax. It uses the optional chaining operator (?.)
================
Some comments on the other answers:
Why not this?
if (!!myFramework.ready) {
    myFramework.ready();
}

(the classic double exclamation mark construct -- the first exclamation mark transforms 'undefined' into true, the second one turns it back to false (hence converting 'undefined' to a valid false boolean)
Please note : ESLint doesn't like this construct:
myFramework.ready && myFramework.ready();

It says : "Expected an assignment or function call and instead saw an expression"

A: Since you're not certain a function instance will be provided plus once it is transpiled to JavaScript you definitely cannot be certain, you can check the type before invocation:
if (typeof method === 'function') {
    method();
}

Or you can use optional chaining, though this doesn't ensure a function reference was provided prior to invocation:
method?.();

Another non-TypeScript approach that also doesn't ensure a function reference was provided prior to invocation:
method && method();

A: Why not defining a function on your framework that a user will call on load? something like init(callback_to_developer_code);
But if you insist on doing it your way, you just have to define an optional property on your framework class interface like this:
interface IMyFramework {
  ready? : Function;
}

class MyFramework implements IMyFramework {
}

var myFramework : MyFramework;

if(typeof myFramework.ready !== 'undefined') {
    myFramework.ready();
}

A: You can certainly declare/export interfaces in modules in Typescript... but they're not going to be any use to users of your framework unless those users are also using Typescript (and have the tsd for your framework).
With that caveat then, the following variant on the answer from @gilamran above worked on the Typescript Playground:
module MyModule {
    export interface IMyFramework {
        ready? : () => any;
    }

    class MyFramework implements IMyFramework {
    }

    class YourFramework implements IMyFramework {
        ready = () => {
            alert("You're ready");
        }
    }

    export class Host {
        doReady = (framework: IMyFramework) => {
            if(typeof framework.ready !== 'undefined') {
                framework.ready();
            }
        }
    }

    var host: Host = new Host();
    host.doReady(new MyFramework());
    host.doReady(new YourFramework());

}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Mediawiki build a page from other pages content With Mediawiki I didn't manage to build a main page that would take information from a set of other pages from the wiki. Let's say each page have a status like "in progress", "done"... I would then like the main page to display a table of each page with its status.
How can I specify the status to each page so the main page would be able to grab this information and display the wanted table ?
Thanks a lot for your help.

A: You can use MediaWiki's (built-in) template system (quick intro).
You could create a template for the status of each page, containing just those words. You can include it then both in the main page, the subpage itself or any other place. To update the status, you'll need to edit the template.
Or you could use the pages themselves as templates. With the <onlyinclude> syntax you can tell the templating system to use only a single piece to tranclude in other pages, in here the status information. Including such a page will need the namespace in front, e.g. if it's in the default ("article") namespace without a prefix it would be {{:Subpage}}. This system is a bit more complicated, but you'd only need one edit to change both page and status. See also Help:Advanced templates.

A: Semantic MediaWiki offers very good support for attaching properties to pages and displaying them in various ways. You write something like [[status::in progress]] in the article, and then you can list all those statuses on the main page.
It is a bit of an overkill if the only thing you want is to show the status for a fixed list of pages, but offers a lot of flexibility (e.g. you can automatically order pages by status, or only list those with a given status or whatever).


text:
Q: Best Approach to Receive Email of a particular account under asp.net core We need to setup a mechanism of  receiving email of a particular Account of a Domain, Just like normal ticketing system reply emails.
Found some of the sources of how it could be achieved.
Either Go For Custom Solution
https://github.com/jstedfast/MailKit
https://joshwright.com/tips/tips-sending-receiving-email-in-csharp/
Send Grid Web Hooks
The Other Ready to go solution is Send Grid, but the problem with send grid is it monitors each and every email of domain, i can filter them at my end but still it  doesn't seem good approach keeping the security prospect in mind.
Here our Approach could be , can create a sub domain under the domain and receive those emails
I am currently using send grid for sending emails
Looking forward , what could the best, reliable and scalable approach and the pros and corns of it.

A: Simply write a C# program to receive emails of that particular box as follows:
var client = new POPClient();
client.Connect("pop.gmail.com", 995, true);
client.Authenticate("admin@bendytree.com", "YourPasswordHere");

var count = client.GetMessageCount();

// use a for loop to get the subject / message
Message message = client.GetMessage(count);

Console.WriteLine(message.Headers.Subject);

// message.Headers.From.Address;
// from address
// messagePart.BodyEncoding.GetString(messagePart.Body);
// message body

modify the above program so that, after receiving the email, the system

*

*inject the subject and message into a db record

*generate a ticket number

*reply to the sender that a ticket (# xxxxxx) has been issued

*follow up all the correspondence using this ticket (store all the correspondence in the db record)


text:
Q: ModuleNotFoundError: No module named 'fasttext' I have tried installing fasttext through conda using two channels:
conda install -c conda-forge fasttext
and
conda install -c conda-forge/label/cf201901 fasttext
as per (https://anaconda.org/conda-forge/fasttext).
I am using the following command to import: import fasttext
However, the import fails with the error:

ModuleNotFoundError                       Traceback (most recent call
  last)  in
  ----> 1 import fasttext
ModuleNotFoundError: No module named 'fasttext'

However, tried to import it in an older fashion import fastText, which failed.
Have tried it on python and python3, both of which fail.
I want to avoid installing it using pip and manage the packages using conda.
conda list shows that fasttext being installed. The output of which is shown below:
fasttext                  0.2.0                hfc679d8_1    conda-forge/label/cf201901
The output of python -c 'import sys; print(sys.path) is as below:
['', '/<dir>/<dir>/anaconda3/lib/python37.zip', '/<dir>/<dir>/anaconda3/lib/python3.7', '/<dir>/<dir>/anaconda3/lib/python3.7/lib-dynload', '/<dir>/<dir>/anaconda3/lib/python3.7/site-packages']

A: I used fastText in this way:
!git clone https://github.com/facebookresearch/fastText.git
!cd fastText
!pip install fastText
import fasttext.util
fasttext.util.download_model('en', if_exists='ignore')  # English
model = fasttext.load_model('cc.en.300.bin')

Note 1: Pay attention to uppercase letters.
Note 2: Here is the list of supported languages.


text:
Q: Wordpress links not working after domain update I changed my wordpress from domain1.com to domain2.com
Everything looks OK, until I click on an old post. It 404's.
If I change the root domain in the post to domain1.com/posts/post1 it renders correctly. I've used the search and replace script to search for domain1 but I see no results.
What can I do?

A: You may need to set your WP_HOME and WP_SITEURL variables in your wp-config.php.
define('WP_HOME','http://domain2.com');
define('WP_SITEURL','http://domain2.com');

WordPress stores these values in the database, but you can override them in your config file.
You may need to refresh your permalinks as well.
Settings -> Permalinks -> Save


text:
Q: Show that if $G$ is a non-trivial subgroup of $\Bbb R$ then either $G$ is dense in $\Bbb R$ or $G=l\Bbb Z$
Show that if $G$ is a non-trivial subgroup of $\Bbb R$ then either $G$ is dense in $\Bbb R$ or $G=l\Bbb  Z$, where $l=\inf\{x\in G:x>0\}$.

My try:
If $G=\Bbb Q$ then $\Bbb Q$ is dense in $\Bbb R$.
If $G=n\Bbb Z$ then $G$ is not dense but $G$ takes the form $G=l\Bbb Z$.
But how should I do the sum for any subgroup of $\Bbb R$?Please help.

A: First, note that $n G \subset G$ for every integer $n$.
If $G$ is cyclic, then $G = k \mathbb{Z}$ for some real nonzero $k$.  (Because there are no elements of finite order.)
If $G$ is not cyclic, then $$\inf_{\substack{x, y \in G\\ x \neq y}}|x-y| = 0,$$
(otherwise the positive infimum would be your $k$). Thus, if $\epsilon > 0$ and $r$ are real numbers, then $G$ has an element $g$ such that for some integer $n$ the integral multiple $ng$ (which is also in $G$) is within distance $\epsilon$ of $r$.


text:
Q: How to best execute a set of methods even if an exception happens In a current Java project we have code similar to the following example:
try {
    doSomeThing(anObject);
}
catch (SameException e) {
    // Do nothing or log, but don't abort current method.
}

try {
    doOtherThing(anObject);
}
catch (SameException e) {
    // Do nothing or log, but don't abort current method.
}

// ... some more calls to different method ...

try {
    finallyDoYetSomethingCompletelyDifferent(anObject);
}
catch (SameException e) {
    // Do nothing or log, but don't abort current method.
}

As you can see, several different method are called with the exact same object and for every call the same exception is caught and handled the same (or in a very similar) way. The exception is not re-thrown, but may only be logged and then discarded.
The only reason why there is a try-catch around every single method, is to always execute all of the methods, no matter if a previously executed method failed.
I don't like the above code at all. It takes up a lot of space, is very repetitive (especially the logging done in the catch-block; not presented here) and just looks bad.
I can think of some other ways to write this code, but don't like them very much, either. The following options came to my mind:
Loop-switch sequence / for-case paradigm
(See Wikipedia or The Daily WTF)
for (int i = 0; i <= 9; i++) {
    try {
        switch (i) {
            case 0:
                doSomeThing(anObject); break;
            case 1:
                doOtherSomeThing(anObject); break;
            // ...More cases...
            case 9:
                doYetSomethingCompletelyDifferent(anObject); break;
        }
    }
    catch (SameException e) {
        // Do nothing or log, but don't abort current method.
    }
}

This is obviously bad code, very error-prone and looks amateurish.
Reflection
Use reflection to get Method objects for the methods to call and store them in a list in the order they are supposed to be executed. Then iterate over this list and call the method using anObject as only parameter. The exception is handled inside of the loop.
I don't like this approach, as bugs (for example typos in the method names) only pop up during runtime and the Reflection API is somewhat chatty.
Functor
Create a Functor class like this:
private class Functor
{
    void doStuff(MyObject object) throws SameException;
}

Then create a list of Functor objects that call the methods. Like this:
List<Functor> functors = new ArrayList<Functor>();

functors.add(new Functor() {
    @Override
    public void execute(MyObject anObject) {
        doSomeThing(anObject);
    }
});

functors.add(new Functor() {
    @Override
    public void execute(MyObject anObject) {
        doOtherSomeThing(anObject);
    }
});

Later, iterate this list and call execute() on every Functor object.
I can summarize my feeling about this approach with two words: Code bloat.

As I don't really like all four approaches, I would like to discuss this problem here. What do you feel is the best approach? How did you solve similar problems in the past? Is there maybe a much simpler solution I missed completely?

A: I would advocate the refactoring approach (or "Why did we get here in the first place?"):
Consider why the individual methods can throw the exception after doing "stuff" with myObject and that exception can then be safely ignored. Since the exception escapes the method, myObject must be in an unknown state.
If it's safe to ignore the exception, surely it must be the wrong way to communicate that something went wrong in each method.
Instead, maybe it's each method that needs to do some logging on failure. If you don't use static loggers, you can pass a logger to each method.

A: The functor approach is the nicest one to my mind - it's just a shame that Java doesn't have a nicer way of representing closures or delegates. That's basically what you're really after, and in C# (and many other languages) it would be trivial.
You can cut down on the physical bloat somewhat by using something like:
Functor[] functors = new Functor[] {
    new Functor() { @Override public void execute(MyObject anObject) {
        doSomeThing(anObject);
    }},
    new Functor() { @Override public void execute(MyObject anObject) {
        doSomeOtherThing(anObject);
    }}
};

The whitespace collapsing here may well be against the style guide you're using, but I think it makes the code easier to actually read, in that you can see the meat more easily.
Better start lobbying for closures in Java 8 ;)

A: On the first look, I agree with PeterR: if it is safe to ignore the exception that easily, maybe that method should not be throwing an exception at all.
However, if you're sure that's exactly what you want, say, perhaps you're working with methods from a 3rd party library which insist on throwing specific exceptions, I would opt for the following approach:

*

*create an interface containing all the methods that can be called:

public interface XyzOperations {
     public void doSomething(Object anObject);
     public void doOtherThing(Object anObject);
     ...
     public void finallyDoYetSomethingCompletelyDifferent(Object anObject);

*create a default implementation class for those methods appropriate methods, possibly refactoring them from some other place:

    public class DefaultXyzOperations implements XyzOperations {
    ...
    }

*use a Java Proxy class to create a dynamic proxy on XyzOperations which would delegate all methods to DefaultXyzOperations, but, would have centralized exception handling in its InvocationHandler. I didn't compile the following, but it's a basic outline:

  XyzOperations xyz = (XyzOperations)Proxy.newProxyInstance(
        XyzOperations.class.getClassLoader(),
        new Class[] { XyzOperations.class },
        new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                 try {
                      method.invoke(new DefaultXyzOperations(), args);
                 }
                 catch(SameException e) {
                     // desired exception handling
                 }
            }
        });

*use that proxy instance from then on, simply calling the desired methods
Alternatively, you could use AspectJ or similar AOP solution to add around advice to all methods of XyzOperations and do the exception handling there.
Whether you would rather introduce a new dependency, or write proxies manually is up to your personal preference and the total amount of code where you need such behavior.

A: I agree with PeterR. I find it hard to believe that you really want to continue execution of something after an exception has been thrown. If you do, then something exceptional probably has not actually happened.
Put another way, exceptions should not be used for logging or flow control. They should only be used when something exceptional has happened that the code at the level where the exception was thrown cannot deal with.
As such, I would internalize the logging messages and remove the exceptions that are being thrown.
At a minimum, I think you need to go back and re-understand what the code is trying to do and what business value or rules are being implemented. As PeterR said, try to understand "why did we get here in the first place?" part of the code and what exactly the exceptions mean.

A: Are the methods you're calling under your control? If so, in this special case returning error codes (or objects) might yield to a better overall design than using exceptions:
handle(doSomething(anObject));
handle(doOtherThing(anObject));
// some more calls to different methods
handle(finallyDoYetSomethingCompletelyDifferent(anObject));

with
private void handle(ErrorCode errorCode) {
  // Do something about it
}

and
private ErrorCode doSomething(Object anObject) {
  // return ErrorCode describing the operation's outcome
}

This seems less verbose, although not DRY.
Alternatively, you use some AOP mechanism to intercept the calls to doSomething, doOtherThing and finallyDoYetSomethingCompletelyDifferent with an Around Advice that first handles and then discards the Exception. Combine that with RuntimeExceptions and a pointcut based on some nice descriptive annotation and you perfectly capture what seems to be some kind of hidden crosscutting concern.
I do confess that I like the Functor approach, tho.
EDIT: Just saw your comment on one of the answers. I would probably go with the AOP approach in that case.

A: Leaving aside the refactoring issue, AspectJ (or similar) seems the easiest way to transparently catch/report these exceptions. You should be able to configure such that it'll weave the try/catch around the method calls even if you add new ones (the code block above would, I suspect, be quite fragile in the face of someone modifying that code without fully understanding the rationale behind it)

A: If you are going the different code style route, I would stick with a simple:
try { doSomeThing(anObject); } catch (SameException e) { Log(e); }
try { doOtherThing(anObject); } catch (SameException e) { Log(e); }
// ... some more calls to different method ...

Update: I don't see how going with a syntax like the Functor's approach reduces any of the code involved. As mentioned by Jon, java doesn't support a simple syntax to reduce it further. If it were c# there are plenty of variations you can do, all around the fact that there isn't much extra syntax to compose methods like that i.e. an expression like actions.Add(() => doSomething(anObject));

A: Let me elaborate on the functor approach a bit more...
Depending on the complexity of your app, sometimes it is worth to move part of your business logic to a conf file, where it can be expressed more appropriately and briefly. This way you separate the technical details (the functor creation/invocation, exception handling) from the business logic - the definition of which methods and in what order are to be called.
In the simplest form it could be something like this:
mypackage.Action1
mypackage.Action2
...

where ActionX is a class implementing the Functor class (or interface).


text:
Q: will a manually updated stack in AWS that was created with cloudformation cause conflicts in the future? I am using cloudformation to deploy/update some stacks, including RDS. At the moment I successfully created my database and I want to update the port since I set the wrong one.
Reading the docs I encounter that by updating it via cloudformation, I must rename the stack in order to be able to update the port, therefore it will just create a new RDS instance with the new port and destroy the old one, this means I must create a backup first and later restore it.
I was reading that updating the port "manually" from the AWS console does not behave that way and no data loss should happen, so far I have not tried.
So, for example:
My deployed cloudformation is the following:
cloudformation template -> port 123
deployed stack -> port 123
I need to update it to port 234
then my cloudformation will still know the latest deploy happen to port 123
deployed stack -> 234 (the updated via aws console)
My question is the following: In the case, I am able to update the port via AWS Console, what will happen with the cloudformation template? should I update the template to have port 234 or I should leave it with port 123 so it wont try to make an update? (that would cause inconsistency on what I have at the template and what is really deployed but I wonder if would work)
https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-updating-stacks-update-behaviors.html#update-replacement
I dont have problems with all the vpc, security groups, rules, etc,  its basically just the port.
Any idea about this?

A: Modify resources manually outside in AWS console (or CLI, SDK) which were created by CFN  is a bad practice which results in a stack drift. The drift can lead to future issues; from docs:

Regardless, changes made outside of CloudFormation can complicate stack update or deletion operations.

Specifically to answer your question:

In the case, I am able to update the port via AWS Console, what will happen with the cloudformation template?

Nothing will happen per-se. CFN will not be aware by itself of any changes made to your RDS outside of CFN. But your stack will be considered as drifted, which, as AWS docs write, can lead to issues. Thus its better to avoid such situation.

should I update the template to have port 234 or I should leave it with port 123 so it wont try to make an update?

Yes, if you want to avoid drift. But updating port through CFN will lead to replacement of your db instance and data lost. So you must take all precautions on how to do it. Best would be to create some dummy RDS db, and do a test-run on it to understand the procedure and consequences of changing its port.


text:
Q: Azure FHIR search for resources with _include expression not supported I'm using following Azure For API(STU3) to play around. I'm trying to get other resources linked to DiagnosticReport resource with _include param.
https://xxx-xxx-xxxx.azurehealthcareapis.com/DiagnosticReport?_id=1234&_include=DiagnosticReport:encounter&_include=DiagnosticReport:result
But I'm getting following error : {
"resourceType": "OperationOutcome",
"id": "af40478f6fe6de47b8e0fc4f40e698ba",
"issue": [
{
"severity": "error",
"code": "forbidden",
"diagnostics": "Include expression is not supported."
}
]
}

A: Actually we just figured out that we are using CosmoDb in Azure FHIR which wont support Queries so the include revInclude search params wont work with CosmosDb instead they will work for SQL dbs.


text: Q: What is average force? When reading about how to calculate the force exerted from a liquid on the sides of a container it's said that the average force is equal to 1/2hA x pg what is the meaning of an average force here? Why the book didn't say force only?


text:
Q: Changing the width of Bootstrap popover I am designing a page using Bootstrap 3. I am trying to use a popover with placement: right on an input element. The new Bootstrap ensures that if you use form-control you basically have a full-width input element.
The HTML code looks something like this:

        Name:
        <input id="name" class="form-control" type="text"
                         data-toggle="popover" data-trigger="hover"
                         data-content="My popover content.My popover content.My popover content.My popover content." />

The popovers width is too low, in my opinion because their isn't any width left in the div.
I want the input form on the left side, and a wide popover on the right side.
Mostly, I'm looking for a solution where I don't have to override Bootstrap.
The attached JsFiddle. The second input option. Haven't used jsfiddle a lot so don't know, but try increasing the size of the output box to see results, on smaller screens wouldn't even see it.
http://jsfiddle.net/Rqx8T/

A: With the help of what @EML has described above regarding popover on modal windows and also the code shown by @2called-chaos, this is how I solved the problem.
I have an icon on the modal which when clicked should the popup
My HTML

My Script
$('[rel=popover]').popover({
    placement: 'bottom',
    html: 'true',
    container: '#name-of-modal-window .modal-body'
}).on("show.bs.popover", function () {
$(this).data("bs.popover").tip().css("max-width", "600px"); });

A:

    Name:
    <input id="name" class="form-control" type="text" />

Basically i put the popover code in the row div, instead of the input div. Solved the problem.

A: You can use attribute data-container="body" within popover

A: Here's the non-coffeescript way of doing it with hover:
$(".product-search-trigger").popover({
    trigger: "hover",
    container: "body",
    html: true,
    placement: "left"
  }).on("show.bs.popover", function() {
    return $(this).data("bs.popover").tip().css({
      maxWidth: "300px"
    });
  });
});

A: I had the same problem. Spent quite some time searching for an answer and found my own solution:
Add following text to the head:

A: No final solution here :/ Just some thoughts how to "cleanly" solve this problem...
Updated version (jQuery 1.11 + Bootstrap 3.1.1 + class="col-xs-" instead of class="col-md-") of your original JSFiddle: http://jsfiddle.net/tkrotoff/N99h7/
Now the same JSFiddle with your proposed solution: http://jsfiddle.net/tkrotoff/N99h7/8/
It does not work: the popover is positioned relative to the
 + imagine you have multiple inputs for the same
...
So if we want to keep the popover on the inputs (semantically better):

*

*.popover { position: fixed; }: but then each time you scroll the page, the popover will not follow the scroll

*.popover { width: 100%; }: not that good since you still depend on the parent width (i.e

*.popover-content { white-space: nowrap; }: good only if the text inside the popover is shorter than max-width
See http://jsfiddle.net/tkrotoff/N99h7/11/
Maybe, using very recent browsers, the new CSS width values can solve the problem, I didn't try.

A: container: 'body' normally does the trick (see JustAnil's answer above), but there's a problem if your popover is in a modal. The z-index places it behind the modal when the popover's attached to body. This seems to be related to BS2 issue 5014, but I'm getting it on 3.1.1. You're not meant to use a container of body, but if you fix the code to
   $('#fubar').popover({
   trigger : 'hover',
   html    : true,
   dataContainer : '.modal-body',
   ...etc });

then you fix the z-index problem, but the popover width is still wrong.
The only fix I can find is to use container: 'body' and to add some extra css:
.popover {
  max-width : 400px;
  z-index   : 1060;
}

Note that css solutions by themselves won't work.

A: I also needed a wider popover for a search text field. I came up with this Javascript solution (here in Coffee):
$(".product-search-trigger")
  .click(-> false) # cancel click on  tag
  .popover
    container: "body"
    html: true
    placement: "left"
    title: "Product search enter number or name"
  .on("show.bs.popover", -> $(this).data("bs.popover").tip().css(maxWidth: "600px"))

The workaround is in the last line. Before the popover is being displayed the max-width option is set to a custom value. You could also add a custom class to the tip element.

A: Increase width with CSS
You can use CSS to increase the width of your popover, like so:
/* The max width is dependant on the container (more info below) */
.popover{
    max-width: 100%; /* Max Width of the popover (depending on the container!) */
}

If this doesn't work, you probably want the solution below and alter your container element. (View the JSFiddle)

Twitter bootstrap Container
If that doesn't work, you probably need to specify the container:
// Contain the popover within the body NOT the element it was called in.
$('[data-toggle="popover"]').popover({
    container: 'body'
});

More Info

The popover is contained within the element that it is triggered in. In order to extend it "full width" - specify the container:
// Contain the popover within the body NOT the element it was called in.
$('[data-toggle="popover"]').popover({
    container: 'body'
});

JSFiddle
View the JSFiddle to try it out.
JSFiddle: http://jsfiddle.net/xp1369g4/

A: To change width you can use css
For fixed size wanted
.popover{
    width:200px;
    height:250px;
}

For max width wanted:
.popover{
    max-width:200px;
    height:250px;
}

jsfiddle: http://jsfiddle.net/Rqx8T/2/

A: One tested solution for Bootstrap 4 beta:
.popover {
        min-width: 30em !important;
    }

Together with the jQuery statement:
$('[data-toggle="popover"]').popover({
      container: 'body',
      trigger: 'focus',
      html: true,
      placement: 'top'
    })

Side-note, data-container="body" or container: "body" in either HTML or as an option to the popover({}) object didn't really do the trick [maybe the do work but only together with the CSS statement];
Also, remember that Bootstrap 4 beta relies on popper.js for its popover and tooltip positioning (prior to that it was tether.js)

A: You can adjust the width of the popover with methods indicated above, but the best thing to do is to define the width of the content before Bootstrap sees is and does its math.  For instance, I had a table, I defined it's width, then bootstrap built a popover to suit it.  (Sometimes Bootstrap has trouble determining the width, and you need to step in and hold its hand)

A: I used this(working fine) :
.popover{
   background-color:#b94a48;
   border:none;
   border-radius:unset;
   min-width:100px;
   width:100%;
   max-width:400px;
   overflow-wrap:break-word;
}

A:  Overview

        Your content

I end up by setting div "popover-content" width to the number I want. (other ids
 or class won't work.....) Good luck!
  #popover-content{
      width: 600px;

  }

A: To change the popover width you may override the template:
$('#name').popover({
    template: '

'
})

A: For people who prefer the JavaScript solution.
In Bootstrap 4 tip() became getTipElement() and it returns a no jQuery object. So in order to change the width of the popover in Bootstrap 4 you can use:
}).on("show.bs.popover", function() {
    $($(this).data("bs.popover").getTipElement()).css("max-width", "405px");
});

A: You can change the template of your popover. Either with the data-template-attribute or with the relevant part in the function that sets it up:

      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    clickme

A: On Bootstrap 4, you can easily review the template option, by overriding the max-width :
$('#myButton').popover({
    placement: 'bottom',
    html: true,
    trigger: 'click',
    template: '

'
});

This is a good solution if you have several popovers on page.

A: I found this solution for Bootstrap 5+ when I wanted to change the width of a specific popover. Adding a customClass worked for me:
Html:
<button class="btn btn-outline-secondary"  id="popover-help" data-bs-container="body" data-bs-toggle="popover" data-bs-placement="right" data-bs-content="Right popover">

</button>

 How to:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec condimentum ultricies elit, mattis egestas nisl suscipit ac. Duis ipsum augue, convallis sed nunc in, pellentesque luctus elit. Duis porttitor massa sed finibus rutrum. Nunc eu risus ultrices, volutpat leo eget, pulvinar eros. Donec rhoncus mattis sem, ac iaculis turpis semper non. Cras dapibus tristique risus, eu tincidunt elit condimentum fermentum. Nunc at dignissim ante, nec efficitur felis. Duis mauris magna, fermentum eu egestas vel, vehicula at est. Nullam dapibus nisi non purus pellentesque ultrices. Nulla pulvinar neque quis ipsum semper, a congue tortor aliquet. Suspendisse vulputate porttitor feugiat. Maecenas pretium porta mauris feugiat pellentesque. Integer tempus risus eu pretium consectetur.

Donec interdum, eros ac imperdiet pretium, magna risus laoreet tellus, in finibus justo sapien et lacus. Pellentesque placerat ligula at metus sollicitudin, et convallis nisi luctus. Vivamus non arcu vel ex pharetra auctor. Morbi efficitur sed turpis id finibus. Sed porttitor luctus quam sed laoreet. Nunc facilisis finibus aliquet. Maecenas pellentesque sem dui, sed blandit tortor placerat ut. Donec tempor ipsum in sem fermentum, vel vulputate magna egestas.

JS:

css:
.popover-large {
  max-width: 50%; /* Max Width of the popover (depending on the container!) */
}

A: you can also add the data-container="body" which should do the job :

        Name:
        <input id="name" class="form-control" type="text"
               data-toggle="popover" data-trigger="hover"
               data-container="body"
               data-content="My popover content.My popover content.My popover content.My popover content." />

A: For a typescript component:
@Component({
    selector: "your-component",
    templateUrl: "your-template.component.html",
    styles: [`
        :host >>> .popover {
          max-width: 100%;
        }
    `]
})

A: In Angular ng-bootstrap you can simply container="body" to the control that triggers popover (such as button or textbox). Then in your global styleing file (style.css or style.scss) file you must add .popover { max-width: 100% !important; }. After that, the content of the popover will automatically set to its content width.

A: In bootstrap 4 you can simply override default value of bootstrap variable $popover-max-width in your styles.scss file like so:
$popover-max-width: 300px;

@import "node_modules/bootstrap/scss/functions";
@import "node_modules/bootstrap/scss/variables";
@import "node_modules/bootstrap/scss/mixins";
@import "node_modules/bootstrap/scss/popover";

More on overriding bootstrap 4 defaults https://getbootstrap.com/docs/4.0/getting-started/theming/#variable-defaults

A: Try this:
var popover_size=($('.popover').css('width'));
var string=(popover_size).split('px');
alert("string"+string);
popover_size = ((parseInt(string[0])+350));
alert("ps"+popover_size);
$('.popover').css('width',parseInt(popover_size));


text:
Q: How come at a certain joint a truss is a zero force member and at another is isn't? I have a slight confusion regarding zero force members. I'm analyzing a structure and I started at joint E and found that truss GE has a force of 8.4 [kN]. However, if I analyzed it at joint G, I can see that it is a zero force member.
Now in the official answer to the question, the member is indeed zero force. However, it did raise for me the question of how come at a certain joint it can be analyzed a zero force one and at another it is not? Shouldn't it be zero force in both joints it is connected to - regardless of which one I start analyzing from? How can I avoid this confusion in the first place when analyzing struts?

A: Assuming the support at G is friction-less, there can be no horizontal force is the segment EG.  I would suggest that you recheck your calculations for point E.  Are these beams allowed to flex at the circled joints?


text:
Q: Access: Display hidden combobox column in textbox I have a combobox with a record source that brings 4 columns, but only shows the second column (Column Widths: 0";1";0";0"). I am trying to display the third column value selected in a text box, using the it's control Source property.

A: A combo's Column property uses zero-based index numbers, so the third column is Column(2).
Set the text box's Control Source property to ...
=[YourComboName].[Column](2)

A: If you're looking to show both column 2 and column 3
Column Count = 2
Column Width = 0;1;1;0

If you're looking to show column 3 instead of column 2
Column Width = 0;0;1;0


text:
Q: Confusion with Newton's Second Law : Position & Time Dependence of Force For a conservative force $\vec{F}(x,y)$ we have
$$\vec{F}(x,y) = - \vec{\nabla}\phi(x,y)$$
where $\phi(x,y)$ is a potential function for $\vec{F}(x,y)$.
Again, Newton's second law states that
$$ \vec{F}(t) = \frac{d \vec{P}(t)}{dt}$$
where $\vec{P}(t)$ is the momentum.
How these two equations are compatible; i.e, for a conservative force
$\vec{F}(x,y)$ how can we write the Newton's second law?
Edit
For a conservative force $\vec{F}(x,y)$ how can we write the Newton's second law?

A: What @lemon said is right. While $\bf F = -\nabla \phi\left({\bf r}\right)$ suggests that $\bf F$ depends on $\bf r$, it ultimately depends on time through ${\bf r} = {\bf r}\left(t\right)$. That is, ${\bf F} = -\nabla \phi\left({\bf r}\left(t\right)\right)$. So, there is no inconsistency in writing Newton's second law as (a dot represents a time derivative)
$$
{\bf F} = m \ddot{\bf r} = -\nabla \phi
$$
In fact, we don't have to restrict ourselves to a conservative force. $\bf F$ can depend on position, velocity, and time explicitly, ${\bf F} = {\bf F}\left({\bf r}\left(t\right),\dot{\bf r}\left(t\right),t\right)$, since you will end up with a perfectly consistent system of differential equations
$$
\begin{eqnarray}
\ddot{x} &=& F_x\left(x,y,z,\dot{x},\dot{y},\dot{z},t\right)/m \\
\ddot{y} &=& F_y\left(x,y,z,\dot{x},\dot{y},\dot{z},t\right)/m \\
\ddot{z} &=& F_z\left(x,y,z,\dot{x},\dot{y},\dot{z},t\right)/m \\
\end{eqnarray}
$$
To work a simple example, consider the potential energy
$$
\phi\left(x\right) = \frac{1}{2} k x^2.
$$
Then
$$
{\bf F} = -\nabla\left(\frac{1}{2} k x^2\right) = -k x \ \hat{\bf x} = m \left(\ddot{x} \ \hat{\bf x} + \ddot{y} \ \hat{\bf y} + \ddot{z} \ \hat{\bf z}\right),
$$
or
$$
\begin{eqnarray}
m \ddot{x} = -kx &\Rightarrow& x\left(t\right) = x\left(0\right) \cos\left(\omega t \right) + \frac{\dot{x}\left(0\right)}{\omega} \sin\left(\omega t\right), \omega = \sqrt{k/m} \\
m \ddot{y} = 0 &\Rightarrow& y\left(t\right) = {\dot y}\left(0\right) t + y\left(0\right)\\
m \ddot{z} = 0 &\Rightarrow& z\left(t\right) = {\dot z}\left(0\right) t + z\left(0\right)\\
\end{eqnarray}
$$


text:
Q: Flutter Print UTF-8 (Vietnamese) on bluetooth thermal printer using "blue_thermal_printer 1.1.3" I have a trouble, here is my code:
  if (isConnected) {
    final f = NumberFormat("#,###", "vi_VN");
    bluetooth.printCustom("CÔNG TY CỔ PHẦN", 3, 1);
  }

The printer worked properly but can not print UTF-8 Unicode characters:
The result: "C NG TY C  PH N"

I also found charset in plugin lib:
 Future<dynamic> printCustom(String message, int size, int align,
      {String? charset}) =>
  _channel.invokeMethod('printCustom', {
    'message': message,
    'size': size,
    'align': align,
    'charset': charset
  });

And replace charset by "UTF-8" but nothing change:
 Future<dynamic> printCustom(String message, int size, int align,
      {String? charset}) =>
  _channel.invokeMethod('printCustom', {
    'message': message,
    'size': size,
    'align': align,
    'charset': "UTF-8"
  });

I've tried with writeBytes but nothing change:
bluetooth.writeBytes(utf8.encode("CÔNG TY CỔ PHẦN ĐẦU TƯ XÂY DỰNG DƯƠNG KINH"));

Hope your help, thank you so much!

A: In method bluetooth.writeBytes you must write bytes(List) your charset.
Like this:
 if (isConnected ?? false) {
      bluetooth.writeBytes(Uint8List.fromList([27, 116, 0]));
      bluetooth.printCustom(
            "Example",
            2,
            1,
            charset: 'Cp437',
          );
      bluetooth.paperCut();
 }

In this  site you can look charsets and codes.
Look "ESC t n"
Read more about charsets.


text:
Q: Keycloak client credentials grant type with refresh token I have a client in keycloak (7.0.0) with given configuration - highlighted option "enables support for 'Client Credentials Grant'":

When I obtain a token for that client (POST /auth/realms/{my-realm}/protocol/openid-connect/token), I receive a following json response:
{
  "access_token": "xxx",
  "expires_in": 600,
  "refresh_expires_in": 1800,
  "refresh_token": "xxx",
  "token_type": "bearer",
  "not-before-policy": 1572415518,
  "session_state": "xxx",
  "scope": "xxx xxx"
}

I want to integrate it with OAuth2FeignRequestInterceptor, which by default ignores refresh token and creates a new session every access_token's expires_in seconds:
if (accessToken == null || accessToken.isExpired()) {
            try {
                // no refresh token usage here
                accessToken = acquireAccessToken();
            }
            ...
}

My questions are:

*

*Why do I receive a refresh token at all for client_credentials, which is a grant type for backend -> backend communication? The OAuth2 documentation link says explicitly that "A refresh token SHOULD NOT be included" for client_credentials grant type.

*Is it possible to configure keycloak that it won't send refresh tokens for clients with client_credentials grant type?

*If answer to 2. is 'NO' - do I have to implement my own feign request interceptor with refresh token support?

*If the client scope includes offline_access - the refresh_expires_in is 0 and, from what I understood, the refresh token is an offline token. Here is a link to keycloak mailing list where offline token usage is recommended by someone from keycloak's team - isn't it in conflict with OIDC specification for client_credentials grant type?

A: My answer is maybe a bit too late, but Keycloak recently added support for disabling refresh tokens in the case of client_credentials grants. This was implemented in version 12.0.0, which was released in December 2020.
Here is the part of the documentation pointing to that: https://www.keycloak.org/docs/12.0/release_notes/#other-improvements
Before this version, it was not possible to disable refresh tokens, and so you would have indeed to write your own version of OAuth2FeignRequestInterceptor that would either ignore the refresh token (and try to obtain a new access token), or use the refresh token to obtain a renewed access token. I would choose the first solution, as it closer from the OAUTH2 spec.

A:
My questions are:

*

*Why do I receive a refresh token at all for client_credentials, which is a grant type for backend -> backend communication? The OAuth2
documentation link says explicitly that "A refresh token SHOULD
NOT be included" for client_credentials grant type.

First, one needs to clarify the meaning of "SHOULD NOT" in that context. According to rfc2119:

  The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL
  NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED",  "MAY", and
  "OPTIONAL" in this document are to be interpreted as described in
  RFC 2119.

Note that the force of these words is modified by the requirement
level of the document in which they are used.

*

*MUST   This word, or the terms "REQUIRED" or "SHALL", mean that the    definition is an absolute requirement of the specification.

*MUST NOT   This phrase, or the phrase "SHALL NOT", mean that the    definition is an absolute prohibition of the specification.

*SHOULD   This word, or the adjective "RECOMMENDED", mean that there    may exist valid reasons in particular circumstances to ignore a particular item, but the full implications must be understood and carefully weighed before choosing a different course.

*SHOULD NOT   This phrase, or the phrase "NOT RECOMMENDED" mean that there may exist valid reasons in particular circumstances when the particular behavior is acceptable or even useful, but the full  implications should be understood and the case carefully weighed before implementing any behavior described with this label.

As you can read, "SHOULD NOT" does not mean that the specification prohibits it but rather that it does not recommend it.

*Is it possible to configure keycloak that it won't send refresh tokens for clients with client_credentials grant type?

As first mentioned in the answer provided by @Clement Petit; Keycloak v12 introduced:

Support for OAuth2 Client Credentials grant without refresh token and without user session.

That option can be found in each client configuration under the section "OpenID Connect Compatibility Modes" as shown below:

*If the client scope includes offline_access - the refresh_expires_in is 0 and, from what I understood, the refresh
token is an offline token. Here is a link to keycloak mailing
list where offline token usage is recommended by someone from
keycloak's team - isn't it in conflict with OIDC specification for
client_credentials grant type?

As you have seen, the specification does not explicitly prohibits it. Notwithstanding, conceptually, it does not make sense to have a refresh token when using the client credentials flow since the backend already has the client secret stored locally anyway, and can simply acquire a new access token without the hassle of either having to store user credentials or request the user to enter them again.
From the original poster from the thread of the keycloak mailing list that you have posted:

Hi,

Currently, every time a confidential client tries to get a new access token
from the token endpoint a new session is created on the server. This can
lead to multiple active sessions for a single client/service account when
doing multiple requests to token endpoint.
To avoid that the client should store the access token/refresh token and
use a refresh token when appropriate in case the access token has expired.
That is fine.

one can infer that the reason why Keycloak had (at that time) the refresh token available for the client credential flows was to be used as a workaround to a technical issue with their client credential flow implementation (i.e., creating too many sessions).


text:
Q: When decrypting an encrypted string in c#, only the first character is returned I have an encryption algorithm and decryption algorithm used for a login page. When encrypting, everything seems fine and seems to encrypt everything as expected, but when the encrypted password is put back through my decryption algorithm, only the first character is returned.
Example
Here is the code:
public string encrypt(string key, string data)
        {
            byte[] clearBytes = Encoding.Unicode.GetBytes(data);
            byte[] iv = new byte[16];
            using (Aes encryptor = Aes.Create())
            {
                encryptor.Key = Encoding.UTF8.GetBytes(key);
                encryptor.IV = iv;
                encryptor.Padding = PaddingMode.PKCS7;

                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(clearBytes, 0, clearBytes.Length);
                        cs.Close();

                    }
                    data = Convert.ToBase64String(ms.ToArray());
                }

            }
            return data;
        }

        public static string decryptData(string key, string data)
        {
            byte[] iv = new byte[16];
            byte[] clearBytes = Convert.FromBase64String(data);

            using (Aes decrpytor = Aes.Create())
            {
                decrpytor.Key = Encoding.UTF8.GetBytes(key);
                decrpytor.IV = iv;
                ICryptoTransform decryptor = decrpytor.CreateDecryptor(decrpytor.Key, decrpytor.IV);
                decrpytor.Padding = PaddingMode.PKCS7;
                using (MemoryStream ms = new MemoryStream(clearBytes))
                {
                    using (CryptoStream cs = new CryptoStream((Stream)ms, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader sr = new StreamReader((Stream)cs))
                        {

                            return sr.ReadToEnd();

                        }
                    }
                }
            }
        }
        public void button1_Click(object sender, EventArgs e)
        {
            var key = "b14ca5898a4e4133bbce2ea2315a1916";
            var str = passWord.Text;
            var encryptedPassword = encrypt(key, str);
            var decrpted = decryptData(key, encryptedPassword);
            passwordTest.Text = encryptedPassword;
            decryptedtest.Text = decrpted;

        }

the last 2 lines are purely for testing to see what they output.
Any help is appreciated.


text:
Q: How would I identify a gap in a set of curve data, and get its value? I have  a set of 2-D data (x,y) and it produces a set of curves,
and sometimes the set of curves do not overlap, and there is a
distinct separation between the groups of curves, how would I
identify and get this separation?
Here is some sample data
and its plot

0.0000   -0.4270
0.1000   -0.4239
0.2000   -0.4141
0.3000   -0.3979
0.4000   -0.3753
0.5000   -0.3464
0.6000   -0.3113
0.7000   -0.2705
0.8000   -0.2244
0.9000   -0.1732
1.0000   -0.1174
1.0000   -0.4270
0.9000   -0.0578
0.8000    0.0050
0.7000    0.0698
0.6000    0.1361
0.5000    0.2026
0.4000    0.2685
0.3000    0.3327
0.2000    0.3920
0.1000    0.4396
0.0000    0.4597
0.0000    0.4597
0.1000    0.4463
0.2000    0.4160
0.3000    0.3812
0.4000    0.3474
0.5000    0.3172
0.6000    0.2917
0.7000    0.2715
0.8000    0.2569
0.9000    0.2480
1.0000    0.2450
1.0000    0.4597
1.0000    0.4597
1.0000    0.2450
0.9000    0.2480
0.8000    0.2569
0.7000    0.2715
0.6000    0.2917
0.5000    0.3172
0.4000    0.3474
0.3000    0.3812
0.2000    0.4160
0.1000    0.4463
0.0000    0.4597
0.0000    0.6484
0.1000    0.6402
0.2000    0.6191
0.3000    0.5918
0.4000    0.5639
0.5000    0.5389
0.6000    0.5186
0.7000    0.5046
0.8000    0.4973
0.9000    0.4975
1.0000    0.5063
1.0000    0.6484
1.0000    0.6484
1.0000    0.5063
0.9000    0.5239
0.8000    0.5508
0.7000    0.5874
0.6000    0.6333
0.5000    0.6876
0.4000    0.7450
0.3000    0.7622
0.2000    0.7078
0.1000    0.6657
0.0000    0.6484
0.0000    0.6484
0.1000    0.6657
0.2000    0.7078
0.3000    0.7622
0.4000    0.8222
0.5000    0.8864
0.6000    0.9527
0.7000    1.0206
0.8000    1.0899
0.9000    1.1586
1.0000    1.2059
1.0000    0.6484
1.0000    0.7146
1.0000    1.2059
0.9000    1.1586
0.8000    1.0899
0.7000    1.0206
0.6000    0.9527
0.5000    0.8864
0.4000    0.8222
0.3000    0.7869
0.2000    0.7731
0.1000    0.7338
0.0000    0.7146

This for the curious, is a band dispersions diagram, from solid state physics.


text:
Q: Delock Adapter USB 3.0 > HDMI I am trying to connect my laptop (Ubuntu 16.04) to extra monitor with this adapter.
Laptop has USB 3.0 . and when i insert adapter into USB, it gets recognized in terminal with lsusb.
damba@damba-Inspiron-5559:~$ lsusb
Bus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 001 Device 007: ID 8087:07dc Intel Corp.
Bus 001 Device 006: ID 0bda:0129 Realtek Semiconductor Corp. RTS5129 Card Reader Controller
Bus 001 Device 005: ID 0c45:6712 Microdia
Bus 001 Device 014: ID 046d:c534 Logitech, Inc. Unifying Receiver
Bus 001 Device 013: ID 0d8c:000c C-Media Electronics, Inc. Audio Adapter
Bus 001 Device 012: ID 1d5c:2000
Bus 001 Device 011: ID 1a40:0101 Terminus Technology Inc. Hub
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

Can someone help?
lsusb
Bus 002 Device 007: ID 1d5c:2000
Bus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.O root hub
Bus 001 Device 005: ID 8087:07dc Intel Carp.
Bus 001 Device 004: ID 0bda:0129 Realtek Semiconductor Carp. RTS5129 Card Reader Controller
Bus 001 Device 003: ID 0c45:6712 Microdia
Bus 001 Device 023: ID 046d:c534 Logitech, Inc. Unifying Receiver
Bus 001 Device 025: ID 0d8c:000c C-Media Electronics, Inc. Audio Adapter
Bus 001 Device 024: ID 1a40:0101 Terminus Technology Inc. Hub
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.O root hub

A: I was unable to locate a Linux compatible driver for your device. Until some one far more motivated than I writes a driver or support for this device into the kernel, it appears that if you want to use it you are stuck with using the Operating Systems that support it which according to the product link you provided are:
• Windows 7 32-bit
• Windows 7 64-bit
• Windows 8.1 32-bit
• Windows 8.1 64-bit
• Windows 10 32-bit
• Windows 10 64-bit
Note: NDISwrapper is known to make some drivers work with the Linux kernel, sadly to the best of my knowledge it requires drivers that comply to the NDIS 5.0 spec which went out with Windows XP I believe, so that isn't likely to  help you with this particular device.


text:
Q: How to find common text form 2 column containing string vlaues? I have two columns 'Title' that contains data like 'What is Physics ?' and another column 'Content' that contains data like 'Physics is a study of....'.
I want the common text of both like ['is','Physics'].
This has to be done for all the rows of data. How can I achieve that using R ?
Regards,

A: I think you want something like the following:
df <- data.frame(col1=c('what is physics?', 'set cover is NP hard', 'abstract algebra'),
                 col2=c('Physics is the study of...', 'Example of an NP complete problem is 3-SAT', 'linear algebra'),
                 stringsAsFactors = FALSE)
#       col1                col2
# 1     what is physics?    Physics is the study of...
# 2 set cover is NP hard    Example of an NP complete problem is 3-SAT
# 3     abstract algebra    linear algebra

apply(df, 1, function(x) intersect(tolower(unlist(strsplit(gsub('[^a-zA-Z\\s]+', ' ', x[1]), split=' '))),
                               tolower(unlist(strsplit(gsub('[^a-zA-Z\\s]+', ' ', x[2]), split=' ')))))

#[[1]]
#[1] "is"      "physics"

#[[2]]
#[1] "is" "np"

#[[3]]
#[1] "algebra"


text:
Q: Converting table layout to div equivalent I currently have a table:

            FAQ Categories

            some content goes here

With CSS:
#blockcontainer {width:100%;}
#blockcontainer .topleft{background:url(../../Content/Images/top-left.png) no-   repeat;width:8px;height:52px;}
#blockcontainer .topcenter{background:url(../../Content/Images/top-center.png) repeat-x;height:52px;color:#fff;padding-left:5px;font-size: large;text-align: left;}
#blockcontainer .topright{background:url(../../Content/Images/top-right.png) no-repeat;width:8px;height:52px;}
#blockcontainer .topleftgrey{background:url(../../Content/Images/top-leftgrey.png) no-repeat;width:8px;height:52px;text-align: left;}
#blockcontainer .topcentergrey{background:url(../../Content/Images/top-centergrey.png) repeat-x;height:52px;padding-left:5px;font-size:large;text-align: left;}
#blockcontainer .toprightgrey{background:url(../../Content/Images/top-rightgrey.png) no-repeat;width:8px;height:52px;text-align: left;}
#blockcontainer .middleleft{background:url(../../Content/Images/middle-left.png) repeat-y;width:8px;}
#blockcontainer .middlecenter{background-color:#fff;padding:5px;}
#blockcontainer .middleright{background:url(../../Content/Images/middle-right.png) repeat-y;width:8px;}
#blockcontainer .bottomleft{background:url(../../Content/Images/bottom-left.png) no-repeat;width:8px;height:8px;}
#blockcontainer .bottomcenter{background:url(../../Content/Images/bottom-center.png) repeat-x;height:8px;}
#blockcontainer .bottomright{background:url(../../Content/Images/bottom-right.png) no-repeat;width:8px;height:8px;}

That looks like this:

The problem I am having is that there are multiple tables like this on one page (this table acts as my content containers), and due to the way that tables load in a browser, the page loads terribly slow.
I know converting this to a div will make the world of difference, but I am unable to convert this table structure to an equivalent div stricture.
Sorry for posting a "do it for me" question, but multiple attempts at this has already left a piece of my keyboard on my wall. :)
Here is the jsfiddle example

A: Aniket beat me to it, however I believe mine is a more accurate CSS rendition of your current image and table-based code:
http://jsfiddle.net/purmou/YyHKf/
It uses CSS3 box-shadow (along with the browser prefixed versions for compatibility) and gradient backgrounds (which doesn't work in Opera only, but that's an easy addition).
HTML:

        FAQ Categories

content

5

CSS:
.container {
    -moz-border-radius:5px;
    -webkit-border-radius:5px;
    border-radius:5px;
    -moz-box-shadow: 0 0 5px #888;
    -webkit-box-shadow: 0 0 5px#888;
    box-shadow: 0 0 5px #888;
    background: #fff;
    width:100%;
}

.header {
    padding:5px;
    background:#eeeeee;
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#eeeeee');
    background: -webkit-gradient(linear, left top, left bottom, from(#fff), to(#eee));
    background: -moz-linear-gradient(top,  #fff,  #eee);
  height:40px;
    -moz-border-radius-topright:5px;
    -webkit-border-top-right-radius:5px;
    border-top-right-radius:5px;
    -moz-border-radius-topleft:5px;
    -webkit-border-top-left-radius:5px;
    border-top-left-radius:5px;
    border-bottom:1px #888 solid;
    -moz-box-shadow: 0 1px 3px #888;
    -webkit-box-shadow: 0 1px 3px#888;
    box-shadow: 0 1px 3px #888;
}

.content {
    padding:0 5px 10px 5px;
    margin-top:3px;
    background-color:#ffffff;
    -moz-border-radius-bottomright:5px;
    -webkit-border-bottom-right-radius:5px;
    border-bottom-right-radius:5px;
    -moz-border-radius-bottomleft:5px;
    -webkit-border-bottom-left-radius:5px;
    border-bottom-left-radius:5px;
}

.content div {
    padding:5px 5px 5px 5px;
    border-bottom:1px #ccc solid;
}

.content .right {
    float:right;
    border:none;
}

A: The below uses floated div's and negative margins. I also wrapped the content with the middleleft and middleright elements so they would inherit the height of the content itself and stretch the borders to the appropriate height.
Note, due to the negative margins, you'll probably want to look at the margins put on the middlecenter element.
.blockcontainer .topleft {
    background: url(http://www.effortshare.com/Content/Images/top-left.png) no-repeat;
    width: 8px;
    height: 52px;
    float: left;
    margin-left: -8px;
}
.blockcontainer .topcenter {
    background: url(http://www.effortshare.com/Content/Images/top-center.png) repeat-x;
    color: #fff;
    font-size: large;
    text-align: left;
}
.blockcontainer .topright {
    background: url(http://www.effortshare.com/Content/Images/top-right.png) no-repeat;
    width: 8px;
    height: 52px;
    float: right;
    margin-right: -8px;
}
.blockcontainer .topleftgrey {
    background: url(http://www.effortshare.com/Content/Images/top-leftgrey.png) no-repeat;
    width: 8px;
    height: 52px;
    text-align: left;
    float: left;
    margin-left: -8px;
}
.blockcontainer .topcentergrey {
    background: url(http://www.effortshare.com/Content/Images/top-centergrey.png) repeat-x;
    height: 52px;
    font-size: large;
    text-align: left;
}
.blockcontainer .toprightgrey {
    background:url(http://www.effortshare.com/Content/Images/top-rightgrey.png) no-repeat;
    width: 8px;
    height: 52px;
    text-align: left;
    float: right;
    margin-right: -8px;
}
.blockcontainer .middleleft {
    background: url(http://www.effortshare.com/Content/Images/middle-left.png) repeat-y;
    margin-left: -8px;
    overflow: visible;
}
.blockcontainer .middlecenter {
    padding: 5px 8px 5px 8px;
}
.blockcontainer .middleright {
    background: url(http://www.effortshare.com/Content/Images/middle-right.png) repeat-y;
    background-position: right top;
    margin-right: -8px;
    overflow: visible;
}
.blockcontainer .bottomleft {
    background: url(http://www.effortshare.com/Content/Images/bottom-left.png) no-repeat;
    width: 8px;
    height: 8px;
    float: left;
    margin-left: -8px;
}
.blockcontainer .bottomcenter {
    background: url(http://www.effortshare.com/Content/Images/bottom-center.png) repeat-x;
    height: 8px;
}
.blockcontainer .bottomright {
    background:url(http://www.effortshare.com/Content/Images/bottom-right.png) no-repeat;
    width: 8px;
    height: 8px;
    float: right;
    margin-right: -8px;
}

        This is a title

This is left

Right

This is left

Right

This is left

Right

http://jsfiddle.net/userdude/FtCLJ/4/

A: Check this fiddle -
http://jsfiddle.net/aniketpant/ePARN/
I have removed the use of all images, and it's pure CSS.
HTML

FAQ Categories

Some content goes here

Some content goes here

Some content goes here

Some content goes here

CSS
#blockcontainer {
    border: 2px solid #ddd;
    -webkit-border-radius: 10px;
    -moz-border-radius: 10px;
    border-radius: 10px;
}

#blockcontainer dl dt.title {
    font-size: 1.25em;
    border-bottom: 2px solid #ddd;
    background: -moz-linear-gradient(top, #eee, #ddd, #fff); /* FF 3.6+ */
    background: -ms-linear-gradient(top, #eee, #ddd, #fff); /* IE10 */
    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #eee), color-stop(50%, #ddd), color-stop(100%, #fff)); /* Safari 4+, Chrome 2+ */
    background: -webkit-linear-gradient(top, #eee, #ddd, #fff); /* Safari 5.1+, Chrome 10+ */
    background: -o-linear-gradient(top, #eee, #ddd, #fff); /* Opera 11.10 */
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ddd', endColorstr='#ffffff'); /* IE6 & IE7 */
    -ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr='#ddd', endColorstr='#ffffff')"; /* IE8+ */
    background: linear-gradient(top, #eee, #ddd, #fff); /* the standard */
}

#blockcontainer dl {
}

#blockcontainer dl dt {
    padding: 5px;
}

A: Ideally you should be using Ul and Li (to be more semantic) for navigation not table tags. Using table will just screw up the entire layout.
If I were you, I would opt for 960 gs and choose grid_1

Home

FaQ

some here

others here

and my css would say:
#sidenavi ul li
{
#background ......
}

I hope it works out for u.
The code would be shorter, efficient and as per semantics :)


text:
Q: Exception when sending an email with play iam getting the following error while sending an email from playframework
sample code from Mail Notifier
        setFrom("xyz@xyz.com");
        setSubject("Relax 500 Error on production machine");
        addRecipient("xyz@xyz.com");
        send("errors/error1",errorContent);

if i use error1.txt everything is working fine iam able to send email .
But when ever i change the template to error1.html play is unable to send text/html messages for some reason which i could not able to figure it out.
Below is the exception :
Caused by: javax.mail.MessagingException: IOException while sending message;
  nested exception is:
        java.io.IOException: "text/html" DataContentHandler requires String obje
ct, was given object of type class javax.mail.internet.MimeMultipart
        at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:625)
        at javax.mail.Transport.send0(Transport.java:169)
        at javax.mail.Transport.send(Transport.java:98)
        at org.apache.commons.mail.Email.sendMimeMessage(Email.java:1232)
        ... 8 more
Caused by: java.io.IOException: "text/html" DataContentHandler requires String o
bject, was given object of type class javax.mail.internet.MimeMultipart
        at com.sun.mail.handlers.text_plain.writeTo(text_plain.java:121)
        at javax.activation.ObjectDataContentHandler.writeTo(DataHandler.java:86
9)
        at javax.activation.DataHandler.writeTo(DataHandler.java:302)
        at javax.mail.internet.MimeBodyPart.writeTo(MimeBodyPart.java:1350)
        at javax.mail.internet.MimeMessage.writeTo(MimeMessage.java:1683)
        at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:585)
        ... 11 more

A: Which SMTP server are you using?
I had a similar problem when using a Lotus Notes mailserver - and only in this case.  Every other mail server was fine.
The (somewhat annoying) solution was to copy Play's Mailer#send(Object... args) method and change
HtmlEmail htmlEmail = new HtmlEmail();
htmlEmail.setHtmlMsg(bodyHtml);
if (!StringUtils.isEmpty(bodyText)) {
    htmlEmail.setTextMsg(bodyText);
}
email = htmlEmail;

to
public static Future<Boolean> sendMail(Map<String, Object> args) {
    ...
    HtmlEmail htmlEmail = new HtmlEmail();
    htmlEmail.setHtmlMsg(bodyHtml);
    htmlEmail.setContent(bodyHtml, "text/html"); // !! add this line!!
    if (!StringUtils.isEmpty(bodyText)) {
        htmlEmail.setTextMsg(bodyText);
    }
    email = htmlEmail;
    ...
}

Explicitly setting the content type of the htmlEmail object fixed the problem.  The side-effect of this was that we have to pass in a map of arguments that are explicitly defined in the mail-sending methods, e.g.
public static void sendTestMail(String to,
                                String subject,
                                String name) {
    addRecipient(to);
    setSubject(subject);

    Map<String, Object> args = new HashMap<String, Object>();
    args.put("name", name);

    sendMail(args);
}

In your custom sendMail method, you'll also need to change the code that binds the arguments, from
for (Object o : args) {
    List<String> names = LocalVariablesNamesTracer.getAllLocalVariableNames(o);
    for (String name : names) {
        templateHtmlBinding.put(name, o);
        templateTextBinding.put(name, o);
    }
}

to
for (String key : args.keySet()) {
    templateHtmlBinding.put(key,
                            args.get(key));
    templateTextBinding.put(key,
                            args.get(key));
}

Very annoying, and very verbose, but it works.


text:
Q: Display product price in two currencies at the same time? How do I modify PrestaShop 1.5 to display product prices in two currencies at the same time (ie. base currenct and visitor's currency on products listed in product & categories pages):

I think I should be modifying ProductController.php and product.tpl. Is this correct?
Below is one solution for the product page that I find on a forum, but it is for PrestaShop 1.4x:

*

*Override ProductController.php in /controllers/ProductController.php
<?php
class ProductController extends ProductControllerCore{
    public function displayContent() {
        global $currency;
        $second_currency = 'USD';
        $productPriceWithTax = Product::getPriceStatic($this->product->id, true, NULL, 6);
        if (Product::$_taxCalculationMethod == PS_TAX_INC) {
            $productPriceWithTax = Tools::ps_round($productPriceWithTax, 2);
        }
        $productPriceWithoutEcoTax = (float)($productPriceWithTax - $this->product->ecotax);

        $current_currency = $currency->iso_code;
        $default_currency = Currency::getDefaultCurrency()->iso_code;
        $currency_array   = Currency::getCurrencies($object = false, $active = 1);

        if ($current_currency == $default_currency) {
            foreach ($currency_array as $arr) {
                if ((string)$arr['iso_code'] == $second_currency) {
                    $second_currency_price = Tools::ps_round($productPriceWithoutEcoTax * (float)$arr['conversion_rate'], 2);
                }
            }
        }

        self::$smarty->assign('second_currency_price', $second_currency_price . ' ' . $second_currency);
        parent::displayContent();
    }
}

*Modify product.tpl:
{if $priceDisplay >= 0 && $priceDisplay <= 2}
    {convertPrice price=$productPrice}

to
{if $priceDisplay >= 0 && $priceDisplay <= 2}
    {$second_currency_price} /
    {convertPrice price=$productPrice}

In above example USD is the second currency ($second_currency='USD'). I was wondering if it would be possible to modify this code for PrestaShop 1.5, which has changed significantly since 1.4x.

A: You have to loop this array which contains all the currencies you manage: {$currencies}
{foreach from=$currencies item=c}{$c.name}{/foreach}

The default currency is in: {$id_currency_cookie}
If I remember, you have to write this in product.tpl.
I don't know how to display the correct price for your currency. Tell us if you find.


text:
Q: When declaratively creating a dojox.grid.DataGrid - how to specify nested data in the field attribute? I'm creating a dojox.grid.DataGrid in dojo 1.6 with the following notation:

      ID
      Name
      Telephone
      Birthday

The Data looks something like this:
[{
'id':1,
'contact':{
  'name':'Doh',
  'firstname':'John',
  'tel':'123-123456',
  'birthdate':{
    'javaClass':'java.sql.Timestamp',
    'time':1234567893434}}
}]

ID is rendered corectly, but all the others render as "...".
I have tried to specify a formatter, setting the base Object "contact" as
the FIELD and then returning FIELD.name for example.
This works in so far that the correct Value is displayed, but the Sorting then
uses the base object.
I think there might be a way to push this even further, overriding the sorting
of the table, but I would like to keep this as simple as possible.
Also I wish to prevent performance issues from popping up.
Any Ideas?

A: I have found out that there is an attribute for the DataGrid row definition called "get".
"get" specifies the name of a function that returnes the value to be displayed in the DataGrid column.
Theoretically this should solve my Problem.
The get-function is to be implemented in the following way:
Grid Definition:

      ID
      Name
      Telephone
      Birthday

Callback Function (example):
myGrid.getContactName = function(colIndex,item){
  return item.name;
};

I can not tell at the Moment if this implementation is correct, since
the item parameter is always null in my application.
This could be due to the use of the new Store API (store.Memory) instead of the ItemFileReadStore, but I have not been successfull in solving this puzzle yet.
Also I was not able to test Gird sorting with this new approach, so I will not flag
this sollution as resolved yet.
update
myGrid.getContactName = function(colIndex,record){
  if(record)return record.contact.name;
  else return null;
};

Once I averted the null case it worked fine this way.
However client sort of the Grid doesn't seem to access through the get function but uses the field directly. This prevents correct sorting on nested fields.
update
I finally got a sollution for my problems:
The first problem : specifying nested data for the DataGrid fields was solved allready using the get-function to dive into the arrays substructure. (that is explained above)
Sorting however is still dependent on the field attribute.
If the field attribute contains the name of an array this column will not sort correctly.
I had to modify a few dojo classes to accomodate for that. I will later put this in a more modular form, but here is the raw result for now:
First I needed to allow the definition of an addtional comparator callback in the Grid Definition.
For that I have added some code to the dojox.grid.cells._base
dgc._Base.markupFactory = function(node, cellDef){
var d = dojo;
...
var comparator = d.trim(d.attr(node,"comparator")||"");
if(comparator){
  cellDef.comparator = dojo.getObject(comparator);
}
...
}

Next the DataGrid needs to give this new parameter to the query to do the sorting.
This is done in the dojox.grid.DataGrid. "c" is the Cell I modified above.
getSortProps:function(){
...
return[{attribute:c.field,descending:desc,comparator:c.comparator}];
}

Finally I need to change the sorting itself which is defined in dojo.store.util.SimpleQueryEngine.
SimpleQueryEngine is the default Engine for the MemoryStore (dojo.store.Memory).
function execute(array){
    // execute the whole query, first we filter
    var results = dojo.filter(array, query);
    // next we sort
    if(options && options.sort){
        results.sort(function(a, b){
            for(var sort, i=0; sort = options.sort[i]; i++){
                var aValue = a[sort.attribute];
                var bValue = b[sort.attribute];
                if (aValue != bValue) {
                    // changed Part start
                    if(options.sort[i].comparator){
                        return !!sort.descending == options.sort[i].comparator(aValue,bValue) ? -1 : 1;
                    }
                    else{
                        return !!sort.descending == aValue > bValue ? -1 : 1;
                    }
                    // changed Part end
                }
            }
            return 0;
        });
    }
    ...
    return results;
}

Now I can add comparators to each column and define them where I want to:
Declarative DataGrid Setup:
...
Name
...

Javascript definition of the comparator function (a and b are "myArray" objects):
compareNames = function(a,b){
  return a.name > b.name;
}

Javascript definition of the getter function (record is the whole row and contains the "myArray" object):
getNamesFromArray= function(idx,record){
  return record.myArray.name;
}


text:
Q: Multiplications with doubles c++ I'm new to C++ and I wanted to code the mandelbrot set in it to get some practise and compare the speed to Python. My function to iterate to see if the complex number blows up to infinity looks like this:
int iterate(double ir, double ii, int iterations){
    double sr = 0.0;
    double si = 0.0;
    unsigned int steps = 0;
    while(sr < 2.0 && sr > -2.0 && si < 2.0 && si > -2.0 && steps < iterations){
        sr = sr*sr-si*si+ir;
        si = si*sr*2 + ii;
        steps ++;
    }
    return steps;
}

I compared the outputs to my python code and realised the the line where it updates the imaginary part doesn't work properly. The *2 doesn't work properly. Insted of doubling it makes the results negative. For example when I insert the number 0.2 + 1i it does the following:
0.2 + 1i,  -0.76 - 0.52i, 0.5072 + 0.472512i, 0.233984 + 1.22112i, -1.23639 - 2.01956i
What it should do instead (what I got from my Python programm) is:
0.2+ 1i, -0.76 + 1.4i, -1.1823999999999997 - 1.1279999999999997i, 0.3256857599999999 + 3.6674943999999985i
My guess is that it writes to the sign instead of either doubling the mantissa or increasing the exponent. I can't just make it unsigned because it must also be able to store negative values. What can you do about it? Thanks for your awnsers!

A: I would write your function like this, using std::complex:
template <class T>
std::size_t iterate(std::complex<T> c, std::size_t max_iterations) {
    std::complex<T> z = 0;
    std::size_t steps = 0;

    while (std::norm(z) <= 4 && steps < max_iterations) {
        z = z * z + c;
        ++steps;
    }

    return steps;
}

Then you can call your function like this:
using std::complex_literals::operator""i;
std::complex<double> c = 0.2 + 1i; // or c(0.2, 1);
const auto steps = iterate(c, 256);

The reason you should use std::norm(z) <= 4 instead of std::abs(z) <= 2 is because it's less costly to compute.
You can verify that the following program outputs your expected sequence if you stream z to std::cout after each iteration:
(0.2,1)(-0.76,1.4)(-1.1824,-1.128)(0.325686,3.66749)

A: Uhm I know I'm a little late but I think it's worth it: I fixed my problem without the library. It actually was quite a dumb mistake: I took the new real value for the calculation of the new imaginary value instead of the previous one. I fixxed it by adding a "buffer" variable that stores the previous real value. My current code is:
int iterate(double r,double  i, int max_iterations) {
    double ir = 0;
    double nir;
    double ii = 0;
    int steps = 0;
    while (ir*ir+ii*ii <= 4 && steps < max_iterations) {
        nir = ir*ir-ii*ii+r;
        ii = 2*ir*ii + i;
        ir = nir;
        ++steps;
    }

    return steps;
}

It works perfectly fine and is a lot faster than the solution with the library. I estimate it's about 5-10 times faster which is the reason why I decided to share this. If I compile it in a release build it pretty much renders instantly using the windows.h header for my graphics.


text:
Q: EF Core: Creating a link between items in the same table Suppose I have a list of companies:

Company
CompanyID

CompanyA
1

CompanyB
2

CompanyC
3

CompanyD
4

Let's say we want to show that CompanyA is a competitor of CompanyB and CompanyC but not CompanyD.
I would like to use EF Core to establish such a link/mapping. I'm assuming I will need to create a mapping table that in DB will look something like this:
Competitor mapping:

CompanyId
CompetitorCompanyID

1
2

1
3

What I am struggling with is how to create such a link in the OnModelCreating(ModelBuilder modelBuilder) method?
I've been able to create maps between entities in 2 different tables, but unable to configure the DBContext class for this use case (where mapped entities live in the same table).

A: If was me doing I would do it like this
The Company model
public class Company
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<CompanyCompetitorRelation> CompanyRelation { get; set; }
    public virtual ICollection<CompanyCompetitorRelation> CompetitorRelation { get; set; }
}

In this model I'm saying that it has 2 relations with the CompanyCompetiorRelation model.
Now for the CompanyCompetitorRelation Model
public class CompanyCompetitorRelation
{
    public int CompanyId { get; set; }
    public int CompetitorId { get; set; }
    public virtual Company CompanyRelation { get; set; }
    public virtual Company CompetitorRelation { get; set; }
}

Now here, I'm saying that a CompanyCompetiorRelation has 2 relations with the Company Model.
Now the magic goes on the FluentAPI
protected override void OnModelCreating(ModelBuilder builder)
{
    builder.Entity<Company>()
        .HasKey(e => e.Id);

    builder.Entity<CompanyCompetitorRelation>()
        .HasKey(e => new { e.CompanyId, e.CompetitorId });

    builder.Entity<CompanyCompetitorRelation>()
        // CompanyCompetitorRelation property
        .HasOne(e => e.CompanyRelation)
        // Company property
        .WithMany(e => e.CompanyRelation)
        // Set the property that is FK for this relation
        .HasForeignKey(e => e.CompanyId);

    builder.Entity<CompanyCompetitorRelation>()
        // CompanyCompetitorRelation property
        .HasOne(e => e.CompetitorRelation)
        // Company property
        .WithMany(e => e.CompetitorRelation)
        // Set the property that is FK for this relation
        .HasForeignKey(e => e.CompetitorId);
}

On the first set of FK of the builder.Entity<CompanyCompetitorRelation>() I'm saying that it has one CompanyRelation with many of the Company and is foreignkey is the CompanyId
on the second set of FK of the builder.Entity<CompanyCompetitorRelation>()
I'm saying that it as one CompetitorRelation relation with many Company and is foreignkey is the CompetitorId
This is what it has generated
migrationBuilder.CreateTable(
name: "Company",
columns: table => new
{
    Id = table.Column<int>(type: "int", nullable: false)
        .Annotation("SqlServer:Identity", "1, 1"),
    Name = table.Column<string>(type: "nvarchar(max)", nullable: true)
},
constraints: table =>
{
    table.PrimaryKey("PK_Company", x => x.Id);
});

migrationBuilder.CreateTable(
    name: "CompanyCompetitorRelation",
    columns: table => new
    {
        CompanyId = table.Column<int>(type: "int", nullable: false),
        CompetitorId = table.Column<int>(type: "int", nullable: false)
    },
    constraints: table =>
    {
        table.PrimaryKey("PK_CompanyCompetitorRelation", x => new { x.CompanyId, x.CompetitorId });
        table.ForeignKey(
            name: "FK_CompanyCompetitorRelation_Company_CompanyId",
            column: x => x.CompanyId,
            principalTable: "Company",
            principalColumn: "Id",
            onDelete: ReferentialAction.Cascade);
        table.ForeignKey(
            name: "FK_CompanyCompetitorRelation_Company_CompetitorId",
            column: x => x.CompetitorId,
            principalTable: "Company",
            principalColumn: "Id",
            onDelete: ReferentialAction.Cascade);
    });

migrationBuilder.CreateIndex(
    name: "IX_CompanyCompetitorRelation_CompetitorId",
    table: "CompanyCompetitorRelation",
    column: "CompetitorId");

Hope that this will help out to understand
You can create as many you want if require, you just have point them in the rigth direction on the FluentAPI
I think it's possible to this on the model also, but I like to use the FluentAPI


text:
Q: It is possible to fetch with a single SQL the minimum (maximum) row in the table when the compared value is combined of two separate fields? Examine the following scenario. There is a table with two columns - DateWithoutMilliseconds and Milliseconds. Together these two columns define the exact timestamp with the milliseconds.
Is it possible to write a single SQL statement (not using stored procedures) which would fetch the row with the minimum timestamp with the milliseconds precision? Actually, just the timestamp is good enough, but it has to be with the milliseconds, because several rows may have the same DateWithoutMilliseconds value, but differ in milliseconds.
Now, I am complete with the idea of storing the total milliseconds in the database instead of the aforementioned two columns. However, I must be sure that I am not missing anything and if there is an SQL that allows to have two columns and still be able to fetch the exact minimum - I want to know it.
Thanks a lot in advance to all the good samaritans out there.
EDIT
We use both SqlServer and MySql.

A: It will probably look different for different databases, but in SQL Server you should be able to do something like this:
SELECT TOP 1
    Field1, Field2,
    dateadd(ms, MillisecondsField, DateWithoutMillisecondsField) TimeStamp
FROM Table
ORDER BY TimeStamp DESC

A: In SQL Server you don't need to specify the time fields in the SELECT clause. You can write it like this:
SELECT TOP 1
       field1
     , field2
  FROM table
 ORDER BY DateWithoutMilliseconds ASC
     , Milliseconds ASC;

I am assuming that when you say you want the minimum timestamp, you want the earliest date. If you want the latest date, then replace ASC with DESC in the ORDER BY clause.


text:
Q: Create MySQL view of max version without inner join I need to create a view of max versions
Select * from
(Select * from DSP) A
Right Outer Join
(Select max(SettleDate) as MaxSD, Symbol from DSP group by Symbol) B
On A.SettleDate = B.MaxSD

However, I can't use a select statement after the first from in a view. How do I get around this? This must be an easy fix but I can't find anything online.


text:
Q: Computing list elements that refer to earlier elements and two other lists without iteration I am attempting to compute the elements of a list, $\{a_i\}$ given lists $\{b_i\}$ and $\{c_i\}$ using the following formula:
$a_i = \frac{1}{c_1}(b_i - \sum_{j = 2}^{i}c_{j}a_{i-j+1})$ for $1\leq i \leq n$.
I was able to implement this formula in an explicit loop, but I would really like to understand how to implement it using some kind of implicit looping construct. I feel it can be done with Fold[] or Map[] using Total[] but I can't quite figure out how to put all the pieces together.
Here is my solution using For[].
b = {1, 2, -2, 0, 0, 0};
c = {1, -1, -2, 2, 0, 0};
n = Length[c];
a = Table[0,{n}];
For[ i = 2, i <= n, i++,
    a[[i]] = (b[[i]] - Total[c[[2;;i]]*a[[i-1;;1;;-1]]]) / c[[1]] ];

It seems to me that it should be possible to do this without having to initialize a to an empty list of zeros, use an iterator variable i, or explicitly compute the length of c. I am very new to Mathematica and a broken down explanation of how to do this in a more functional programming way would be super helpful!

A: I would use a memonized function to calculate the values of a and Map that onto a Range.
a[i_Integer/;i>0]:=
  a[i]=
  (1/c[[1]]) (b[[i]] - Sum[c[[j]] a[i-j+1],{j,2,i,1}])
a[0]=0;

This sets up the function to calculate each a and save the value for future use.  Use this to get your values.
aList = a[#]&/@Range[Length[c]]
(* {1, 3, 3, 7, 7, 15} *)

You can see all the saved values of a by evaluating:
?a


text:
Q: Android Things: How to install apk from device with pm install -r I am trying to build an auto-updater for the Android Things app.apk. So far I have downloaded the new version of the .apk into the /sdcard/download/app.apk and I can also install it from there via the adb terminal e.g.
adb shell
pm install -r /sdcard/Download/app

Now I try to do the same via the device itself. Currently I have this
Process install = Runtime.getRuntime().exec("pm install -r /sdcard/Download/app");
install.waitFor();

But nothing happens. I tried to also open the shell like this, but this time I am getting Cannot run program "su": error=13, Permission denied
 Process install = Runtime.getRuntime().exec("su");
 DataOutputStream out = new DataOutputStream(install.getOutputStream());
 out.writeBytes("pm install -r /sdcard/Download/app");
 out.flush();

Is it possible at all to install the downloaded apk from the device itself? The general way with Intent.ACTION_VIEW doesn't work either. It blanks out and that's it. Nothing happens.

A: Use ADB command
adb install /path-of-your-apk/app.apk

A: You can easily launch an install prompt:
Intent promptInstall = new Intent(Intent.ACTION_VIEW)
    .setDataAndType(Uri.parse("file:///path/to/your.apk"),
                    "application/vnd.android.package-archive");
startActivity(promptInstall);

However, you cannot install .apks without user's explicit permission. Not unless the device and your program are rooted.


text:
Q: How to parse/filter log line with awk or sed I am trying to find out how to filter heroku log drains using awk, sed or some other tool. As you can see the examples below, the command filters the lines with grep related to the router only. But I could not figure out how to filter the rest.
heroku logs -t | grep router |  ???

2013-07-20T20:44:40.855998+00:00 heroku[router]: at=info method=GET path=/oauth2/callback?error=access_denied host=app.herokuapp.com fwd="123.234.456.78" dyno=web.5 connect=1ms service=55ms status=302 bytes=5
2013-07-20T20:44:40.855998+00:00 heroku[router]: at=info method=GET path=/oauth2/callback/succesuser=%7B%22user%3Aexample%40example.com%22%2C%22force%22%3Afalse%7D host=app.herokuapp.com fwd="123.234.456.78" dyno=web.5 connect=1ms service=312ms status=302 bytes=5

Question 1) There is a part that gives detail about the service time in the log lines: (service=55ms and service=312ms from the examples) Let's say I want to see only the ones with service time more than 300ms. How can I achive that?
Optional Question) Is there any chance that I can format these lines comma separated like this: timestamp,path,service
Example outputs for the optional question:

2013-07-20 20:44:40,/oauth2/callback?error=access_denied,55`
2013-07-20 20:44:40,/oauth2/callback/succesuser=%7B%22user%3Aexample%40example.com%22%2C%22force%22%3Afalse%7D,312`

A: See if this sed expression is of any use:
sed '/[3-9][0-9][0-9][m][s]/!d'
sed '/[3-9][0-9][0-9][m][s]/!d

Here's an example:
printf '301ms\n300ms\n302ms\n200ms\n40ms' | sed '/[3-9][0-9][0-9][m][s]/!d'

=> 301ms
=> 300ms
=> 302ms

To get only those lines with more than 300ms, use this instead:
sed '/[3-9][0-9][1-9]/!d'

Another example:
printf '301ms\n300ms\n302ms\n200ms\n40ms' | sed '/[3-9][0-9][1-9][m][s]/!d'

=> 301ms
=> 302ms

The reason why the above--this /[3-9][0-9][1-9]/!d--also filters out numbers smaller than 300, is because of the ! flaggy thingy--it tells sed to delete all lines that don't match the pattern [3-9][0-9][1-9][m][s].

A: Use awk. Put this in a file awk0:

BEGIN       {OFS = ","}

            {split($10,arr,"\="); time = arr[2] + 0}

time > 300  {print $1, $5, time}

Then this should work:
heroku logs -t | grep router | awk -f awk0

Good luck!


text:
Q: Google Advanced Drive API fails on insert of some PDFs but not others function extractTextFromPDF() {
// PDF File URL
// You can also pull PDFs from Google Drive

// this Fall2019_LLFullCatalog.pdf will not insert - internal error on insert is all the feedback that gets logged"
// doesn't matter if I retrieve it from the university website or if I first copy it to my google drive and then retrieve it from there
//var url = "https://uwf.edu/media/university-of-west-florida/offices/continuing-ed/leisure-learning/docs/Fall2019_LLFullCatalog.pdf";
//var url = "https://drive.google.com/drive/u/0/my-drive/Fall2019_LLFullCatalog.pdf";

// both of these pdfs will insert just fine. Size is not the issue because this one is much larger than the one I need to insert
var url = "https://eloquentjavascript.net/Eloquent_JavaScript_small.pdf";
//var url = "https://img.labnol.org/files/Most-Useful-Websites.pdf";

var blob = UrlFetchApp.fetch(url).getBlob();
var size = blob.getBytes().length;

var resource = {
    title: blob.getName(),
    mimeType: blob.getContentType()
};

// Enable the Advanced Drive API Service
var file = Drive.Files.insert(resource, blob, {ocr: true, ocrLanguage: "en"});

// Extract Text from PDF file
var doc = DocumentApp.openById(file.id);
var text = doc.getBody().getText();

return text;

}
See comments in code above that describe the problem.
The PDF that I need to insert with OCR is not working - regardless of whether I retrieve it from the original site or retrieve a copy that I put on google drive. However, two other PDF urls will insert just fine and one of them is considerably larger than the one that fails.
What else could be the issue, if not size limitation?
Thanks,
Steve

A: It could very well be a bug in the Chrome API.  Not all PDF software is created equal, check if the PDF can be read in Adobe Acrobat as a simple test.


text:
Q: Php song like counter This is more of a general question on how I would approach this.
I have a audio player. No data about songs is stored in the database. I would like to use database for counting likes for each song. My question is how would I organize this?
1.
If I list all my songs in database beforehand and add a column for like, then where would I keep track of user ip address? (not sure if there is a better way than using ip address?) So I prevent of same user voting multiple times.
2.
Every time user likes a song I would store {song title, like count, user ip} (maybe something else) in database. But then I would end up with multiple rows of same song with different user ip addresses, so how would I keep track of likes for every song in this case?

A:
No data about songs is stored in the database

If you want to store data about each song, you should probably add a table for the songs.

not sure if there is a better way than using ip address?

If you have a table with user IDs, use that because the same user can log on from different IPs, and different users can log on from the same IP.
As for database structure, what you proposed is probably the right answer.  Once you have a table set up for songs, have a dedicated column just for likes to you can retrieve it easily.
If you want to know which user liked which song (and when) then you need to make a new table like you suggested in your second point.  This is called a junction-table, and is used for many:many relationships (m:m).  There is no unique id.  It joins two tables with many keys (users:songs) and stores any relationship between the two.

*Every time user likes a song I would store {song title, like count, user ip} (maybe something else) in database. But then I would end up with multiple rows of same song with different user ip addresses, so how would I keep track of likes for every song in this case?

Even if you end up with many rows of the same song, they are all unique since each has a different user liking it (and vice-versa, you can get all the songs a specific user liked).  You wouldn't need to store a like-count in here, since you can just count the number of records in the database.  {song title, user id, datestamp} would be fine.


text:
Q: Extracting sublists of specific elements from Python lists of strings I have a large list of elements
a = [['qc1l1.1',
 'qc1r2.1',
 'qc1r3.1',
 'qc2r1.1',
 'qc2r2.1',
 'qt1.1',
 'qc3.1',
 'qc4.1',
 'qc5.1',
 'qc6.1',.................]

From this list i want to extract several sublists for elements start with the letters "qfg1" "qdg2" "qf3" "qd1" and so on.
such that:
list1 = ['qfg1.1', 'qfg1.2',....]
list2 = ['qfg2.1', 'qfg2.2',,,]

I tried to do:
list1 = []
for i in all_quads_names:
    if i in ['qfg']:
       list1.append(i)

but it gives an empty lists, how can i do this without the need of doing loops as its a very large list.

A: Try to revert you if statement and to compare a string to the list elements :
if "qfg" in i:

you can refer to this question :
Searching a sequence of characters from a string in python
you have many python methods to do just that described here:
https://stackabuse.com/python-check-if-string-contains-substring/
Edit after AminM coment :
From your exemple it doesn't seem necessary to use the startwith() method, but if your sublist ("qfg") can also be found later in the string and you need to find only the string that is starting with "qfg", then you should have something like :
if i.startswith("qfg"):

A: You are looking for 'qfg' in the ith element of the all_quads_names. So, try the following:
list1 = []
for i in all_quads_names:
    if 'qfg' in i:
       list1.append(i)

A: Using in (as others have suggested) is incorrect. Because you want to check it as a prefix not merely whether it is contained.
What you want to do is use startswith() for example this:
list1 = []
for name in all_quads_names:
    if name.startswith('qc1r'):
       list1.append(name)

The full solution would be something like:
prefixes = ['qfg', 'qc1r']
lists = []
for pref in prefixes:
   list = []
   for name in all_quads_names:
       if name.startswith(pref):
          list.append(name)
   lists.append(list)

Now lists will contain all the lists you want.

A: Try something like this:

prefixes = ['qfg1', … ]
top = [ […], […], … ]
extracted = []

for sublist in top:
    if sublist and any(prefix in sublist[0] for prefix in prefixes):
        extracted.append(sublist)