text:
Q: unable to upgrade/uninstall current version of python I am trying to upgrade the default version of python on ubuntu 16.04.
I have already run
sudo apt-get install python3.5 command. The result is like below...
Reading package lists... Done
Building dependency tree
Reading state information... Done
python3.5 is already the newest version (3.5.2-2ubuntu0~16.04.5).
0 upgraded, 0 newly installed, 0 to remove and 4 not upgraded.

I also tried to uninstall current version of python. But it didn't work.
Now, how can I upgrade python??
Thanks in advance.


text:
Q: How to fix broken packages in Kali Linux? I was trying to update and upgrade my packages but when i executed the following command :
sudo apt upgrade && sudo apt update

The following message appeared :
Hit:1 https://download.sublimetext.com apt/stable/ InRelease
Hit:2 http://kali.cs.nctu.edu.tw/kali kali-rolling InRelease
Reading package lists... Done
Building dependency tree
Reading state information... Done
767 packages can be upgraded. Run 'apt list --upgradable' to see them.
Reading package lists... Done
Building dependency tree
Reading state information... Done
Calculating upgrade... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 gnustep-base-runtime : Depends: gnustep-base-common (= 1.27.0-3) but 1.26.0-7 is to be installed
 libgnustep-base1.27 : Depends: gnustep-base-common (= 1.27.0-3) but 1.26.0-7 is to be installed
E: Broken packages

I have tried to execute commands below :
sudo dpkg --configure -a
sudo apt install -f
sudo apt update && sudo apt upgrade

But it still error.
What should i do now ?...
Thank you in advance....

A: 1st:    try the apt-get command (if you didn't) so
apt-get update && apt-get upgrade

then these command will help clean your dependencies
sudo apt-get autoclean &&  sudo apt-get clean && sudo apt-get autoremove

those helped in a similar problem. I hope they also helped you ;)

A: So this worked for me
I reinstall libwacom-common and libwacom-bin with:
sudo apt reinstall libwacom-common && sudo apt reinstall libwacom-bin

A: sudo apt-get update --fix-missing

sudo apt-get upgrade --fix-missing

A: I'd suggest running
    sudo apt-get autoclean &&  sudo apt-get clean && sudo apt-get autoremove && sudo apt-get update --fix-missing && sudo apt-get upgrade --fix-missing

redpajama_set_name: RedPajamaStackExchange


text:
Q: JPA @Query select on oracle throws ORA-01722: invalid number on string I have the following query that works perfectly with ms-SQL but failing with oracle
there is sample query, the original is way complicated but this one reproduces the error
@Query("SELECT new Map((s.name + ' - ' + s.name) as name , s.idStandard as idStandard) FROM Standard s ")

jpa model
public class Standard
{

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(unique = true, nullable = false)
    private int idStandard;

    @Column(name = "Name")
    @NonNull
    private String name;

    @Column(name = "Description")
    private String description;

    @Column(name = "UpdateUser")
    private String updateUser;

    @Column(name = "UpdateDT")
        private Date updateDt;
}

why oracle thinks this is  (s.name + ' - ' + s.name) is a number ?

A: I think the world deserves to know :) using concatenate operator || solves the problem!!
concatenate operator allows you to concatenate 2 or more strings together.
see the doc for more info
https://www.techonthenet.com/oracle/functions/concat2.php
updating the query runs on ms SQL and oracle
@Query("SELECT new Map((s.name || ' - ' || s.name) as name , s.idStandard as idStandard) FROM Standard s ")


text:
Q: In Typescript, error constructing Map from Array using common string field for key The following code in Typescript gives an assignment error on the last line
interface T {id: string}
let ts: Array<T> = []
let tMap: Map<string, T> =
    new Map (
        ts.map(t => [t.id, t])
    )

Similar code in a javascript environment works. Cant see what I am doing wrong

A: The problem is that the Map constructor wants an array of two-element tuples, but TypeScript does not infer tuple types from string literals.  That means, the following:
const foo = [1, "two"];

is inferred as the array type Array<string | number> and not the tuple type [number, string].  If you want it to be [number, string] you can use an explicit type annotation like
const foo: [number, string] = [1, "two"];

or a type assertion like
const foo = [1, "two"] as [number, string];

Or, if you need this a lot, since it is possible to get TypeScript to infer a tuple type from function arguments, you can make a helper function like this:
const tuple = <T extends any[]>(...t: T) => t;

and then use it:
const foo = tuple(1, "two"); // inferred as type [number, string]

Any of those will help you get [t.id, t] to behave properly.  Let's try the last one:
interface T { id: string }
let ts: Array<T> = []
let tMap: Map<string, T> =
  new Map(
    ts.map(t => tuple(t.id, t))  // okay
  );

Hope that helps.  Good luck!

A: Seems like Typescript can't infer the the map content as tuples, which should probably be reported as a bug. But I found a workaround which I think is acceptable, by explicitly writing the type of the map content:
let tMap: Map<string, T> =
  new Map(ts.map<[string, T]>(t => [t.id, t]))


text:
Q: Ng-init from an ng-repeat I have a list of products, you can see the JSON :
var panier =
    {
        "Client": "Ben",
        "Date":"",
        "Produits": [
            {
                "Id": "188",
                "Name":"Name1",
                "Qte": "5",
                "Variante":
                "20 Pcs",
                "Prix" :"149.00"
            },
            {
                "Id": "231",
                "Name":"Name2",
                "Qte": "2",
                "Variante": "7 encas de 35g",
                "Prix" :"109.00"
            },
            {
                "Id": "232",
                "Name":"Name3",
                "Qte": "7",
                "Variante": "10 pieces",
                "Prix" :"99.00"
            }
        ]
    };

I do a list with ionic to retrieve the products and it all works.
Inside of the list Item when I do (for example the firsr item) Qte = {{product.Qte}} it gives me Qte = 5
But when I want to put the quantity on a select it doesn't work with the ng-init :
<select
    ng-model="selectedQte"
    ng-init="selectedQte = {{product.Qte}}"
    ng-options="selectedQte for selectedQte in range('10')"
    ng-change="product.Qte = selectedQte">
</select>

I have tried :
ng-init="selectedQte = product.Qte"

and :
ng-init="selectedQte = {{product.Qte}}"

But nothing happens. When I have tried :
ng-init="selectedQte = 3"

I have a 3on my 3 selects.
But I want 5 on the first one, 2on the second and 7on the third.
Any help is needed, thanks !

A: Looks like the problem is with the dataType of the Qte in the JSON is string & the array created for range is sequence of number. You need to convert the JSON coming from response to number instead of string will do the trick. You could directly bind the Product.Qte to your ng-model.
Markup
<select ng-model="product.Qte"
    ng-options="selectedQte for selectedQte in range('10')">
</select>

A: This should work:
<select ng-model="selectedQte" ng-init="selectedQte = panier.Produits[0]"
ng-options="item.Name for item in panier.Produits">
</select>

Your ng-model contains the selected value, however ng-option should iterate over your list. In your html you use selectedQte for both cases.


text:
Q: SSIS apparently changes data type of column in inbound Excel file I have an Excel file coming in from an outside vendor.  Column A contains a unique identifier that usually starts with the letter "K" but the first several records start with a number "9", so of course SSIS wants to interpret the column as numeric, causing the "K" records to come out of the Excel data source as null.  So I set the column data type to WSTR(20) in Advanced Editor, which worked fine in development.  But when I run from the prod environment and my inbound file has the first several records starting with "9", SSIS seems to dynamically change the data type to numeric and then the "K" records again come out as null.  I realize that putting the "K" records first will solve the problem but I have no control over a file from an outside vendor.  Your suggestions are greatly appreciated.

A: SSIS guesses the data types based on a sample of the first X rows in the file.  You can expand the range of sampling but it is limited.  You can always go in and override/manually set the data type for the column in the Advanced Editor for the source.  Setting it manually base on pre-existing knowledge will always give you the best results.

A: In ssis we can increase default guess rows by changing connection configuration used to connect excel file. You can set IMEX=1 in connection string to increase type guess rows.


text:
Q: do-release-upgrade complains no module namedd apt Been searching for a while and couldn't find the relevant questions/solutions.
My system is running 14.04, every time when I logon the system, a message pops up saying 14.10 available, run do-release-upgrade.
Before hit with do-release-upgrade,  I ran apt-get update & apt-get upgrade to make sure nothing is pending to update. Here are the errors I got
root@ubuntu:~# do-release-upgrade
Checking for a new ubuntu release
Get:1 Upgrade tool signature [198 B]
Get:2 Upgrade tool [1147 kB]
Fetched 1148 kB in 6s (109 kB/s)
authenticate 'utopic.tar.gz' against 'utopic.tar.gz.gpg'
extracting 'utopic.tar.gz'
Traceback (most recent call last):
  File "/tmp/update-manager-J0y7tt/utopic", line 3, in <module>
    from DistUpgrade.DistUpgradeMain import main
  File "/tmp/update-manager-J0y7tt/DistUpgrade/DistUpgradeMain.py", line 22, in <module>
    import apt
ImportError: No module named 'apt'
root@ubuntu:~#

Although apt and python are both installed properly.
root@ubuntu:~# apt-cache policy apt
apt:
  Installed: 1.0.1ubuntu2.18
  Candidate: 1.0.1ubuntu2.18
  Version table:
 *** 1.0.1ubuntu2.18 0
        500 http://us.archive.ubuntu.com/ubuntu/ trusty-updates/main amd64 Packages
        100 /var/lib/dpkg/status
     1.0.1ubuntu2.17 0
        500 http://security.ubuntu.com/ubuntu/ trusty-security/main amd64 Packages
     1.0.1ubuntu2 0
        500 http://us.archive.ubuntu.com/ubuntu/ trusty/main amd64 Packages
root@ubuntu:~# apt-cache policy python
python:
  Installed: 2.7.5-5ubuntu3
  Candidate: 2.7.5-5ubuntu3
  Version table:
 *** 2.7.5-5ubuntu3 0
        500 http://us.archive.ubuntu.com/ubuntu/ trusty/main amd64 Packages
        100 /var/lib/dpkg/status
root@ubuntu:~#

python-apt is also installed.
root@ubuntu:~# apt-cache policy python-apt
python-apt:
  Installed: 0.9.3.5ubuntu2
  Candidate: 0.9.3.5ubuntu2
  Version table:
 *** 0.9.3.5ubuntu2 0
        500 http://us.archive.ubuntu.com/ubuntu/ trusty-updates/main amd64 Packages
        100 /var/lib/dpkg/status
     0.9.3.5 0
        500 http://us.archive.ubuntu.com/ubuntu/ trusty/main amd64 Packages
root@ubuntu:~#

Did anyone know how to get around this so I can go to 14.10?
Thanks,
The problem here appeared to be with python-apt package, although the right version is showing installed but somehow python script was complaining apt module cannot be recognized,  after re-installed the package python-apt, do-release-upgrade worked.

A: Ubuntu 14.10 has been EOL since July 23, 2015 so it is not possible to update to this version. It should be possible to update to 16.04 which is also a LTS version.
Check settings in Update Manager is set to only inform on new LTS versions, and there should be a button saying New release 16.04 is available.

A: The problem is that python-apt somehow was playing up. The DistUpgradeMain.py simply failed at the first line
import apt
I just removed python-apt and re-installed it again, do-release-upgrade now worked.


text:
Q: How to avoid anemic domain models, or when to move methods from the entities into services I have a common scenario that I am looking for some guidance from people more experienced with DDD and Domain Modeling in general.
Say I start out building a blog engine, and the first requirement is that after an Article is posted, users can start posting Comments on it. This starts fine, and leads to the following design:
public class Article
{
    public int Id { get; set; }

    public void AddComment(Comment comment)
    {
        // Add Comment
    }
}

My MVC Controller is designed like this:
public class ArticleController
{
    private readonly IRepository _repository;

    public ArticleController(IRepository repository)
    {
        _repository = repository;
    }

    public void AddComment(int articleId, Comment comment)
    {
        var article = _repository.Get<Article>(articleId);
        article.AddComment(comment);
        _repository.Save(article);
        return RedirectToAction("Index");
    }
}

Now everything works fine, and it meets the requirement. Next iteration we get a requirement that every time a Comment is posted, the blog author should get an email notifying him.
At this point, I have 2 choices that I can think of.
1) Modify Article to require an IEmailService (in the ctor?) or obtain an EmailService from a static reference to my DI container
1a) Seems pretty ugly. I believe it breaks some Domain model rules that my entities are aware of services?
public class Article
{
    private readonly IEmailService _emailService;

    public Article(IEmailService emailService)
    {
        _emailService = emailService;
    }

    public void AddComment(Comment comment)
    {
        // Add Comment

        // Email admin
        _emailService.SendEmail(App.Config.AdminEmail, "New comment posted!");
    }
}

1b) Also seems ugly, I now require a configured DI container which is accessed statically.
public class Article
{
    public void AddComment(Comment comment)
    {
        // Add Comment

        // Email admin
        var emailService = App.DIContainer.Resolve<IEmailService>();
        emailService.SendEmail(App.Config.AdminEmail, "New comment posted!");
    }
}

2) Create an IArticleService and move the AddComment() method to this service instead of on the Article Entity itself.
This solution is cleaner I believe, but Adding a comment is now less discoverable and requires an ArticleService to perform the work. It seems like AddComment should belong on the Article class itself.
public class ArticleService
{
    private readonly IEmailService _emailService;

    public ArticleService(IEmailService emailService)
    {
        _emailService = emailService;
    }

    public void AddComment(Article article, Comment comment)
    {
        // Add comment

        // Email admin
        _emailService.SendEmail(App.Config.AdminEmail, "New comment posted!");
    }

}

public class ArticleController
{
    private readonly IRepository _repository;
    private readonly IArticleService _articleService;

    public ArticleController(IRepository repository, IArticleService articleService)
    {
        _repository = repository;
        _articleService = articleService;
    }

    public void AddComment(int articleId, Comment comment)
    {
        var article = _repository.Get<Article>(articleId);
        _articleService.AddComment(article, comment);
        _repository.Save(article);
        return RedirectToAction("Index");
    }
}

So I am basically look for advice from people more experienced in domain modeling. If I am missing a more obvious solution please let me know :)
I generally dislike both solutions to be honest, because the Service option is less discoverable. I can no longer add a Comment to an instance of an Article without having an ArticleService available. It also feels less natural, since AddComment seems like such an obvious method on the Article type.
Anyway I look forward to reading the input. Thanks in advance.

A: I think this particular issue can be solved elegantly with a Domain Event.

A: Have you considered having the article controller essentially pass a message up / post an event? Then any "article-posted-event-listeners" would consume that message and respond accordingly; in your specific case, an email notifier would be listening for those events and be configured to do so. This way the article posting bits don't need to know anything about the email notifying bits.

A: Looking through this excellent question, has lead me to read Employing the Domain Model Pattern from Udi on MSDN.
HTH helps other users.
I been trying to work out how to ask this same question but managed to confused myself several times. Your question certainly is not! Thanks

A: Without using domain events, you can use the Double Dispatch pattern and put the AddComment logic inside a Domain Service.
This is how it would look like:
public class Article
{
    public void AddComment(Comment comment, IAddCommentProcessor commentProcessor)
    {
        commentProcessor.AddComment(this, comment);
    }
}

public interface IAddCommentProcessor
{
    void AddComment(Article article, Comment comment);
}

public class AddCommentAndEmailProcessor : IAddCommentProcessor
{
    private readonly _emailService;
    public AddCommentAndEmailProcessor(EmailService emailService)
    {
        _emailService = emailService;
    }

    public void AddComment(Article article, Comment comment)
    {
        // Add Comment

        // Email
        _emailService.SendEmail(App.Config.AdminEmail, "New comment posted!");
    }
}

public class ArticleController
{
    private readonly IRepository _repository;
    private readonly IArticleService _articleService;

    public ArticleController(IRepository repository, IArticleService articleService)
    {
        _repository = repository;
        _articleService = articleService;
    }

    public void AddComment(int articleId, Comment comment)
    {
        var article = _repository.Get<Article>(articleId);
        article.AddComment(comment, new AddCommentAndEmailProcessor(ServiceLocator.GetEmailService())); // Or you can use DI to get the Email Service, or any other means you'd prefer
        _repository.Save(article);
        return RedirectToAction("Index");
    }
}

If you prefer, you can keep the Adding Comment logic on the AddComment of Article, and instead make the Domain Service into something like ICommentAddedProcessor with a CommentAdded() method and have AddComment on Article take a Comment and a ICommentAddedProcessor.

A: I think whenever the domain expert uses the word "when" one must consider Domain Events or an event bus, this was a classic example in that sense.
I have written a detailed answer which describes when to use event buses, it might be a good read around this topic


text:
Q: How can I use the find command to list all the file types in a directory and all subdirectories? How can I use the find command to recursively list all the file extensions in a directory?  Using wildcards I can find all the files of a certain type:
find . -iname '*.mp3'

but what I want to to list to search a directory and all sub directories and list all of the file extensions found.

A: A little more searching revealed this solution:
find . -type f | awk -F'.' '{print $NF}' | sort| uniq -c | sort -g

Not sure why this link did not show up in previous searches.

A: This would be more robust than your solution:
find . -type f -name '*.*' | awk -F. '{print $NF}' | sort | uniq -c | sort -g

That is, since you're looking for the part of a filename following a dot, it's important to add that detail to filters of find. Otherwise files without an extension will give strange results: the entire path may be printed, or if the path contained a dot in one of the intermediary subdirectories, then a partial path after the last dot will be printed.


text:
Q: Prove $10^{3n+1}+10^{6n+2}+1=111k$ I'm stuck to prove this one can anyone help me please?

Prove that $10^{3n+1}+10^{6n+2}+1=111k$.

I'm not sure what exactly I should do.
n is a natural number and k is an integer

A: The OP has corrected the problem.  The corrected answer is below.
Assuming that $k$ must be an integer (not stated by OP), this is the same as showing that
$$
10^{n+1}+10^{6n+2}+1\equiv 0\pmod{111}.
$$
Observe that $10^3=1000=999+1=1+9(111)$.  Therefore, there are only three values for the first and second terms, $10$, $100$, and $1$.  In particular, when
$$
10^{n+1}=\begin{cases}10&n+1\equiv 1\pmod 3\\100&n+1\equiv 2\pmod 3\\1&n+1\equiv 0\pmod 3.\end{cases}=\begin{cases}10&n\equiv 0\pmod 3\\100&n\equiv 1\pmod 3\\1&n\equiv 2\pmod 3.\end{cases}
$$
On the other hand, there is only one value for $10^{6n+2}\pmod{111}$ since $10^{6n}=(10^3)^{2n}\equiv 1^{2n}=1\pmod{111}$.  Therefore, the second term is equivalent to $100$ modulo $111$.
This appears to be a problem, since (modulo $111$) there are exactly three sums $10+11+1$, $100+100+1$, and $1+100+1$, only the first one is equivalent to $0$ modulo $111$.  In other words, if we let $n=1$, then the sum is $100,000,101$, which is not a multiple of $111$.
To the OP, please check the original statement.  The statement would be correct if the first term were $10^{3n+1}$, however.
When the first term is $10^{3n+1}$ instead of $10^{n+1}$, observe that $10^{3n}=(10^3)^n\equiv 1^n=1\pmod{111}$, therefore, the sum can be reduced to
$$
10^{3n+1}+10^{6n+2}+1\equiv 10+10^2+1\equiv 0\pmod{111}.
$$

A: There's a typo. The assertion should be
$$10^{3n+1}+10^{6n+2}+1\equiv 0\mod111.$$
As  $10^3\equiv1 \bmod 3$ and$\bmod37$, and $3$ and $37$ are coprime, $10^3\equiv 1\bmod 111$. Hence
$$10^{3n+1}+10^{6n+2}+1\equiv 10+10^2+1=111\equiv0\mod111.$$

A: Hint $\ {\rm mod}\,\ i^2\!+i+1\!:\,\ \color{#0a0}{i^3}\equiv\color{#c00}{\bf 1}\ $ by $\ i^3\!-1 = (i\!-\!1)(i^2\!+i+1)\equiv 0\ $
therefore  $\qquad\quad  \begin{align} &\color{#0a0}i^{\large \color{#0a0}{3}j}\, i^{\large  2} + {\color{#0a0}i^{\large\color{#0a0}{3}k}}\, i +  1\\
\equiv\ &\,\color{#c00}{\bf 1}^{\large  j}\,i^{\large 2}\,  + \color{#c00}{\bf 1}^{\large  k}\, i + 1\\
\equiv\ &\quad\ i^{\large 2}\ \  +\,\ \ \ i+1\ \equiv\ 0 \end{align}\qquad $ OP is case $\,i = 10,\ j=2n,\ k=n$


text:
Q: MonoTouch issues when binding ObjectiveC library I am trying to make bindings for the Vfr PDF reader: https://github.com/vfr/Reader
This is an ObjectiveC application.
I followed the walkthrough from Xamarin there: http://docs.xamarin.com/guides/ios/advanced_topics/binding_objective-c/binding_walkthrough/
Unfortunately I am still struggling on one issue. In my AppDelegate I instantiate a ReaderDemoController, which comes from the Vfr Reader library but, when running on the device (an iPhone5), it keeps saying:

Wrapper type 'Hager.VfrReaderCoreBinding.ReaderDemoController' is missing its native ObjectiveC class 'ReaderDemoController'.

Which is strange since the Fat library contains i386, armv7, armv7s and arm64 libraries (done that using lipo). This is the LinkWith file content:
[assembly: LinkWith ("libVfrReaderCoreNative.a", LinkTarget.Simulator | LinkTarget.ArmV7 | LinkTarget.ArmV7s, ForceLoad = true)]

In the ApiDefinition file this is the ReaderController interface:
[BaseType (typeof (UIViewController))]
public interface ReaderDemoController {
}

Nothing really "complicated". Any idea of what could be the cause?
This is the binding solution: solution zipped
This is also not working in the simulator. I get :
Could not create an native instance of the type 'Hager.VfrReaderCoreBinding.ReaderDemoController': the native class hasn't been loaded.

It is possible to ignore this condition by setting MonoTouch.ObjCRuntime.Class.ThrowOnInitFailure to false.

A: It looks like the Objectice-C library wasn't built correctly, if you run nm on it you'll see it's almost empty:
$ nm libVfrReaderCoreNative.a

libVfrReaderCoreNative.a(VfrReaderCoreNative.o):
0000000000000000 s L_OBJC_CLASS_NAME_
                 U _OBJC_CLASS_$_NSObject
00000000000000d0 S _OBJC_CLASS_$_VfrReaderCoreNative
                 U _OBJC_METACLASS_$_NSObject
00000000000000a8 S _OBJC_METACLASS_$_VfrReaderCoreNative
                 U __objc_empty_cache
                 U __objc_empty_vtable
0000000000000060 s l_OBJC_CLASS_RO_$_VfrReaderCoreNative
0000000000000018 s l_OBJC_METACLASS_RO_$_VfrReaderCoreNative

In particular nothing related to ReaderDemoController.


text:
Q: How do I connect a wired desktop to internet via a wireless laptop? I have a desktop system running Ubuntu 10.10. It has no wireless card just a wired Ethernet card.
I have a Thinkpad T42 laptop running Ubuntu 10.10 in the same room as the desktop. It uses its  wireless connection to connect to a wireless access point in another room. The wireless access point provides internet access to the laptop.
Is there anyway to create a wired connection between the desktop and the laptop so that the desktop can connect out to the internet through the laptop?

A: I did this not that long ago for my brother when I set up Ubuntu 11.04 on his desktop and used an Ethernet cable between his machine and my Ubuntu 11.04 laptop, so his desktop could use my laptop's wireless. It was all GUI too, and required no extra packages or anything.
Unfortunately, I can't find the original source of my solution, but this post for how to do it in Ubuntu 9.10 should work just as well, it seems familiar. Basically, you just need to go to your network connections on your laptop, open Edit Connections..., click your wired Ethernet connection, and under IPv4 settings set the Method to "Shared to other computers". Then click Save and reboot your machine for it to take effect.

A: It would be a bit tricky but it could work.  You would need to set the default gateway to your primary router, bridge your LAN to your WLAN, make sure DNS is a match on the desktop and laptop.  Pretty sure I'm missing a few steps, but it gives you a general direction.


text:
Q: Asp Core: Azure Ad Auth + custom JWT + custom Identity store With ASP.NET Core 2.0 I try to achieve the following:

*

*Authentication via Azure AD (registered App)

*Custom JWT as the authentication scheme to

*

*make the the web app auth work across servers/instances

*be able to save the bearer to login with desktop clients

*Have a custom identity store to introduce custom roles, policies, and other.

All these parts have working examples, but while trying to combine them I stumbled over some problems.
The Web Api + Azure Ad Auth example uses JWT Tokens for authentication, but doesn't have logic for validating or creating tokens. Neither does it have logic for login/logout, but this seems reasonable, its just Api.
Here is a quick reminder of the code of the Web Api example:
AzureAdAuthenticationBuilderExtensions.cs
using System;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;

namespace Microsoft.AspNetCore.Authentication
{
    public static class AzureAdServiceCollectionExtensions
    {
        public static AuthenticationBuilder AddAzureAdBearer(this AuthenticationBuilder builder)
            => builder.AddAzureAdBearer(_ => { });

        public static AuthenticationBuilder AddAzureAdBearer(this AuthenticationBuilder builder, Action<AzureAdOptions> configureOptions)
        {
            builder.Services.Configure(configureOptions);
            builder.Services.AddSingleton<IConfigureOptions<JwtBearerOptions>, ConfigureAzureOptions>();
            builder.AddJwtBearer();
            return builder;
        }

        private class ConfigureAzureOptions: IConfigureNamedOptions<JwtBearerOptions>
        {
            private readonly AzureAdOptions _azureOptions;

            public ConfigureAzureOptions(IOptions<AzureAdOptions> azureOptions)
            {
                _azureOptions = azureOptions.Value;
            }

            public void Configure(string name, JwtBearerOptions options)
            {
                options.Audience = _azureOptions.ClientId;
                options.Authority = $"{_azureOptions.Instance}{_azureOptions.TenantId}";
            }

            public void Configure(JwtBearerOptions options)
            {
                Configure(Options.DefaultName, options);
            }
        }
    }
}

Excerpt of Startup.cs
public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(sharedOptions =>
    {
        sharedOptions.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
    })
    .AddAzureAdBearer(options => Configuration.Bind("AzureAd", options));

    services.AddMvc();
}

The Web Application + Azure Ad example on the other hand uses OpenId with cookies and does have login/logout logic:
AzureAdAuthenticationBuilderExtensions.cs
using System;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;

namespace Microsoft.AspNetCore.Authentication
{
    public static class AzureAdAuthenticationBuilderExtensions
    {
        public static AuthenticationBuilder AddAzureAd(this AuthenticationBuilder builder)
            => builder.AddAzureAd(_ => { });

        public static AuthenticationBuilder AddAzureAd(this AuthenticationBuilder builder, Action<AzureAdOptions> configureOptions)
        {
            builder.Services.Configure(configureOptions);
            builder.Services.AddSingleton<IConfigureOptions<OpenIdConnectOptions>, ConfigureAzureOptions>();
            builder.AddOpenIdConnect();
            return builder;
        }

        private class ConfigureAzureOptions : IConfigureNamedOptions<OpenIdConnectOptions>
        {
            private readonly AzureAdOptions _azureOptions;

            public ConfigureAzureOptions(IOptions<AzureAdOptions> azureOptions)
            {
                _azureOptions = azureOptions.Value;
            }

            public void Configure(string name, OpenIdConnectOptions options)
            {
                options.ClientId = _azureOptions.ClientId;
                options.Authority = $"{_azureOptions.Instance}{_azureOptions.TenantId}";
                options.UseTokenLifetime = true;
                options.CallbackPath = _azureOptions.CallbackPath;
                options.RequireHttpsMetadata = false;
            }

            public void Configure(OpenIdConnectOptions options)
            {
                Configure(Options.DefaultName, options);
            }
        }
    }
}

Excerpt of Startup.cs
public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(sharedOptions =>
    {
        sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
    })
    .AddAzureAd(options => Configuration.Bind("AzureAd", options))
    .AddCookie();

    services.AddMvc(options =>
    {
        var policy = new AuthorizationPolicyBuilder()
            .RequireAuthenticatedUser()
            .Build();
        options.Filters.Add(new AuthorizeFilter(policy));
    })
    .AddRazorPagesOptions(options =>
    {
        options.Conventions.AllowAnonymousToFolder("/Account");
    });
}

AccountController.cs
public class AccountController : Controller
{
    [HttpGet]
    public IActionResult SignIn()
    {
        var redirectUrl = Url.Page("/Index");
        return Challenge(
            new AuthenticationProperties { RedirectUri = redirectUrl },
            OpenIdConnectDefaults.AuthenticationScheme
        );
    }

    [HttpGet]
    public IActionResult SignOut()
    {
        var callbackUrl = Url.Page("/Account/SignedOut", pageHandler: null, values: null, protocol: Request.Scheme);
        return SignOut(
            new AuthenticationProperties { RedirectUri = callbackUrl },
            CookieAuthenticationDefaults.AuthenticationScheme, OpenIdConnectDefaults.AuthenticationScheme
        );
    }
}

I have merged somehow both variants, but apparently it doesn't work. I replaced of course CookieAuthenticationDefault with JwtBearerDefaults in the login method.
Excerpt of Startup.cs
public void ConfigureServices(IServiceCollection services)
{
    services.AddEntityFrameworkSqlServer().AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

    services.AddIdentity<ApplicationUser, IdentityRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders();

    services.AddAuthentication(sharedOptions =>
    {
        sharedOptions.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
        sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
    })
    .AddAzureAd(options => Configuration.Bind("AzureAd", options))
    .AddJwtBearer(options =>
    {
        options.IncludeErrorDetails = true;

        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = "localhost",
            ValidAudience = "localhost",
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("test"))
        };
    });

    services.AddMvc(options =>
    {
        var policy = new AuthorizationPolicyBuilder()
            .RequireAuthenticatedUser()
            .Build();
        options.Filters.Add(new AuthorizeFilter(policy));
    })
    .AddRazorPagesOptions(options =>
    {
        options.Conventions.AllowAnonymousToFolder("/Account");
    });
}

I don't fully understand how the different authentications are chained or depend on each other. I understand, that OpenId uses internally some sort of JWT, still the following questions remain:

*

*Why does the Web Api example just uses JWT, but the other uses OpenId with cookies ?

*Why does the OpenId example doesn't use JWT in the first place ?

*Does custom JWT work with OpenId ?

*Is it possible to introduce a custom identity store, but keep the Azure AD for login (and the login name) ?

It would be great if you could offer me some guidance, no fully working example needed (even though this would be great)

A: If you want combine Cookies and Bearer authorization in your ASP.NET Core web application, you could follow the code snippet below:
services.AddAuthentication(sharedOptions =>
{
    sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddJwtBearer(jwtOptions=> {
    jwtOptions.IncludeErrorDetails = true;
    jwtOptions.Authority = "{Authority}";
    jwtOptions.Audience = "{Audience}";
    jwtOptions.TokenValidationParameters = new TokenValidationParameters()
    {
        ValidIssuer = "{ValidIssuer}",
        ValidAudience = "{ValidAudience}"
    };
    jwtOptions.Events = new JwtBearerEvents()
    {
        OnAuthenticationFailed = context => {
            //TODO:
            return Task.FromResult(0);
        },
        OnTokenValidated = context => {
            //At this point, the security token has been validated successfully and a ClaimsIdentity has been created
            var claimsIdentity = (ClaimsIdentity)context.Principal.Identity;
            //add your custom claims here
            claimsIdentity.AddClaim(new Claim("test", "helloworld!!!"));

            return Task.FromResult(0);
        }
    };
})
.AddAzureAd(options => Configuration.Bind("AzureAd", options))
.AddCookie();

I noticed that you added a global AuthorizeFilter, at this time you need to make sure the anonymous action(s) need to decorate with AllowAnonymous attribute.
services.AddMvc(options =>
{
    var policy = new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        .AddAuthenticationSchemes(CookieAuthenticationDefaults.AuthenticationScheme, JwtBearerDefaults.AuthenticationScheme)
        .Build();
    options.Filters.Add(new AuthorizeFilter(policy));
})

Or you could decorate the controller action with Authorize attribute as follows:
[Authorize(AuthenticationSchemes = "Cookies,Bearer")]
public IActionResult UserInfo()
{
    return Json(User.Claims.Select(c => new { key = c.Type, value = c.Value }));
}

For the OpenID Connect middleware, you could modify the Configure(string name, OpenIdConnectOptions options) method under AzureAdAuthenticationBuilderExtensions.cs file to add your custom claims (e.g. role,etc.) as follows:
public void Configure(string name, OpenIdConnectOptions options)
{
    options.ClientId = _azureOptions.ClientId;
    options.Authority = $"{_azureOptions.Instance}{_azureOptions.TenantId}";
    options.UseTokenLifetime = true;
    options.CallbackPath = _azureOptions.CallbackPath;
    options.RequireHttpsMetadata = false;
    //the new code
    options.Events = new OpenIdConnectEvents
    {
        OnTokenValidated = context =>
        {
            var claimsIdentity = (ClaimsIdentity)context.Principal.Identity;
            //add your custom claims here
            claimsIdentity.AddClaim(new Claim("test", "helloworld!!!"));

            return Task.FromResult(0);
        }
    };
}

In summary, upon the configuration, you could combine Cookies and Bearer authentication, and after the token has been validated, you could retrieve the user identifier and get additional user info from your database, then attach them to ClaimsIdentity.
For desktop clients, you could leverage ADAL (for AD app v1.0) or MSAL (for AD app v2.0) to log in and retrieve the access_token or id_token, then use it as the bearer token to access your web application.


text:
Q: Alternative Smartlock for Passwords implementation? I had to sign in to Netflex yesterday and got an unexpected UI. Can you tell me which library they are using? This is not the normal Smartlock for Passwords UI which I'm using in my own App.
Even on the documentation is an old screenshot of Netflix with their old UI.

A: Netflix uses One tap sign in provided by google
, More info you can find over this link
https://developers.google.com/identity/one-tap


text:
Q: How can I find mean for same value column? in pandas I have dataframe, and I am trying to find mean of stars for each name
  Name  stars
0   A      5
1   A      5
2   B      3
3   C      2
4   B      4
5   B      2
6   B      2

Output:
       count mean stars
    A   2     5.00
    C   1     2.00
    B   4     1.57

A: Group the dataframe by Name, then apply len, and np.mean aggregates on stars column.
>>> df.groupby('Name')['stars'].agg(**{ 'count': len, 'mean stars': np.mean})

      count  mean stars
Name
A         2        5.00
B         4        2.75
C         1        2.00


text:
Q: No Rails found in SDK on Sierra I have seen:
How to fix "Run Configuration Error: [No Rails found in SDK]"?
https://stackoverflow.com/questions/35658326/rubymine-kept-telling-me-no-rails-found-in-sdk
No rails found in sdk intellij
https://intellij-support.jetbrains.com/hc/en-us/community/posts/206714535-No-Rails-found-in-SDK
I have:
RubyMine 2016.2.3
Build #RM-162.1812.23, built on September 5, 2016
JRE: 1.8.0_112-release-b343 x86_64
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
MacOs 10.12.1 (16B2555)

I tried setting it up as normal by choosing the ruby version with a green check, hitting apply:

Also I tried running:
gem update --system
gem install rails

This doesn't work. What am I doing wrong?

A: If you haven't, update your X-code installation by running:
xcode-select --install

then rebuild all your gems by running:
gem pristine --all

Updating to sierra messes up with your dev environment. The above worked for me.


text:
Q: How can I send a 997 ACK through Logic Apps I am trying to send a 997 ack through logic apps. I have managed to generate the JSON through get the FA returned when decoding a message. I then pass this over to another app which then tries to encode it to X12.
The problem comes here, the app throws an error saying that it cannot find the relevant schema in the agreement, but I am unable to add a 997 schema to the agreement as it doesn't show up in the UI. I have the schema in the portal.

A: If anyone needs this in the future, the answer is to first enable the FA expected within the Receive Agreement. Then within your Logic App, when you're iterating through good and bad messages you create another ForEach and iterate through 'GeneratedAcks'. Then add an Encode X12 step, pass in the AckPayload and the name of the agreement. This will give you your 997 EDI, you then simply need to send it over to the customer by the usual means, in my case AS2 and HTTP. enter image description here


text:
Q: Adding a 'Covered Domain' to a lightsail load balancer certificate? I'm working with Lightsail for a single domain, and also have a lightsail load balancer in place. Under the domain I have a few subdomains (blog.mydomain.com, admin.mydomain.com etc) - all of that is working just fine.
However, I'm now trying to roll out another subdomain (for an AMP mobile version), which also requires that I use https. As I understand it, because I can only 'attach' one certificate at a time, the only way I can add this subdomain is to delete the current certificate & create a new one with both the existing subdomains and the new one I want to add.
So, I have 2 questions;
1) Firstly, is my assumption correct that I will need to delete the existing certificate & create a new one?
2) If so, when I create the new one will the CNAME names & values be the same as the current certificate, or will I have to re-do all the dns entries too?
Many Thanks in advance!

A: Answering my own question here because I figured I'd just go ahead and try it (living life on edge etc!).

*

*No need to delete the existing certificate before creating a new one (it does allow you to add the same domains & subdomains, before deleting the existing).

*'Wildcard' subdomains are not permitted (as far as I can tell - it wouldn't allow me to create *.mydomain.com anyway)

*The names & values on the 'new' certificate are the same as the existing, so those 'validate' almost immediately and don't require new dns entries.


text:
Q: Cannot read property 'length' of undefined: Datatables So I'm following the information here, http://datatables.net/examples/ajax/simple.html, just to setup a very basic datatable. I'll work on getting it exactly the way I want once that is done. Here's my code:
Table:

            Symbol
            Company Name
            Market
            Purchase Price
            Commission
            Shares
            Purchase Date

            Symbol
            Company Name
            Market
            Purchase Price
            Commission
            Shares
            Purchase Date

Javascript:
$('table#transactions').dataTable({
    ajax: url
});

Data (received):
{"data":
    [
        ["AAPL","Apple Inc.","NYSE","30.00","0.00","100","2015-02-03"],
        ["T.TO","TELUS Corporation","TSE","12.75","1.25","400","2015-02-03"],
        ["SNE","Sony Corporation","NASDAQ","42.63","2.50","50","2015-01-28"]
    ]
}

So the issue is I'm getting the error in the title, and I have no idea why. As far as I can tell, I've almost exactly copied the code on the example page, and copied the way the data is sent. I was hoping another set of eyes would help tell me where I went wrong.
EDIT:
I've changed the data being sent to the smallest amount of data possible, and checked the actual response from the network, and this is what I see:
"{\"data\":[\"AAPL\",\"Apple Inc.\",\"NYSE\",\"30.00\",\"0.00\",\"100\",\"2015-02-03\"]}"

Is the output of that data messing me up? I should mention I am sending this data via PHP, it was an array that I used json_encode on.

A: So, I finally figured out the answer to this and thought I would put it up for anyone in the same position as me.
DataTables states that it wants a json object, so I encoded an array in PHP using json_encode to get that. However, it turns out that sending a standard array of $data['data'][] is what it actually wants.


text:
Q: My non-nullable ArrayList is returning a null upon calling it and throwing a Null Pointer Exception Running this on IntelliJ IDEA 2020.11 using JDK 14 and coding it in Kotlin.
I have a class with a variable menuComponents which is an ArrayList full of MenuComponents, but it's empty at initialization.
var menuComponents: ArrayList<MenuComponent> = ArrayList()

I want to edit the components so I wrote this.
for (component in menuComponents) {
    //Do some stuff. The stuff doesn't matter, it throws an exception if I leave it blank
}

When I call on this method, I get a null pointer exception. Additionally, the for loop doesn't even matter.
class NPE() {

    init {
        refreshProperties()
    }

    var menuComponents: ArrayList<Double> = ArrayList()

    fun refreshProperties() {
        refreshJMenuComponents()
    }

    private fun refreshJMenuComponents() {
        val i = menuComponents.size
        println("$i is the length.")
        for (index in 0 until menuComponents.size) {
            val component = menuComponents[index]
            println("Refreshed component: $component")
        }
    }
}

fun main() {

    NPE()
}

This statement errors out too. I don't change menuComponents at all before I call these, so it should just be equal to a blank array list. I don't know why it's throwing a Null Pointer Exception.
menuComponents = arrayListOf(//component 1, component 2)

If I try running any of the previous statements on menuComponents now, it still throws a Null Pointer Exception. The value is not nullable, and I am explicitly setting it equal to something, so why is it erroring out at all? It should just not even compile if there is a null object somewhere? It compiles and then throws an exception.
Is this some sort of possible bug or am I just missing something?

A: I just needed to move the variable initialization above the init block.
class NPE() {

    var menuComponents: ArrayList<Double> = ArrayList()

    init {
        refreshProperties()
    }

    fun refreshProperties() {
        refreshJMenuComponents()
    }

    private fun refreshJMenuComponents() {
        val i = menuComponents.size
        println("$i is the length.")
        for (index in 0 until menuComponents.size) {
            val component = menuComponents[index]
            println("Refreshed component: $component")
        }
    }
}

fun main() {

    NPE()
}


text:
Q: Docker Pull Access Denied for Repository does not exist or login required I want to place the existing web api inside the docker container. I added the Docker file through visual studio.
The application build is successful. But when I try to run the docker. It doesn't provide any information.
The docker repository is created

when i run the below cmd it executes and doesn't throw any error

The IOswagger is my application image.
When I run the image without the tag. The command automatically takes the tag of another image and it throws an error saying the repository doesn't exists.

In the docker the image is running.

Docker FIle :
#See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging.

#Depending on the operating system of the host machines(s) that will build or run the containers, the image specified in the FROM statement may need to be changed.
#For more information, please see https://aka.ms/containercompat

FROM mcr.microsoft.com/dotnet/core/aspnet:3.0-nanoserver-1903 AS base
WORKDIR /app
EXPOSE 80

FROM mcr.microsoft.com/dotnet/core/sdk:3.0-nanoserver-1903 AS build
WORKDIR /src
COPY ["aspnetcore-server/src/IO.Swagger/IO.Swagger.csproj", "aspnetcore-server/src/IO.Swagger/"]

RUN dotnet restore "aspnetcore-server/src/IO.Swagger/IO.Swagger.csproj"
COPY . .

WORKDIR "/src/aspnetcore-server/src/IO.Swagger"
RUN dotnet build "IO.Swagger.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "IO.Swagger.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "IO.Swagger.dll"]

When I try to build the application using docker it fails. The build is failed by throwing "Command failed with exit code 1"
I don't know how to proceed further. Not sure whether my application is even running or not.

A: It's a bit late and not exactly the case what you described, but I have faced with the same error when specified in Dockerfile wrong link to docker image like
FROM microsoft-dotnet-aspnet:5.0 AS base
when it should be:
FROM mcr.microsoft.com/dotnet/aspnet:5.0 AS base
or
FROM mcr.microsoft.com/dotnet/core/aspnet:3.1 AS base


text:
Q: Best way to compute the moving average of word vectors in JAX Let say I have a matrix W of shape (n_words, model_dim) where n_words is the number of words in a sentence and model_dim is the dimension of the space where the word vectors are represented. What is the fastest way to compute the moving average of these vectors ?
For example, with a window size of 2 (window length = 5), I could have something like this (which raises an error TypeError: JAX 'Tracer' objects do not support item assignment):
from jax import random
import jax.numpy as jnp

# Fake word vectors (17 words vectors of dimension 32)
W = random.normal(random.PRNGKey(0), shape=(17, 32))

ws = 2          # window size
N = W.shape[0]  # number of words

new_W = jnp.zeros(W.shape)

for i in range(N):
    window = W[max(0, i-ws):min(N, i+ws+1)]
    n = window.shape[0]
    for j in range(n):
        new_W[i] += W[j] / n

I guess there is a faster solution with jnp.convolve but I'm not familiar with it.

A: This looks like you're trying to do a convolution, so jnp.convolve or similar would likely be a more performant approach.
That said, your example is a bit strange because n is never larger than 4, so you never access any but the first four elements of W. Also, you overwrite the previous value in each iteration of the inner loop, so each row of new_W just contained a scaled copy of one of the first four rows of W.
Changing your code to what I think you meant and using index_update to make it compatible with JAX's immutable arrays gives this:
from jax import random
import jax.numpy as jnp

# Fake word vectors (17 words vectors of dimension 32)
W = random.normal(random.PRNGKey(0), shape=(17, 32))

ws = 2          # window size
N = W.shape[0]  # number of words

new_W = jnp.zeros(W.shape)

for i in range(N):
    window = W[max(0, i-ws):min(N, i+ws)]
    n = window.shape[0]
    for j in range(n):
      new_W = new_W.at[i].add(window[j] / n)

and here is the equivalent in terms of a much more efficient convolution:
from jax.scipy.signal import convolve
kernel = jnp.ones((4, 1))
new_W_2 = convolve(W, kernel, mode='same') / convolve(jnp.ones_like(W), kernel, mode='same')

jnp.allclose(new_W, new_W_2)
# True


text:
Q: variable inside custom function how i can access below  alRec variable inside the Ext.Msg function,right now am not able to access.
var alRec = allRecords[i];
prefFlag = true;

Ext.Msg.show({
    title:'Error',
    msg:"SOME MESSAGE",
    buttons: Ext.Msg.OKCANCEL,
    animEl: 'wId',
    icon: Ext.MessageBox.ERROR,
    fn: function(button,alRec) {
        if(button=='ok')
            this.onApply();
        else {
                        alRec.reject();
            return false;
        }
    },
    scope:this
});

A: var alRec = ['a'];
    Ext.Msg.show({
        title:'Error',
        alRec: alRec,
        msg:"SOME MESSAGE",
        buttons: Ext.Msg.OKCANCEL,
        animEl: 'wId',
        icon: Ext.MessageBox.ERROR,
        fn: function(button){
            console.log(this.alRec); //now its accesible
            if(button=='ok')
                this.onApply();
            else
            {
                //sth to do
                return false;
            }
        },
        scope:this
    });


text:
Q: How to implement 3D Touch preview action with left or right swipe? I know how to add UIPreviewActionItem when swipe from the bottom. There is a method previewActionItems(). But how to do the following thing:

A: Left and right swipe is a custom implementation by Apple engineers. Broke my heart when I found that out as well.

A: As Apple's documentation says:

Provide peek quick actions, if appropriate. Within a peek, users can swipe up to reveal actions that are related to the item.

There is nothing about left/right swipe.


text:
Q: How to Use Laravel Query Builder with and Where Clause in PHP? I am trying to ensure that a record exists in the database before performing a user-related action. When I execute the query directly in my PHPMyAdmin like so (for testing purposes).
SELECT * FROM `chat_participants` WHERE `chat_id` = 2 AND `user_id` = 2

I receive the correct record. However, when I try to use the Laravel Query Builder to achieve the same.
dd($this->participants
    ->where('chat_id', '=', 2)
    ->where('user_id', '=', 2)
    ->get()
    ->first());

I get null. Is there a way I can ensure that the record exists in the database using Query Builder? Do I need to declare AND in the Query Builder?
Update: I set the participants variable in my constructor.
public function __construct()
{
    $this->middleware('auth');
    $this->header = DB::table('chat_headers');
    $this->participants = DB::table('chat_participants');
    $this->messages = DB::table('chat_messages');
}

toSql() produces:
select * from chat_participants`
    inner join chat_headers on chat_headers.id = chat_participants.chat_id
    inner join chat_rbac on chat_rbac.id = chat_participants.rbac
 where chat_participants.chat_id = ? and chat_participants.user_id = ?
    and chat_id = ? and user_id = ?

A: Objects are passed by reference in PHP, this means you're passing a pointer to the same Query Builder object everywhere you use the participants property.  So in most cases, you would want to instantiate a new query builder object for each query.
However, PHP does allow for cloning of objects, which would allow you to pass a base query builder and start fresh everywhere you use it:
$query = clone $this->participants;
$query->where(..)->first();

This is an implementation of the Prototype OO pattern, build up a base object and then create a copy of it to do the specifics.
This would be just one way you could avoid hard-coding your table name everywhere you query it.


text:
Q: HTML5 Canvas: Why are these squares not the same size? Recently, I was playing around with the HTML5 Canvas and I ran across the problem seen here - https://jsfiddle.net/6buwndz6/.
Here's the code:
ctx.fillStyle = "#e74c3c";
ctx.beginPath();
ctx.rect(0,0,15,15);
ctx.fill();
ctx.closePath();

ctx.fillStyle = "#e67e22";
ctx.beginPath();
ctx.rect(60,14,75,29);
ctx.fill();
ctx.closePath();

The only differences between the two squares (that I can see) are the colour codes, and the starting position of the x, y, w and h parameters. However, in both cases the w and h parameters are 15 more than the x and y parameters. So, apart from being positioned in different places, they should be the same size (15 x 15), right?
Nope :P
The orange square is significantly bigger than the red one, and I can't see any real reason as to why. Just to clarify, the red square is the intended size.
I'm using Chrome 49 on Mac OS X Yosemite.
Any suggestions?

A: I think that you're thinking the arguments for ctx.rect is x1, y1, x2, y2; but, it is, in fact, as you say: x, y, w, h.
Therefore: 15x15 != 75x29

A: W means width and H means height. Therefore, both cases should be 15
ctx.rect( 0, 0, 15, 15);
ctx.rect( 60, 14, 15, 15);


text:
Q: How can I use onClick On the small screen, it doesn't show/hide. How can I change this code to work on the small screen?
import React from 'react';
import assets from './assets';
import { FaBars, FaFacebook, FaRegHeart, FaInstagram, FaLinkedin, FaStar, FaStarHalf, FaTimes, FaTwitter } from 'react-icons/fa';

var navLinks = document.getElementById('navLinks');
function showMenu() {
    navLinks.style.right = "0";
}
function hideMenu() {
    navLinks.style.right = "-200px";
}

Above var worked a few times mistakenly, but I still did not get it.

export const Home = () => (
    <>

                    <FaTimes class='fa' onClick={showMenu} />

HOME

ABOUT

COURSE

BLOG

CONTACT

                <FaBars class='fa' onClick={hideMenu} />

World's Biggest University

Making website is now one of the easiest thing in the world. You just need to learn HTML, CSS,
Javascript and you are good to go.

                Visit Us to Know More

    </>
)

My CSS file is below.
I've tried many ways but I couldn't.

nav .fa{
  display: none;
}

A: As some people have mentioned before you are not utilising the React library correctly.
The (untested) code below should suit you better. As you can see a state has been used instead of directly changing style properties. I have tried to comment the code as clearly as possible but for more in depth instructions i recommend reading the React docs.
import React, { useState } from 'react';
import assets from './assets';
import { FaBars, FaFacebook, FaRegHeart, FaInstagram, FaLinkedin, FaStar, FaStarHalf, FaTimes, FaTwitter } from 'react-icons/fa';

export const Home = () => {

    // Set state value to keep track of menu open or closed status
    const [navOpen, setNavOpen] = useState(false)

    // Open the active menu
    const open = () => {
        setNavOpen(true)
    }

    // Close the active menu
    const close = () => {
        setNavOpen(false)
    }

    return (
        <>

                        <button onClick={open}>
                            <FaTimes class='fa' />
                        </button>

                        {
                            // Only render the UL node when the navOpen variable is true
                            navOpen && (

HOME

ABOUT

COURSE

BLOG

CONTACT

                            )
                        }

                    <button onClick={close}>
                        <FaBars class='fa' />
                    </button>

World's Biggest University

Making website is now one of the easiest thing in the world. You just need to learn HTML, CSS,
Javascript and you are good to go.

                    Visit Us to Know More

        </>
    )
}


text:
Q: Does a sql server filtered index <> 0 performs differently than > 0? I have a table with an Id column.
This column always hold value >= 0 (there's no constraint to assert this).
I have an index on this column filtered for value > 0.
Could this index perform differently (faster/slower queries?) if the filter was value <> 0
Maybe one is a best practice and the other a bad one...
EDIT, I wrote this script:
-- Structure
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[tst20150513_Src]') AND type in (N'U'))
DROP TABLE [dbo].[tst20150513_Src]
GO

CREATE TABLE tst20150513_Src (
    ID INT NOT NULL
    , CONSTRAINT PK_tst20150513_Src PRIMARY KEY (ID)
)
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[tst20150513_1]') AND type in (N'U'))
DROP TABLE [dbo].[tst20150513_1]
GO

CREATE TABLE tst20150513_1 (
    ID INT NOT NULL
    , CONSTRAINT PK_tst20150513_1 PRIMARY KEY (ID)
)
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[tst20150513_2_1]') AND type in (N'U'))
DROP TABLE [dbo].[tst20150513_2_1]
GO

CREATE TABLE tst20150513_2_1 (
    ID INT NOT NULL
)
GO

CREATE NONCLUSTERED INDEX IDX_tst20150513_2_1 ON tst20150513_2_1 (ID)
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[tst20150513_2_2]') AND type in (N'U'))
DROP TABLE [dbo].[tst20150513_2_2]
GO

CREATE TABLE tst20150513_2_2 (
    ID INT NOT NULL
)
GO

CREATE NONCLUSTERED INDEX IDX_tst20150513_2_2 ON tst20150513_2_2 (ID) WHERE ID <> 0
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[tst20150513_2_3]') AND type in (N'U'))
DROP TABLE [dbo].[tst20150513_2_3]
GO

CREATE TABLE tst20150513_2_3 (
    ID INT NOT NULL
)
GO

CREATE NONCLUSTERED INDEX IDX_tst20150513_2_3 ON tst20150513_2_3 (ID) WHERE ID > 0
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[tst20150513_2_4]') AND type in (N'U'))
DROP TABLE [dbo].[tst20150513_2_4]
GO

CREATE TABLE tst20150513_2_4 (
    ID INT NOT NULL
    , CONSTRAINT CHK_tst20150513_2_4 CHECK (ID <> 0)
)
GO

CREATE NONCLUSTERED INDEX IDX_tst20150513_2_4 ON tst20150513_2_4 (ID) WHERE ID <> 0
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[tst20150513_2_5]') AND type in (N'U'))
DROP TABLE [dbo].[tst20150513_2_5]
GO

CREATE TABLE tst20150513_2_5 (
    ID INT NOT NULL
    , CONSTRAINT CHK_tst20150513_2_5 CHECK (ID > 0)
)
GO

CREATE NONCLUSTERED INDEX IDX_tst20150513_2_5 ON tst20150513_2_5 (ID) WHERE ID > 0
GO

-- Populate
; WITH CTE AS (
    SELECT
        ROW_NUMBER() OVER (ORDER BY [type], [number],[name]) AS n
    FROM master.dbo.spt_values AS T
)
INSERT tst20150513_Src ( ID )
SELECT
    n
FROM CTE WHERE n <= 1000

INSERT tst20150513_2_1 (ID)
SELECT ID FROM tst20150513_Src

INSERT tst20150513_2_2 (ID)
SELECT ID FROM tst20150513_Src

INSERT tst20150513_2_3 (ID)
SELECT ID FROM tst20150513_Src

INSERT tst20150513_2_4 (ID)
SELECT ID FROM tst20150513_Src

INSERT tst20150513_2_5 (ID)
SELECT ID FROM tst20150513_Src
GO

-- Tests
PRINT '
tst20150513_2_1
---------------
'

INSERT tst20150513_1 (ID)
SELECT ID FROM tst20150513_Src
GO

ALTER TABLE tst20150513_2_1 ADD
    CONSTRAINT FK_tst20150513_2_1 FOREIGN KEY (ID) REFERENCES tst20150513_1 (ID) ON DELETE CASCADE
GO

SET STATISTICS IO ON
GO

DELETE FROM tst20150513_1
GO

SET STATISTICS IO OFF
GO

IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_tst20150513_2_1]') AND parent_object_id = OBJECT_ID(N'[dbo].[tst20150513_2_1]'))
ALTER TABLE [dbo].[tst20150513_2_1] DROP CONSTRAINT [FK_tst20150513_2_1]
GO

PRINT '
tst20150513_2_2
---------------
'

INSERT tst20150513_1 (ID)
SELECT ID FROM tst20150513_Src
GO

ALTER TABLE tst20150513_2_2 ADD
    CONSTRAINT FK_tst20150513_2_2 FOREIGN KEY (ID) REFERENCES tst20150513_1 (ID) ON DELETE CASCADE
GO

SET STATISTICS IO ON
GO

DELETE FROM tst20150513_1
GO

SET STATISTICS IO OFF
GO

IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_tst20150513_2_2]') AND parent_object_id = OBJECT_ID(N'[dbo].[tst20150513_2_2]'))
ALTER TABLE [dbo].[tst20150513_2_2] DROP CONSTRAINT [FK_tst20150513_2_2]
GO

PRINT '
tst20150513_2_3
---------------
'

INSERT tst20150513_1 (ID)
SELECT ID FROM tst20150513_Src
GO

ALTER TABLE tst20150513_2_3 ADD
    CONSTRAINT FK_tst20150513_2_3 FOREIGN KEY (ID) REFERENCES tst20150513_1 (ID) ON DELETE CASCADE
GO

SET STATISTICS IO ON
GO

DELETE FROM tst20150513_1
GO

SET STATISTICS IO OFF
GO

IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_tst20150513_2_3]') AND parent_object_id = OBJECT_ID(N'[dbo].[tst20150513_2_3]'))
ALTER TABLE [dbo].[tst20150513_2_3] DROP CONSTRAINT [FK_tst20150513_2_3]
GO

PRINT '
tst20150513_2_4
---------------
'

INSERT tst20150513_1 (ID)
SELECT ID FROM tst20150513_Src
GO

ALTER TABLE tst20150513_2_4 ADD
    CONSTRAINT FK_tst20150513_2_4 FOREIGN KEY (ID) REFERENCES tst20150513_1 (ID) ON DELETE CASCADE
GO

SET STATISTICS IO ON
GO

DELETE FROM tst20150513_1
GO

SET STATISTICS IO OFF
GO

IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_tst20150513_2_4]') AND parent_object_id = OBJECT_ID(N'[dbo].[tst20150513_2_4]'))
ALTER TABLE [dbo].[tst20150513_2_4] DROP CONSTRAINT [FK_tst20150513_2_4]
GO

PRINT '
tst20150513_2_5
---------------
'

INSERT tst20150513_1 (ID)
SELECT ID FROM tst20150513_Src
GO

ALTER TABLE tst20150513_2_5 ADD
    CONSTRAINT FK_tst20150513_2_5 FOREIGN KEY (ID) REFERENCES tst20150513_1 (ID) ON DELETE CASCADE
GO

SET STATISTICS IO ON
GO

DELETE FROM tst20150513_1
GO

SET STATISTICS IO OFF
GO

IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_tst20150513_2_5]') AND parent_object_id = OBJECT_ID(N'[dbo].[tst20150513_2_5]'))
ALTER TABLE [dbo].[tst20150513_2_5] DROP CONSTRAINT [FK_tst20150513_2_5]
GO

And I'm a bit puzzled by the results:
tst20150513_2_1
---------------

(1000 row(s) affected)
Table 'tst20150513_2_1'. Scan count 1, logical reads 5006, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table 'Worktable'. Scan count 2, logical reads 2018, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table 'tst20150513_1'. Scan count 1, logical reads 6, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

(1000 row(s) affected)

tst20150513_2_2
---------------

(1000 row(s) affected)
Table 'tst20150513_2_2'. Scan count 1, logical reads 3004, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table 'Worktable'. Scan count 2, logical reads 2018, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table 'tst20150513_1'. Scan count 1, logical reads 6, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

(1000 row(s) affected)

tst20150513_2_3
---------------

(1000 row(s) affected)
Table 'tst20150513_2_3'. Scan count 1, logical reads 3004, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table 'Worktable'. Scan count 2, logical reads 2018, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table 'tst20150513_1'. Scan count 1, logical reads 6, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

(1000 row(s) affected)

tst20150513_2_4
---------------

(1000 row(s) affected)
Table 'tst20150513_2_4'. Scan count 1, logical reads 5006, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table 'Worktable'. Scan count 2, logical reads 2018, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table 'tst20150513_1'. Scan count 1, logical reads 6, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

(1000 row(s) affected)

tst20150513_2_5
---------------

(1000 row(s) affected)
Table 'tst20150513_2_5'. Scan count 1, logical reads 5006, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table 'Worktable'. Scan count 2, logical reads 2018, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table 'tst20150513_1'. Scan count 1, logical reads 6, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

(1000 row(s) affected)

There are 5006  logical reads for tst20150513_2_1, tst20150513_2_4 and tst20150513_2_5.
Those table have in common that their index either is not filtered, either "combine" perfectly with the "associated" CHECK clause.
I don't get why those have more logical reads than the 2 other tables with indexed filters but no CHECK clause.


text:
Q: Physical interpretation of different selfadjoint extensions Given a symmetric (densely defined) operator in a Hilbert space, there might be quite a lot of selfadjoint extensions to it. This might be the case for a Schrödinger operator with a "bad" potential. There is a "smallest" one (Friedrichs) and a largest one (Krein), and all others are in some sense in between.
Considering the corresponding Schrödinger equations, to each of these extensions there is a (completely different) unitary group solving it.
My question is: what is the physical meaning of these extensions? How do you distinguish between the different unitary groups? Is there one which is physically "relevant"?
Why is the Friedrichs extension chosen so often?

A: The differential operator itself (defined on some domain) encodes local  information about the dynamics of the quantum system . Its self-adjoint extensions depend precisely on choices of boundary conditions of the states that the operator acts on, hence on global  information about the kinematics of the physical system.
This is even true fully abstractly, mathematically: in a precise sense the self-adjoint extensions of symmetric operators (under mild conditions) are classified by choices of boundary data.
More information on this is collected here
http://ncatlab.org/nlab/show/self-adjoint+extension
See the references on applications in physics there for examples of choices of boundary conditions in physics and how they lead to self-adjoint extensions of symmetric Hamiltonians. And see the article by Wei-Jiang there for the fully general notion of boundary conditions.

A: A typical interpretation of the self-adjoint extensions for the free hamiltonian in a line segment is that you get a four parametric family of possible boundary conditions, to preserve unitarity. Some of them just "bounce" the wave, some others "teletransport" it from one wall to the other. So it is also traditional to imagine this segment as a circle where you have removed a point, and then you are in the mood of studying "point interactions" or generalisations of dirac-delta potentials. The topic resurfaces from time to time, but surely some old references can be digged starting from M. Carreau. Four-parameter point-interaction in 1d quantum systems. Journal of Physics A, 26:427, 1993. In some works, I quote also Seba and Polonyi.
Sometimes the extensions are linked to the question of the domain of definition for the operator and then to the existence of anomalies. Here Phys.Rev.D34: 674-677, 1986,
"Anomalies in conservation laws in the Hamiltonian formalism", revisited by the same autor, J G Esteve, later in Phys.Rev.D66:125013,2002 ( http://arxiv.org/abs/hep-th/0207164 ). These topics have been live for years in the university of Zaragoza; some related material, perhaps more about boundary conditions than about extensions, is http://arxiv.org/abs/0704.1084, http://arxiv.org/abs/quant-ph/0609023, http://arxiv.org/abs/0712.4353


text:
Q: Central fibre singularities Let $f:X\to Y $ be a proper surjective holomorphic fibre space where $X,Y $ are projective varieties.

If the central fibre $X_0$ has at worst log terminal singularities,
  then can we say that all other fibres $X_t $ at worst have log
  terminal singularities and $X$ at worst have log terminal singularities?.
  What about the inverse. If $X$ has log terminal singularity then the
  central fibre $X_0$ at worst has log terminal singularity?

A: It could easily happen that $X_0$ has log terminal singularities and $X$ is not log terminal. The standard example is if $f:Y\to X$ is a flipping contraction of a 3-fold over a curve $T$ (where the flipping curve $C$ is contained in the central fiber). The issue is that if $Y_0$ is log terminal, then as $Y_0\to X_0$ is $K_{Y_0}$ negative birational map of surfaces, then $X_0$ also has log terminal singularities (and is even Q-factorial). On the other hand $K_X$ is automatically not Q-Cartier (if it where, then $K_Y=f^*K_X$ and so $K_Y\cdot C=0$ which is impossible). Note however that if you require $X_0$ to be canonical, then so is $X$ (see Theorem 1.4 of  arXiv:math/9809091). Finally, if you assume that $X$ is log terminal, you can deduce almost nothing for $X_0$ (it could be reducible or even non-reduced). However, if you assume that $(X,X_0)$ is plt, then you can deduce that $(K_X+X_0)|_{X_0}=K_{X_0}+B_0$ where $(X_0,B_0)$ is klt (the converse to this statement is also true; it is known as inversion of adjunction; see the book of Kollár-Mori).


text:
Q: Viewport function clips the main map I would like to include an inset map next to a main map. Here is the code that I use:
# Combine crude rate map (inset + main) =====

ut_map_cruderate
print(ut_map,
      vp = viewport(
        x = 0.5,
        y = 0.18,
        width = 0.3,
        height = 0.3))

However, the inset map kept "clipping" into the main map. How do i fix this?


text:
Q: libuv slow in establishing a multiple connections? I am trying to evaluate the performance of libuv because of the promise that it can manage 100,000 of TCP sockets and can generate 10,000 of new TCP sessions/second.
Created the following code snippet based on a gist to validate the performance of libuv. However, when it runs against a server, it's surprisingly slow according to wireshark pcap capture

*

*TCP handshakes were done one after another, I was expecting TCP SYNs to be sent in parallel

*The TCP data was sent after all the sessions were established. I had expected the TCP data to be sent as soon as the TCP handshake is complete.

This test was run on Ubuntu 14.04 (64bit core i7 cpu).
Not sure if there is problem with libuv or with this code snippet.
I know this has some memory leaks, but it doesn't matter since I am only doing evaluation.
#include <stdio.h>
#include <stdlib.h>
#include <uv.h>

//based on https://gist.githubusercontent.com/snatchev/5255976/
//raw/8392c42d719bb775053036e32b21affdf932c1b7/libuv-tcp-client.c
static void on_close(uv_handle_t* handle);
static void on_connect(uv_connect_t* req, int status);
static void on_write(uv_write_t* req, int status);

static uv_loop_t *loop;

static uv_buf_t alloc_cb(uv_handle_t* handle, size_t size) {
  return uv_buf_init(malloc(size), size);
}

void on_close(uv_handle_t* handle)
{
  printf("closed.");
}

void on_write(uv_write_t* req, int status)
{
  if (status) {
    uv_err_t err = uv_last_error(loop);
    fprintf(stderr, "uv_write error: %s\n", uv_strerror(err));
        return;
  }
    printf("wrote.\n");
    free(req);
    //uv_close((uv_handle_t*)req->handle, on_close);
}

void on_read(uv_stream_t* tcp, ssize_t nread, uv_buf_t buf)
{
    printf("on_read. %p\n",tcp);
    if(nread >= 0) {
        //printf("read: %s\n", tcp->data);
        printf("read: %s\n", buf.base);
    }
    else {
        //we got an EOF
    uv_close((uv_handle_t*)tcp, on_close);
    }

    //cargo-culted
    free(buf.base);
}

void write2(uv_stream_t* stream, char *data, int len2) {
    uv_buf_t buffer[] = {
        {.base = data, .len = len2}
    };
    uv_write_t *req = malloc(sizeof(uv_write_t));
    uv_write(req, stream, buffer, 1, on_write);
}

void on_connect(uv_connect_t* connection, int status)
{
    if (status < 0) {
        printf("failed to connect\n"); return;
    }
    printf("connected. %p %d\n",connection, status);

    uv_stream_t* stream = connection->handle;
    free(connection);
    write2(stream, "echo  world!", 12);
    uv_read_start(stream, alloc_cb, on_read);
}

void startConn(char *host, int port) {
    uv_tcp_t *pSock = malloc(sizeof(uv_tcp_t));
    uv_tcp_init(loop, pSock);
    uv_tcp_keepalive(pSock, 1, 60);

    struct sockaddr_in dest = uv_ip4_addr(host, port);

    uv_connect_t *pConn = malloc(sizeof(uv_connect_t));
    printf("allocated %p\n", pConn);
    uv_tcp_connect(pConn, pSock, dest, on_connect);
}

int main(int argc, char **argv) {
    loop = uv_default_loop();
    int i;
    for (i=0; i<10; i++)
        startConn("0.0.0.0", 1234);

    uv_run(loop, UV_RUN_DEFAULT);
}

A: This example is compiled against libuv 0.1.
After it's adapted to compile and run against libuv1.x, it works as expected.  Here is the gist.
There is considerable difference between libuv 0.1 and libuv 1.0.    Hope this version could be helpful to those who are looking for a working example of libuv.c. By the way, there are many good examples in libuv repo in github, check the "test" subdirectory.


text:
Q: Can we change the network structure of Connection strategy in Nearby connections? Can we choose a specific wifi channel in nearby connection api or not...?
If so how...?
Because we want to select specific channels in nearby connection for different purposes, as some channels are Congested and connection establishment between devices is slow, so, if possible we would like

*

*A channel to Advertise/Discover

*A channel to exchange the metadata files after the discovery/advertising

*A channel to exchange files like images,videos etc

A: No, you do not get access to the underlying Wifi stack used by Nearby Connections. The goal is to be a simple abstraction layer, so we purposefully avoid exposing too many knobs to tweak and turn.
I can file a bug internally to more optimally choose the Wifi channel. If you have more specifics (eg. these channels are typically congested), I can attach that to the bug as well.


text:
Q: Multiple Named Queries on Spring I created a Spring project and I would like to create multiple queries on a single file. After googling, I found this link https://www.petrikainulainen.net/programming/spring-framework/spring-data-jpa-tutorial-creating-database-queries-with-named-queries/
So, I should create the file orm.xml:
<?xml version="1.0" encoding="UTF-8"?>
<entity-mappings
        xmlns="http://java.sun.com/xml/ns/persistence/orm"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm http://java.sun.com/xml/ns/persistence/orm_2_0.xsd"
        version="2.0">

    <named-query name="Todo.findByTitleIs">
        <query>SELECT t FROM Todo t WHERE t.title = 'title'</query>
    </named-query>
</entity-mappings>

Then, the interface TodoRepository.java
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.Repository;

import java.util.List;

interface TodoRepository extends Repository<Todo, Long> {

    @Query(nativeQuery = true)
    public List<Todo> findByTitleIs();
}

The spring.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="employeeDAO" class="com.journaldev.spring.jdbc.dao.EmployeeDAOImpl">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <bean id="employeeDAOJDBCTemplate" class="com.journaldev.spring.jdbc.dao.EmployeeDAOJDBCTemplateImpl">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <bean id="todoRepositoryBean" class="com.journaldev.spring.jdbc.dao.TodoRepositoryBeanImpl">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">

        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/springdb" />
        <property name="username" value="root" />
        <property name="password" value="root" />
    </bean>

</beans>

The class SpringMain.java is:
public class SpringMain {

    public static void main(String[] args)
    {
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
        EmployeeDAO employeeDAO = ctx.getBean("todoRepositoryBean", EmployeeDAO.class);
        List<Employee> les = employeeDAO.getAll();
        System.out.println("The list size is: + les.size()");
        ctx.close();
    }
}

I think it was useful but I found a problem: How can I use the named query Todo.findByTitleIs on main class?

A: The tutorials of Petri Kainulainen are really good and you should achieve your goal by reading this one:
https://www.petrikainulainen.net/programming/spring-framework/spring-data-jpa-tutorial-part-eight-adding-functionality-to-a-repository/
He explaines how to implement the TodoRepository class.
To use queries defined in your repository, if you are developing a rest web app, you could use a @Controller class to handle the single functionalities (e.g. TodoController). In the controller you can autowire the repository:
@Autowired
private TodoRepository todoRepository;
and then use it in your methods:
public void doSomething() {
   List<Todo> todoList = todoRepository.findByTitleIs();
}
Remember that you can autowire beans only in spring managed classes (Repository, Service, Controller, Component, Configuration ecc)
Otherwise you could get the repository directly from the ApplicationContext, but it's not recommended:
Why is Spring's ApplicationContext.getBean considered bad?
Personally i use this method only for testing purpose (to create a main test class).
Then i suggest you to write your queries directly in the repository interface, to me it's much simplier (this way you can avoid using the orm.xml file). For example:
@Repository
public interface TodoRepository extends JpaRepository<Todo, Long> {

       // define your custom query
        @Query("SELECT t FROM Todo t WHERE t.title = :title")
        public List<Todo> findByTitleIs(@Param("title") String title);

        // write here all the Todo queries
    }

You can also use the query creation from method names mechanism, and write the previous query like this:
public List<Todo> findByTitle(String title);

http://docs.spring.io/spring-data/jpa/docs/1.4.3.RELEASE/reference/html/jpa.repositories.html


text:
Q: Change to jdk 7 in eclipse(sts) How do I switch project from JDK 6 to 7, I know I am not using it because switch doesn't accept String.
In build path I have jre 7 in compiler settings I have 1.7 , everywhere and it still doesn't work. I use Spring Tool Suite(Eclipse based) latest version which officially supports Java 7.
And in project facets I also have 1.7. Why it has to be so bloody difficult.
And in .ini I have perfectly correct C:\Program Files\Java\jdk1.7.0\bin\javaw.exe
-startup
And I am sure my IDE supports 7 because whenever I create new project I have not syntax errors with String switch statement.
And my JAVA HOME set to JDK 1.7 :-)
UPDATE: The problem only happens with projects of Spring nature.
UPDATE 2: Happens with template Spring MVC project, Spring Hibernate template apparently works with Java 7.
Totally confused.

A: When I start a new Java project  in Eclipse Indigo, eclipse tells me that the compiler compliance level 1.7 is not supported:

It is not possible to change that from inside eclipse, the properties dialog shows that:

So as a result, it is not possible to use the new switch statement with Strings in it:

See the "Eclipse Forums Post" for more information about the topic. It seems that it will come only with the next eclipse version.

A: In window / preferences / Installed JREs you need to have the JDK1.7 as the default set up. Additionally in Project / Properties Java Compiler it should be also set (or disable the project specific settings)
UPDATE :
In my .settings folder there is a file called org.eclipse.wst.common.project.facet.core.xml
<?xml version="1.0" encoding="UTF-8"?>
<faceted-project>
  <fixed facet="wst.jsdt.web"/>
  <installed facet="java" version="1.6"/>
  <installed facet="jst.web" version="2.4"/>
  <installed facet="wst.jsdt.web" version="1.0"/>
</faceted-project>

and contains some rather suspicious values. Not sure it matters, but worth trying to close the project change it then reopen the project. If that doesnt help then search for the string 1.6 in all files in your project

A: Compare .classpath and .project files between your simple Java projects and Spring projects. Sometimes the Nature or other project setting can be set differently.


text:
Q: Backtracking for Knapsack I need to do use backtracking to solve a Knapsack problem. This is an example of what I might have to do for my problem. My question is, how do I know the bounds? I understand that the bound for the root node is $115 because it is the sum of all values. But what I don't understand is how the right child of the root has a bound of $82.
I found this text explaining what it means, but I am still confused:
For a maximization problem the bound is an upper bound,
    – the largest possible solution that can be achieved by
      expanding the node is less or equal to the upper bound

A: I have figured it out:
bound = profit  +  p1 + p2 + (C - 7 ) * p3 / w3 = $0 + $40 + $30 + (16 -7) X $50/10 = $115


text:
Q: Web Scrapping - Python Quando Header Cache-Control é private, isso quer dizer que não é possível acessar formulário pelo Requests? Ideia era coletar da fonte Pública, os dados médios do combustível de todas as cidades de todos os estados mas não encontro Parâmetros para aplicar.
Fonte: https://preco.anp.gov.br/include/Resumo_Por_Estado_Index.asp

A: Quando o cabeçalho cache-control possui o valor private. Isso significa que uma parte ou a resposta da requisição (completa) não deve utilizar um cache compartilhado, quer dizer que apenas um usuário pode ter acesso a esse cache, entenda como um cache exclusivo para um indivíduo, outro usuário em outra sessão não pode receber o mesmo cache (teoricamente) pelo servidor da aplicação.
Ainda na documentação é dito que o uso da palavra private só significa que a resposta não deve ser compartilhada em cache, e não tem relação com o fato da informação ser restrita (privacidade da informação).
Segundo a referência. Estando no link da referência, procurar por: 14.9.1 What is Cacheable


text:
Q: How to make click on button send me to another url So I need to display Home.js at localhost/posts but when i click at button it displays info at the auth.js url
how to link button so that if login info is correct it goes to "localhost/posts" and not render its info at base url
auth.js
const Auth = () => {
  const { Userr } = useContext(Gloabaldata);
  const login = async (e) => {
    e.preventDefault();
    signInWithEmailAndPassword(auth, email, password)
      .then((userCredential) => {
        const user = userCredential.user;
      })
      .catch((error) => {});
  };

  return (
    <>
      {Userr ? (
        <>
          <Home />
        </>
      ) : (
        <>
              <input
                type="email"
                placeholder="Email Address"
                onChange={(event) => {
                  setregisterEmail(event.target.value);
                }}
              />

              <input
                type="password"
                placeholder="Password"
                autoComplete="on"
                onChange={(event) => {
                  setregisterPassword(event.target.value);
                }}
              />
                  <button onClick={login} className="sign-in">
                    SIGN IN
                  </button>
                  <button className="switchmode">

dont have a ACCOUNT ? SIGN UP

                  </button>
            </form>

        </>
      )}
    </>

export default Auth;

A: I have two ways you could achieve navigation in your react app, the code for which will be written in the handler for your onClick function of the button.
Method 1
This is the beat way to do client side routing in react apps which is to use react-router-dom package. You can find out more about it in the official docs here
Method 2
This is not preferable. Use this if there is no state that you want to preserve between the two location. You can use the property of the window object by writing out window.location = "some URL"

A: if i understood you question correctly, you want to redirect user once authentication succeeds right ?. then use useNavigate hook.
import { useNavigate } from 'react-router-dom'

function AuthComponent() {
  const navigate = useNavigate()

  //...
  //...
  signInWithEmailAndPassword(auth, email, password)
    .then((userCredential) => {
      const user = userCredential.user
      navigate('/posts')
    })
    .catch(console.error)

  //...
}


text:
Q: What is the purpose of lower bounded wildcard in Function.class? In Function.class from Java8, we have:
default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
    Objects.requireNonNull(before);
    return (V v) -> apply(before.apply(v));
}

Compose accepts:
Function<? super V, ? extends T> before

Rather than:
Function<V, ? extends T> before

Is there any plausible situation in which the fact that "V" is lower bounded matters?

A: The ? super allows the returned Function's input type (V) to be different from the arguments input type.
For example, this compiles with the ? super version but not the alternate one.
Function<Object, String> before = Object::toString;
Function<String, Integer> after = Integer::parseInt;
Function<Integer, Integer> composed = after.compose(before);


text:
Q: How to make a Loop in an If-Statement Short explanation: There are 3.Letter Templates and i want them to print per Button. But the main problem here is, that the Code is Printing the Template for every Person in the Worksheet also if the Person already had a Letter. It should look something like this.
-If the selected letter in "G3" is 1. Letter then send them only to People where the Cell Range in "Z" is Empty
-If the selected letter in "G3" is 2. Letter then send them only to People where the Cell in Range "Z" is 1.Letter
-If the selected letter in "G3" is 3. Letter then send them only to People where the Cell in Range "Z" is 2.Letter
What do i need to write right here?
Thank you for your answer in Advance!

https://i.stack.imgur.com/1NRbv.png
Option Explicit
Sub CreateWordDocuments()
Dim CustRow, CustCol, LastRow, TemplRow, DaysSince, FrDays, ToDays As Long
Dim DocLoc, TagName, TagValue, TemplName, FileName As String
Dim CurDt, LastAppDt As Date
Dim OutApp, OutMail As Object
Dim WordContent As Word.Range
Dim WordDoc As Word.Document
Dim WordApp As Word.Application

With Tabelle1

    If IsEmpty(Range("G3").Value) = True Then
    MsgBox "Bitte wählen sie eine Vorlage aus"
    .Range("G3").Select
    Exit Sub
    End If
    TemplRow = .Range("B3").Value
    TemplName = .Range("G3").Value
    FrDays = .Range("L3").Value
    ToDays = .Range("N3").Value
    DocLoc = Tabelle2.Range("F" & TemplRow).Value

    On Error Resume Next
    Set WordApp = GetObject("Word.Application")
    If Err.Number <> 0 Then
    Err.Clear
    Set WordApp = CreateObject("Word.Application")
    WordApp.Visible = True
    End If

    ***LastRow = .Range("E9999").End(xlUp).Row
        For CustRow = 8 To LastRow
            DaysSince = .Range("P" & CustRow).Value
            If TemplName <> .Range("Z" & CustRow).Value And DaysSince >= FrDays And DaysSince <= ToDays Then
               Set WordDoc = WordApp.Documents.Open(FileName:=DocLoc, ReadOnly:=False)
                For CustCol = 5 To 26
                    TagName = .Cells(7, CustCol).Value
                    TagValue = .Cells(CustRow, CustCol).Value
                    With WordDoc.Content.Find
                        .Text = TagName
                        .Replacement.Text = TagValue
                        .Wrap = wdFindContinue
                        .Execute Replace:=wdReplaceAll
                    End With***

                Next CustCol
            If .Range("I3").Value = "PDF" Then
                FileName = "Filename" & "\" & .Range("H" & CustRow).Value & " " & .Range("G" & CustRow).Value & " " & .Range("G3").Value & ".pdf"
                WordDoc.ExportAsFixedFormat OutputFileName:=FileName, ExportFormat:=wdExportFormatPDF
                WordDoc.Close False
            Else:
                FileName = ThisWorkbook.Path & "\" & .Range("H" & CustRow).Value & "_" & .Range("G" & CustRow).Value & ".docx"
                WordDoc.SaveAs FileName

            End If
            .Range("Z" & CustRow).Value = TemplName
            .Range("AA" & CustRow).Value = Now
        If .Range("P3").Value = "Email" Then
            Set OutApp = CreateObject("Outlook.Application")
            Set OutMail = OutApp.CreateItem(0)
            With OutMail
                .To = Tabelle1.Range("K" & CustRow).Value
                .Subject = "Hallo, " & Tabelle1.Range("F" & CustRow).Value & "Test Test Test"
                .Body = "Hallo, " & Tabelle1.Range("F" & CustRow).Value & "Test Test Test Test"
                .Attachments.Add FileName
                .Display
            End With

        Else:
        WordDoc.PrintOut
        WordDoc.Close
        End If
        Kill False '(FileName)
        End If

    Next CustRow
    WordApp.Quit
End With
End Sub

A: Try the following: (not tested)
Sub CreateWordDocuments()
Dim CustRow As Long, CustCol As Long, LastRow As Long, TemplRow As Long, DaysSince As Long, FrDays As Long, ToDays As Long
Dim DocLoc As String, TagName As String, TagValue As String, TemplName As String, FileName As String
Dim CurDt As Date, LastAppDt As Date
Dim OutApp As Object, OutMail As Object
Dim WordContent As Word.Range
Dim WordDoc As Word.Document
Dim WordApp As Word.Application

'*~
Dim sLastSentTemplate As String

With Tabelle1

    If IsEmpty(Range("G3").Value) = True Then
    MsgBox "Bitte wählen sie eine Vorlage aus"
    .Range("G3").Select
    Exit Sub
    End If
    TemplRow = .Range("B3").Value
    TemplName = .Range("G3").Value
    FrDays = .Range("L3").Value
    ToDays = .Range("N3").Value
    DocLoc = Tabelle2.Range("F" & TemplRow).Value

    '*~ workout the last sent template name
    '*  this is what you'll be searching for in column Z
    sLastTemplateTarget = GetLastSentTemplate(TemplName)

    On Error Resume Next
    Set WordApp = GetObject("Word.Application")
    If Err.Number <> 0 Then
    Err.Clear
    Set WordApp = CreateObject("Word.Application")
    WordApp.Visible = True
    End If

    '***LastRow = .Range("E9999").End(xlUp).Row
    '*~
    LastRow = .Cells(.Rows.Count, "E").End(xlUp).Row

        For CustRow = 8 To LastRow
            DaysSince = .Range("P" & CustRow).Value
            '*~ changed TemplName to sLastSentTemplate
            If sLastSentTemplate = .Range("Z" & CustRow).Value And DaysSince >= FrDays And DaysSince <= ToDays Then
               Set WordDoc = WordApp.Documents.Open(FileName:=DocLoc, ReadOnly:=False)
                For CustCol = 5 To 26
                    TagName = .Cells(7, CustCol).Value
                    TagValue = .Cells(CustRow, CustCol).Value
                    With WordDoc.Content.Find
                        .Text = TagName
                        .Replacement.Text = TagValue
                        .Wrap = wdFindContinue
                        .Execute Replace:=wdReplaceAll
                    End With '***

                Next CustCol
            If .Range("I3").Value = "PDF" Then
                FileName = "Filename" & "\" & .Range("H" & CustRow).Value & " " & .Range("G" & CustRow).Value & " " & .Range("G3").Value & ".pdf"
                WordDoc.ExportAsFixedFormat OutputFileName:=FileName, ExportFormat:=wdExportFormatPDF
                WordDoc.Close False
            Else:
                FileName = ThisWorkbook.Path & "\" & .Range("H" & CustRow).Value & "_" & .Range("G" & CustRow).Value & ".docx"
                WordDoc.SaveAs FileName

            End If
            .Range("Z" & CustRow).Value = TemplName
            .Range("AA" & CustRow).Value = Now
        If .Range("P3").Value = "Email" Then
            Set OutApp = CreateObject("Outlook.Application")
            Set OutMail = OutApp.CreateItem(0)
            With OutMail
                .To = Tabelle1.Range("K" & CustRow).Value
                .Subject = "Hallo, " & Tabelle1.Range("F" & CustRow).Value & "Test Test Test"
                .Body = "Hallo, " & Tabelle1.Range("F" & CustRow).Value & "Test Test Test Test"
                .Attachments.Add FileName
                .Display
            End With

        Else:
        WordDoc.PrintOut
        WordDoc.Close
        End If
        Kill False '(FileName)
        End If

    Next CustRow
    WordApp.Quit

    '*~ cleanup after finishing
    Set WordApp = Nothing
    Set OutApp = Nothing
End With
End Sub

'*~
Function GetLastSentTemplate(sTemplate As String) As String
    Dim lPrefixNumber As Long

    If Len(sTemplate) > 0 Then
        lPrefixNumber = Val(Left(sTemplate, InStr(sTemplate, ".") - 1))
        If lPrefixNumber > 1 Then
            GetLastSentTemplate = Replace(sTemplate, lPrefixNumber, lPrefixNumber - 1)
        End If
    End If
End Function


text:
Q: Java - select from array of values I was wondering if it is possible to do a select * where value is in Java String[] or do I need to build a string of values from the string array first?
I am trying to find the best way of doing this technically without singular selects or building a string of values from the array.
Thanks for your time.
String[] lookupValues = new String[]{"1", "2", "3", "4"};
Select * from database where value in (lookupvalues)

A: try Arrays.toString(lookupvalues) or write a utility function.
    public String toString(String[] values, boolean addQuotes) {

        StringBuilder buff = new StringBuilder();
        for(String value : values) {
            if(addQuotes) {
                buff.append(String.format("\"%s\"", value)).append(",");
            } else {
                buff.append(value).append(",");
            }
        }
        buff.deleteCharAt(buff.length()-1); // delete the last comma
        return buff.toString();
    }

A: I know that this is not a direct answer to your question considering only arrays. I suggest you to use Guava since it offers a implementation of filter on Java Collections. Using proven libraries will give you flexibility if you use different kind of filters.
You can easily convert your array into proper collection
String[] lookupValues = new String[]{"1", "2", "3", "4"};
List<String> list = new ArrayList<String>(Arrays.asList(lookupValues));

And filter it with Guava filters:
Collection<String> filtered = Collections2.filter(list,
    Predicates.containsPattern("3"));
print(filtered);

will find
3

If you want filtered collection as a list, you can use this something like this from Guava:
List<String> filteredList = Lists.newArrayList(Collections2.filter(
    list, Predicates.containsPattern("3")));

A: Are you looking to search for a string in array? If yes, you might want to look at Collections.binarySearch() or Arrays.binarySearch() - but please not that the collections or arrays need to be sorted before doing binary search