text:
Q: Assign the value to variable in 2 different sub and call the variable based on the value in perl I need help in calling the value from the variable from 2 different subroutines and assigning the value based on input.
For example: I have 3 different subroutines named sub xxx, sub yyy and sub execute. Two subroutines named as xxx and yyy will be defined as the input of the value. The execute sub will take the input based on the value supplied while executing main.pl:
sub xxx
{
    my $input = "repository_1";
}

sub yyy
{
    my $input = "repository_2";
}

sub execute
{
    $output=$input;
    print "This is the Repository connected : $output";
}

When I run the main.pl script, it will call either sub xxx or sub yyy based on the input, and it will execute the output if repository_1 or repository_2.
For example, if I run $main.pl xxx, I am able to connect to sub xxx and skip sub yyy. But I want the sub execute to take the input from sub xxx as repository_1. And so that I can display the $output of the repository like this:
$ main.pl xxx
This is the Repository connected : repository_1

A: The issue with your code is the my $input lines create variables that are local to the xxx and yyy functions. That means $input will not have any value when you use it in the execute function.
Running your code with use strict and use warnings will show the problem
use strict;
use warnings;

sub xxx
{
    my $input = "repository_1";
}

sub yyy
{
    my $input = "repository_2";
}

sub execute
{
    my $output = $input;
    print "This is the Repository connected : $output\n";
}

outputs
Global symbol "$input" requires explicit package name (did you forget to declare "my $input"?) at try.pl line 16.

A very quick fix is to declare $input at a global scope and use @ARGV to trigger the calling of xxx or yyy.
use strict;
use warnings;

my $input;

sub xxx
{
    $input = "repository_1";
}

sub yyy
{
    $input = "repository_2";
}

sub execute
{
    my $output = $input;
    print "This is the Repository connected : $output\n";
}

xxx() if $ARGV[0] eq 'xxx';
yyy() if $ARGV[0] eq 'yyy';

execute();

$ perl main.pl xxx
This is the Repository connected : repository_1

NOTE: the use of @ARGV in the code above is purely to create a self-contained script that allows xxx or yyy to be executed on demand. The real code should not only this technique if the control of xxx and yyy needs to be controlled from the command line.
Recommend that all you Perl code includes the use strict and use warnings. It catches issues like this for for you for free.
Without knowing more about your script, it is difficult to make any other recommendations.

A: A typical use for a dispatch table†, so that we can call the right function based on input (or perhaps other key words but without having to hardcode it)
use warnings;
use strict;
use feature 'say';

my $input = shift // die "Need input\n";

sub xx
{
    #say "In xx(), my input: @_";
    # ... work out output:
    my $output = "repository_1";
    return $output;
}

sub yy
{
    #say "In yy(), my input: @_";
    # ...
    my $output = "repository_2";
    return $output;
}

sub execute
{
    my @output = @_;
    print "This is the Repository connected : @output\n";
}

my %dispatch = ( xx => \&xx, yy => \&yy );

# Is there a function to dispatch to for the given input?
my $call_sub = $dispatch{$input} // die "Input ($input) not supported";

execute( $call_sub->() );

Can add more sophisticated handling for unsupported input.
Prints

> perl dispatch_ex.pl yy
This is the Repository connected : repository_2

†  In Perl this is normally implemented as a hash which has code references for values and their keys are suitable names that allow us to retrieve them as needed.
A code reference is either a reference to a named function, as used here, or it is an anonymous subroutine
my $code_reference = \&name_of_some_function;
# or
my $code_reference = sub { ... };

This is then a scalar like any other, that can be passed around, stored in arrays or hashes (as a value, as having it as a key -- even though technically allowed -- wouldn't make sense).
Note that it is the function name, no parenthesis. Then it is called (dereferenced) as
$code_reference->( @arguments );

If it is called without any arguments we still need (empty) parenthesis.
Documentation: a tutorial perlreftut and a reference perlref, and perlsub.


text:
Q: Need to split string by "," but not by "\," using regular expressions something like this [^\][,] divides the string as needed, but removes the last character.
String example: Id=000243DE,Price=0,Weight=1,Author=Mar\,obar Sul,Skill=Athletics;"
https://regex101.com/r/PxbTYd/24

A: Perhaps you are looking for a comma, but not if it is preceded by a slash:
(?<!\\),

The thing in brackets is a negative lookbehind - if a slash is present it causes matching the comma to fail. The slash is doubled as an escape. If you're putting this into a C# string you'll need a normal string with 4 slashes, or an @string with 2 slashes

redpajama_set_name: RedPajamaStackExchange


text:
Q: Linux intranet networking I want to set up a private network not connected to the Internet. I have a computer running Ubuntu Server 13.10 which I would like to function as a web server accessible from the other computers on the network, all of which are running Ubuntu Desktop 13.10. How should I go about setting up the networking? (I.e. /etc/network/interfaces on the server and the GUI config for the clients.) I need the computers to all be able to communicate.
I can deal with setting up static IP's (not using DHCP). All of the computers are connected with a switch.

A: The job is already done - with a normal setup you can already contact the other machines connected to the same switch by simply knowing their IP address. To find this, simply open a shell and type ip addr. This will show a listing with lots of information, of which the address to the current machine is four numbers separated by dots, typically starting with either 10.0 or 192.168. To verify that you're able to connect to another machine, simply run ping 192.168.x.y (replacing the address with the real one) to check that it's reachable.
Once you've set up a web server on one of the machines, you can simply go to http://192.168.x.y to see the web site.
With regard to security, most home routers will be configured by default to not allow any connections originating from the Internet into your house. You should verify this in the router configuration.


text:
Q: ng-include in angularjs throws error I have this code:
<!DOCTYPE HTML>
<html>
    <head>
        <script src="angular.js"></script>
        <script src="angularmy.js"></script>
        <link rel="stylesheet" href="angular.css"/>
    </head>
    <body ng-app="myMod" ng-controller="myCont">
        <div ng-include="'angular3.html'">
        </div>
    </body>
</html>

All the files are in the same folder, even angular3.html but when I try to run it gives me this error :

Error: NETWORK_ERR ([arguments not
  available])@file://localhost/C:/Users/amondapr/Desktop/html/angularjs/ng-include/angular.js:12014
  sendReq([arguments not
  available])@file://localhost/C:/Users/amondapr/Desktop/html/angularjs/ng-include/angular.js:11776
  serverRequest([arguments not
  available])@file://localhost/C:/Users/amondapr/Desktop/html/angularjs/ng-include/angular.js:11571
  processQueue([arguments not
  available])@file://localhost/C:/Users/amondapr/Desktop/html/angularjs/ng-include/angular.js:16383
  ([arguments not
  available])@file://localhost/C:/Users/amondapr/Desktop/html/angularjs/ng-include/angular.js:16399
  ([arguments not
  available])@file://localhost/C:/Users/amondapr/Desktop/html/angularjs/ng-include/angular.js:17682
  ([arguments not
  available])@file://localhost/C:/Users/amondapr/Desktop/html/angularjs/ng-include/angular.js:17495
  ([arguments not
  available])@file://localhost/C:/Users/amondapr/Desktop/html/angularjs/ng-include/angular.js:17790
  bootstrapApply([arguments not
  available])@file://localhost/C:/Users/amondapr/Desktop/html/angularjs/ng-include/angular.js:1761
  invoke([arguments not
  available])@file://localhost/C:/Users/amondapr/Desktop/html/angularjs/ng-include/angular.js:4718

Has anyone else faced this problem , if yes then how to correct it ?

A: You have to run a local http server.
Easiest way is using python -m http.server (with Python 3) running in application folder.
Then you can just access http://localhost:8000

A: If you are on Mac you can use MAMP


text:
Q: Calling javascript from html button A quick summary of what I am trying to do. I am trying to make a webpage that receives a list from my python server using flask. It then adds each element of the list with a checkbox form. After that using javascript I will figure out which checkboxes have been checked and return the string to the flask server. I've tried to implement it and so far the checkbox list creation works. I just can't figure out how to call the javascript from the html button. I tried to use onClick= "function" but it doesn't seem to work.
{% extends "layout.html" %}
{% block content %}

Courses

{% for i in class_name %}

{{i.name.tagline}}	<input       type="checkbox" name="ischecked">

  {% endfor %}

<input type="button" id ="button" value = "advise" />

endpage

{% endblock %}`

A: I would first recommend placing your script below the #button button, this way the element in the DOM is loaded first. Next onclick is formatted like this in native JavaScript:
obj.onclick = function(){ ... };

So you want to format it like this:
document.getElementById("button").onclick = function() {
    getChecks();
};


text:
Q: .NET Core Identity and Simple Injector. Crosswire not working I am using simple injector (4.8.1) on a project that uses asp.net core identity. I tried to crosswise UserManager but I got an error saying
 No service for type 'Microsoft.AspNetCore.Identity.UserManager`1[Tenancy.Core.Domain.AppUser]' has been registered."
the SimpleInjectorConfig class is:
public static class SimpleInjectorConfig
{
    private static Container _container;

    public static void ConfigureServices(IServiceCollection services, IConfiguration config,
        IWebHostEnvironment env)
    {
        _container = new Container();

        _container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle();

        _container.ConfigureCore(config, env);

        _container.RegisterInitializer<BaseApiController>(controller =>
        {
            controller.Mediator = _container.GetInstance<IMediator>();
        });

        services.AddSingleton(_container);
        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

        services.AddControllers();

        services.AddLogging();
        // Sets up the basic configuration that for integrating Simple Injector with
        // ASP.NET Core by setting the DefaultScopedLifestyle, and setting up auto
        // cross wiring.
        services.AddSimpleInjector(_container, options =>
        {
            // AddAspNetCore() wraps web requests in a Simple Injector scope and
            // allows request-scoped framework services to be resolved.
            options
                .AddAspNetCore()
                .AddControllerActivation();
            options.AddLogging();
            options.CrossWire<UserManager<AppUser>>();
        });
    }

    public static void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseSimpleInjector(_container);
        app.UseRouting();
        app.UseAuthorization();
        app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            IdentityModelEventSource.ShowPII = true;
        }
        //app.UseHttpsRedirection();

        _container.Verify();
    }
}

and I called it in my Startup.cs file
 public class Startup
{
    public IConfiguration _configuration { get; }
    public IWebHostEnvironment _env { get; }

    public Startup(IConfiguration configuration, IWebHostEnvironment env)
    {
        _configuration = configuration;
        _env = env;
    }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        SimpleInjectorConfig.ConfigureServices(services, _configuration, _env);
        CorsConfig.ConfigureServices(services);
        DatabaseConfig.ConfigureServices(services, _configuration);
        MvcConfig.ConfigureServices(services);
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        SimpleInjectorConfig.Configure(app, env);
        CorsConfig.Configure(app, _configuration);
        MvcConfig.Configure(app);
    }
}

The configurations have their own class and called in the Startup called in the Startup class just to keep it clean, SimpleInjectorConfig is the config class for simple injector.


text: Q: Firebase_core:compileDebugJavaWithJavac' > Failed to calculate the value of task ':firebase_core:compileDebugJavaWithJavac' property 'options.generate The app was working fine a few months ago but now, when I run it I got this error. AndroidX is enabled, flutter clean and pub get multiple times, update and downgraded flutter including firebase auth and core but, no change. Rest of the error is options.generatedSourceOutputDirectory'. However it runs on web alright but on android it shows this error.


text:
Q: Data Labelling in Azure - Images not sorted I am labelling image data using Azure Data Labelling service.
My images are sorted in a blob container.
I would like to tag the images in the order they are sorted (which is the chronological order). However, Azure seems to mix them before showing them up.
Does anyone know how to configure that?
Thanks in advance.

A: What ever may be the name of the image we uploaded, but when we upload image into the datastore it will directly rename all the images and it will show in an ascending order by creation date. The order of images will be based on the size of the image which we uploaded. The final set of images will be based on the ascending order of the labeled duration taken to label the data.

It is not an issue of sorting. It will be taken into consideration according to the size of image when the time of upload and then the time taken to label the dataset images.

A: This is by design to reduce bias by the labeler/analyst


text:
Q: Modifying plainurl bst file to add other preprint servers I'm rather new to this and I'm trying to modify the standard plainurl bst file to add other links on top of the usual ones (arxiv/doi/pubmed/url).
By mimicking exactly what appears in the file I'm able to do so, but the preprint server I'd like to resolve needs a final '/' on the url otherwise the page appears to be non-existent.
Specifically, other than the pieces I had to define in ENTRY, STRINGS etc. needed, I have
FUNCTION {format.newserver}
{ newserver empty$
    { "" }
    { newserverprefix number * newserverurl number * make.href }
  if$
}

which in the bibliography prints me newserverprefix:number hyperreff'ed to http://newserverurl/number.
I would like to be it hyperreff'ed to "http://newserverurl/number/". How can I achieve it?

A: Without a proper example to test it is hard to say anything for sure, but if all you want to do is to add a trailing /, then you can use "/" * after newserverprefix number * to add to the printed text and/or after newserverurl number * to add to the actual URL:
FUNCTION {format.newserver}
{ newserver empty$
    { "" }
    { newserverprefix number * "/" * % This adds / to the printed text
         newserverurl number * "/" * % This adds / to the actual URL
      make.href }
  if$
}

An explanation:
The BibTeX language usees Reverse Polish Notation (RPN), or Postfix Notation, which means that you add items to a stack, and then use operators to do something on that stack.
The format.newserver function adds newserver to the stack and then uses the  empty$ function. This function will test if the topmost item of the stack is empty (what a surprise!) and will leave the result on the top of the stack.
The function then adds two more items to the stack: "" and newserverprefix number * newserverurl number * make.href, and then uses the if$ function. This function will take three items from the top of the stack and checks if the third (top-down) is true. If so, the second item is put back on the stack, otherwise the first.
In case the newserver is empty, the function returns "", so we know that the entire function should only return a string. In case newserver isn't empty, then newserverprefix number * newserverurl number * make.href is used.
That sequence puts newserverprefix and number on the stack and concatenates both strings with *. It then puts newserverurl and  number on the stack and concatenates these with *. Then make takes the topmost two items on the stack and writes the URL. The second item (top-down) is the text to be printed, and the first item is the actual URL.
So to add a trailing / you need to add another item to the stack, the string "/", and concatenate it with the URL text and/or the URL with a *:
newserverprefix % add newserverprefix
number          % add number
*               % concatenate
"/"             % add "/"
*               % concatenate
newserverurl    % add newserverurl
number          % add number
*               % concatenate
"/"             % add "/"
*               % concatenate
make.href       % make the hyper-reference


text:
Q: google datastore global connection How would you declare a global for a datastore client?
So far, I have:
var (
    db     driver.Conn
    ctx    context.Context
    client datastore.Client
)

ignore the db. That's for my global db conn.
func bootstrap() {
    ctx = context.Background()
    pId := ProjectId
    var err error
    client, err = datastore.NewClient(ctx, pId)
    if err != nil {
        fmt.Printf("caught error:%v\n", err)
    }

}

My error is:
cannot assign *"cloud.google.com/go/datastore".Client to client (type "cloud.google.com/go/datastore".Client) in multiple assignment

A: Change client datastore.Client to client *datastore.Client.
Your error message says it all:
cannot assign *"cloud.google.com/go/datastore".Client to client (type "cloud.google.com/go/datastore".Client) in multiple assignment

Condensing it a bit...
cannot assign *ds.Client to client (type ds.Client)...
  pointer ━━━━┷━━━━━━━━┙                 │       │
  plain type ━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━┙

Note that the first type is a pointer, denoted by the * character and the second type is a plain type (with no asterisk).


text:
Q: Getting a stronger induction principle in Coq Assume the following:
Inductive bin : Set := Z | O.

Fixpoint fib (n : nat) : list bin :=
  match n with
    | 0   => [Z]
    | S k => match k with
               | 0    => [O]
               | S k' => fib k' ++ fib k
             end
  end.

I would like to show:
Theorem fib_first : forall n,
    Nat.Even n -> n > 3 -> exists w, fib n = Z :: w.

However, by performing induction on n, I get a really useless inductive
hypothesis fixing n, stating that IH : Nat.Even n -> n > 3 -> exists w : list bin, fib n = Z :: w.
What I would ideally have is the following: IH : forall n : nat, Nat.Even n -> n > 3 -> exists w : list bin, fib n = Z :: w. Naturally I cannot assume the original proposition, but it feels like I need to prove something stronger perhaps?
My idea for the inductive reasoning would be made possible by expanding F n = F n-2 . F n-1, we know F n-2 is even iff F n is even, and since neither of F n-2 or F n-1 is empty, we can show the substring is shorter, therefore sufficient for the inductive hypothesis - how does one express this in Coq?

A: The trick is to unfold the definition of Nat.Even and do induction on n / 2 instead of n:
Theorem fib_first : forall n,
  Nat.Even n -> exists w, fib n = Z :: w.
Proof.
intros n [m ->].
induction m as [|m IH].
- now exists nil.
- rewrite <- mult_n_Sm, plus_comm.
  generalize (2 * m) IH. clear m IH. simpl.
  intros n [w ->].
  simpl. eauto.
Qed.

Note that your n > 3 hypothesis is not actually needed.


text:
Q: I am no longer able to burn discs using my MacBook's SuperDrive. How can I fix it? About a year ago, the SuperDrive in my 2010 MacBook appeared to stop working. When I insert a blank CD or DVD, the disc does not show up in the Finder. The drive appears in Disk Utility, and I am able to eject it from there. I assumed this was a hardware problem with the SuperDrive, so I just purchased an external Samsung USB DVD drive. I am seeing the exact same behavior with it. This leads me to believe there is some kind of OS X problem rather than it stemming from the drives.
What steps should I take to troubleshoot and try to fix this?

A: I reset the SMC and the SuperDrive is working again.


text:
Q: load the target with update of 2nd row in the source table source table
id name age
1 a  25
1 a  25
1 a  25

target table
id name age
1 a  25
1 a  30
1 a  25

help me in find out this query

A: You should use merge statement.
Merge into target
using source
on target.id = source.id --and target.name = source.name --if needed
when matched then update
set target.age=source.age;

BUT: you must have unique identifier of rows in the source(it may be composed by multiple columns). For example, for my query to run it need source.id to be unique.


text:
Q: Docker running Windows applications I understand Docker to be a containerization tool, with a limited set of APIs so as to be platform agnostic. I am trying to understand what limitations it places on typical Windows development. For example, does it limit access only to write to a file system (and therefore rules out applications that write to the registry)? Is there a level of complexity where Dock is not suitable (but then again I heard that MSSQL will be supported on docker)?

A: Note: since then, you have "How to run lightweight Windows Containers on Windows 10" (January 2019, 2+ years later), from Stefan Scherer.
It does point out that, with the latest release of Docker Desktop (2.0.0.2+) on Windows 10 1809 you now can run Windows Containers in process isolation mode

In the past process isolation was only possible with Windows Server.
  The Windows 10 operating system uses the same kernel, but with different settings.
  With this pull request moby/moby PR 38000 that got merged into Docker 18.09.1 it is now possible to use it on Windows 10 as well.

*

*You can start more Windows Containers on your machine as they consume less resources

*Containers normally start faster than in hyperv isolation mode

*You can "see" the isolated processes and what they are doing

  Especially for developers this is a great enhancement, because you now can use tools like Task Manager, Process Monitor and others to inspect your container processes from the host
The only caveat using the process isolation mode is that the Windows base image that is used for a Docker image must match the kernel of your Windows 10 machine.
Open up a PowerShell terminal and start a Windows container with this command
docker run -d -p 8080:8080 --isolation=process chocolateyfest/appetizer:1.0.0

As you can see in the screen shot you can see the node.exe process in the Task Manager.
  If you have the Sysinternals Process Monitor installed you also can see what the containerized process is doing.
This is great when you create an own Docker image from your or a 3rd-party app and something doesn't work as expected or the exe file just doesn't want to start inside the container.

A: This question is really broad, and hard to answer definitively, but a few specific points in it can be addressed.

I understand Docker to be a containerization tool, with a limited set of APIs so as to be platform agnostic.

It's platform agnostic in a sense that you could run a container on CentOS, Ubuntu, or any other Linux distribution, but you can't run a Linux container on Windows natively, or a Windows container on Linux natively. Introducing Docker for Windows Server 2016 is a good place to start with information regarding Windows containers.

For example, does it limit access only to write to a file system (and therefore rules out applications that write to the registry)?

Based on this MSDN FAQ, no (emphasis mine)

Windows Server Containers are a lightweight operating system virtualization method used to separate applications or services from other services running on the same container host. To enable this, each container has its own view of the operating system, processes, file system, registry, and IP addresses.

For example, dockerfile for SQL Server Express image modifies the registry.

Is there a level of complexity where Dock is not suitable

The question isn't about complexity but about availability of APIs. This is also from the above mentioned Docker for Windows Server 2016

With the exception of GUI apps and apps requiring Windows Remote Desktop, most apps that run on Windows Server can be dockerized to run in an image based on microsoft/windowsservercore with minimal effort.


text:
Q: node js FCM Send notifications to multiple users at once I am building cloud notifications based on Firebase. We are currently working on creating a server as node js and controlling cloud notifications.
However, I have searched a lot of data, and most of the above data is transmitted to only one person by receiving the token value when sending notifications.
Of course, i can use mysql to send it to a large number of people, but is it possible to send it to all users who have the app installed as a user segment like the Firebase console?
Here is the site I referenced. I made it using the script provided here.
https://www.npmjs.com/package/fcm-node

A:
but is it possible to send it to all users who have the app installed as a user segment like the Firebase console?

Not possible out of box. You need a user's registration token to do any sort of messaging. If you do not have all your user's registration tokens, then you'll need to retrieve it for each user. Remember to verify the tokens before persisting them to your database: https://firebase.google.com/docs/auth/admin/verify-id-tokens
And as the readme states for fcm-node:

Warning: on February 2, 2017, the Firebase Team released the admin.messaging() service to their node.js admin module. This new service makes this module kind of deprecated

With that said, you have two options:

*

*Send notifications to multiple users via their registration token:

-
const registrationTokens = [
  'abc',
  'efg',
  '123'
];

const message = {
  data: {
    score: '850'
  },
  token: registrationToken
};

const promises = [];

registrationTokens.forEach(token => {
  const promise = admin.messaging().send(message);
  promises.push(promise);
});

Promise.all(promises)
  .then(results => console.log(results))
  .catch(err => console.error(err));

*

*Or better yet, use Topic Messaging on a  "user segment". You'll need to subscribe users to their respective topic. For example, Android documentation on how to do that can be found here
-
const message = {
  data: {
    score: '850'
  },
  topic: 'myUserSegmentTopic'
};

admin.messaging().send(message)
  .then(res => console.log(res))
  .error(err => console.error(err));


text:
Q: Considering time in DBSCAN I want to cluster some GPS points with DBSCAN algorithm and I select eps:20 m and min_samples:4.
The algorithm works fine on my data, however I need to also consider time of point in the clustering process.
Suppose there are 10 points in a cluster, however 4 of them are between 8 am and 8:30 am and others in duration of 11 am and 11:15 am. What I want is that the algorithm detects 2 clusters here, one with time of 8 points and one with time of 11 points.
I mean I need to have another criteria for my DBSCAN algorithm rather than eps and min_samples.

A: Use Generalized DBSCAN.
Then define neighbors as being both

*

*within distance maxNeighborDistance km

*within maxNeighborTime minutes


text:
Q: Undefined object I have this simple set of data in an array like so:
const mockData =
{ "data" :
  [
    {
      "id": "76",
      "name": "Dude",
      "time": "08:30"
    },
    {
      "id": "77",
      "name": "Hello",
      "time": "08:40"
    },
  ]
}

I wanted to access each object using for loop, but returned with undefined instead. When I access directly like mockData.data[0].name, I'll get the correct data. But when I use the for loop, I'll be returned with undefined is not an object(evaluating mockData.data[i].name and breaks my app. I'm not sure exactly what's happening, if anyone cares to explain would be nice. Here's my for loop (pretty straight forward).
for(let i = 0; i<=mockData.data.length; i++) {
    if(mockData.data[i].name == "Dude") { //this is the part where the object is undefined
          ... do something
    }
}

A: Your condition inside for loop is wrong. It should be like i < mockData.data.length
for(let i = 0; i < mockData.data.length; i++) {}

const mockData =
{ "data" :
  [
    {
      "id": "76",
      "name": "Dude",
      "time": "08:30"
    },
    {
      "id": "77",
      "name": "Hello",
      "time": "08:40"
    },
  ]
}

for(let i = 0; i< mockData.data.length; i++) {
    if(mockData.data[i].name == "Dude") {
      console.log('hi')
    }
}


text:
Q: Algorithm finding minimum bounding rectangle for given circles not evaluating correctly I'm trying to find the smallest bounding rectangle of a number of circles given the x and y co-ordinates of their centre and the magnitude of the radii.
The test input is:
(1, 1, 2), (2, 2, 0.5), (-1, -3, 2), (5, 2, 1)

Here's my code:
package com.CocoMac.main;

import java.util.ArrayList;
import java.util.Scanner;

public class Challenge330Easy {
    static double maxx;
    static double maxy;
    static double minx;
    static double miny;

    static ArrayList <double[]> circles = new ArrayList<double[]>();

    static String in = "1,1,2\n2,2,0.5\n-1,-3,2\n5,2,1";
    static String s;

    static Scanner inScan = new Scanner(in);

    public static void main(String[] args) {
        for(int i = 0; inScan.hasNextLine(); i++) {
            s = inScan.nextLine();
            circles.add(i, toDouble(s.split(",")));

        }

        for(int i = 0; i < circles.size(); i++) {
                if(maxx < circles.get(i)[0] + circles.get(i)[2]);
                    maxx = circles.get(i)[0] + circles.get(i)[2];

                if(minx > circles.get(i)[0] - circles.get(i)[2]);
                    minx = circles.get(i)[0] - circles.get(i)[2];

                if(maxy < circles.get(i)[1] + circles.get(i)[2]);
                    maxy = circles.get(i)[1] + circles.get(i)[2];

                if(miny > circles.get(i)[1] - circles.get(i)[2]);
                    miny = circles.get(i)[1] - circles.get(i)[2];

        }

        System.out.print("(" + minx + ", " + miny + ")" + ",");
        System.out.print("(" + minx + ", " + maxy + ")" + ",");
        System.out.print("(" + maxx + ", " + maxy + ")" + ",");
        System.out.print("(" + maxx + ", " + miny + ")");

    }

    public static double[] toDouble(String[] input) {
        double[] output = new double[input.length];
        for(int i = 0; i < input.length; i++) {
            output[i] = Double.parseDouble(input[i]);

        }

        return output;

    }

}

The expected output is:
(-3.000, -5.000), (-3.000, 3.000), (6.000, 3.000), (6.000, -5.000)

But instead, the output is:
(4.0, 1.0),(4.0, 3.0),(6.0, 3.0),(6.0, 1.0)

I've tried everything I can think of. For whatever reason, the final input is the maximum values found from the last circle iterated through (5,2,1) instead of the largest possible from all circles, which makes me think the conditional statements used when I'm setting the maximum and minimum values of x and y may be always evaluating to true, but I have no idea how.
If you could, clue me in on what I'm missing here or point me in the direction of what I need to learn. Any help is appreciated!

A: One obvious problem:
if(maxx < circles.get(i)[0] + circles.get(i)[2]);
    maxx = circles.get(i)[0] + circles.get(i)[2];

You put a semicolon after the if condition.  That terminates the statement.  This translates to ...
if(maxx < circles.get(i)[0] + circles.get(i)[2])
    ;  // Do nothing
maxx = circles.get(i)[0] + circles.get(i)[2];


text:
Q: Ember.js - Cannot render the 'edit' .hbs for an instance of a model. I am trying to {{#link-to}} the '/edit' route of a specific instance of a model, 'category/2' making route to 'category/2/edit'.
The problem is when I use the url 'category/2/edit' the page remains on the 'category/2' page except that all of the attributes defined in the model for 'category' like {{CategoryType}}, for instance, disappear.
I don't receive a single error while doing this.
Without further ado, here is my code.
router.js ----
  this.resource('category', { path: '/category/:category_id' }, function() {
    this.route('edit');
  });

category.hbs ----
Notes: {{CategoryName}} initially does show up when the page first loads. Only when the page is reloaded or when I try to link to the 'edit' does it disappear.
Category: {{ProjectName}}
{{#link-to 'this.edit'}}<button>Edit this</button>{{/link-to}}

category_route.js ----
Notes: *I'm defining :category_id in the model*
    VpcYeoman.CategoryRoute = Ember.Route.extend({
        model: function(params) {
            return {
                id: params.category_id
             };
        }
    });

category_model.js ----
Notes: I cut out the other fixtures to simply this
VpcYeoman.Category = DS.Model.extend({
    CategoryName: DS.attr('string'),
    workflow: DS.belongsTo('category', {
        polymorphic: true
    }),
    classNameBindings: ['isAdministrator']
});

VpcYeoman.Category.FIXTURES=[
    {
      id: 2,
      RecordCategoryID: 2,
      Name: "Nilport",
      CategoryName: "Broden Cannon Project"
    }
];

I appreciate this guys!

A: Include an {{outlet}} in category.hbs
You may also have to set the model for the edit route:
VpcYeoman.CategoryEditRoute = Ember.Route.extend({
    model: function(params) {
        return {
            id: params.category_id
         };
    }
});


text:
Q: Рейтинг статей по типу "мне нравится" Решил сделать  для сайта кнопку по типу "мне нравится", как в соц. сетях. Собственно нужен алгоритм осуществления этой задачи. Вот вариант который пока пришел в голову: В БД в таблице статей есть поля like, id_user, hash (к примеру), в поле like естественно кол-во "мне нравится" для статьи, в поле id_user, id человека который нажал на кнопку, и hash это автоматически присваиваемый хэш для статьи. На самом сайте ссылка "мне нравится" будет иметь вид mysite.ru/news?like=af1s4a7ds2a4g6afd6f. Далее при нажатии на кнопку будет сверятся хэш af1s4a7ds2a4g6afd6f со значением в базе для этой статьи, если сходится ставим этой статье в поле like +1. Если есть вариант намного проще и легче осуществить эту задачу, слушаю ваши предложения.
A: Как вариант... Можно завести таблицу  like c полями like_id, like_user_id, like_unick. Потом в таблице статей сделать столбец like_unick, сделать связь с таблицей like. И про получении статьи из БД INNER JOIN'ом делать count лайков в таблице like (like_unick нам известен). А при нажатии на кнопку нравится, просто дописывать в таблицу Like одну строчку с user_id нажавшем на кнопку и like_unick, присущем для ДАННОЙ СТАТЬИ. Сделайте PRIMARY KEY на like_id,like_unick и INDEX на like_user_id. Должно работать все быстро. Столбец Like_unick желательно сделать обычным int'ом.
А то что описали Вы, никак не вяжется со структурой таблицы статей. Там должна быть всего одна строчка на одну статью. Иначе никак...


text:
Q: In which version of MediaWiki came the feature 'page preview'? We've MediaWiki 1.31.0 installed, but can't find the feature 'page preview', which is described here: https://www.mediawiki.org/wiki/Page_Previews
On this feature-page there's no hint, in which version of MediaWiki this feature was implemented. Can anybody tell me?

A: This is not core Mediawiki functionality, but implemented via an extension. See here for more information: https://www.mediawiki.org/wiki/Extension:Popups
PS: 1.31.0 has known security issues, you should at least upgrade to 1.31.7


text:
Q: How can print server side from client app via WCF service? When I run application on server, it prints locally via StimulSoft Print Method to a Physical thermal Printer Properly, but when I call same method from a client app from WCF, get this error:
"Showing a modal dialog box or form when the application is not running in UserInteractive mode is not a valid operation. Specify the ServiceNotification or DefaultDesktopOnly style to display a notification from a service application."
PrinterSettings ps1 = new PrinterSettings();
ps1.PrinterName = MyPrintControler.SellerPrinterName;
stiReport.Print(false, ps1);


text:
Q: Why are they called isothermal coordinates? On a Riemannian manifold, a coordinate system is called "isothermal" if the Riemannian metric in those coordinates is conformal to the Euclidean metric:
$$g_{ij} = e^{f} \delta_{ij}$$
My question is: Why are such coordinate systems called "isothermal"? It must have something to do with classical thermal physics. I tried looking for a reason online, with no success.
It is well known that when the dimension $n=2$, there always exist isothermal coordinates, and this is probably where they were first introduced. So maybe the nomenclature has something to do with heat diffusion in the plane?
(The reason I ask is because I am planning to give a seminar talk next week giving a proof that such coordinates exist when $n=2$, and thought it would be nice to explain to the students where the name comes from...)

A: Isothermal coordinates are harmonic. In other words, it solves $\triangle_g u = 0$. So locally it is a stationary solution of the heat equation. In physics, for a steady state distribution of temperatures, each level set is called an isotherm.

A: According to Gray, Abbena and Salamon, that's the name given to such coordinate systems by Gabriel Lamé in his 1833 study of heat transfer. The reason is, if you've got a thermally isolated surface of constant heat conduction, the constant coordinate lines are isotherms iff the coordinates are isothermal.


text:
Q: Dynamics CRM 2015 Import values I am using Microsoft Dynamics CRM 2015 on-premise version.
Im importing my solution to an other organization with custom entities and workflows.
I created a workflow to do some work depending on the type of the inserted queueitem.
My issue: Some conditions in my imported workflow are not supported in the new organisation (only the conditions on the custom entities are not supported and are replaced by empty brackets)
I think the custom entities IDs are not imported with the same values, so, the CRM does not recognize these custom entities condition.

A: Try exporting and importing the customization in two separate solutions.
In the first solution include the entities and optionsets you wish to import. Export the solution from the old environment, import into the the new environment and publish.
In the second solution include the workflows. Oncce again export the solution from the old environment, import into the the new environment and publish.

A: When you point to an entity inside a workflow, it will retain the GUID.
If you export/import the workflow, the reference will be lost because that specific GUID won't exist in the new environment.

A: The issue is indeed that the GUID values of the records referenced in your workflows are passed trough the solution but doesn't exist in your target environment.
You can either:

*

*Modify you workflows, instead of (for example) Primary Entity Opportunity / Account / Equals / Contoso use Related Entity Account / Account Number / Equals / ContosoNumber

*Import the data referenced in your workflows by keeping the same GUIDs. This is slightly more technical:

*

*First, you need to export the data from your source organization (either SQL or Export to Excel with reimport enabled)

*Then convert this file to csv while keeping the id value embeded

*Reimport the file with import wizard and mapping the GUID column


text:
Q: Regex para verificar se string não termina com determinados caracteres Estou quebrando a cabeça no site http://www.regexplanet.com/advanced/java/index.html
Estou tentando fazer uma regex que valide alguns .txt que não contenha os caracteres JJ ou M3 no final da linha.
Por exemplo, tenho os 3 .txt com as linhas abaixo:
.txt 1

*

*4481;77831853;4461;60;CAD;VCP;M3

*4647;86940830;4847;35;FRA;VCP;M3

.txt 2

*

*3287;69872804;3297;37;ANT;VCP;JJ

*3827;72247849;3857;38;DEC;VCP;JJ

.txt3

*

*5634;7082850;5634;40;MAR;VCP;PZ

*4362;3882867;4382;41;PAU;VCP;PZ

Preciso de uma regex que não aceite os .txt 1 e 2, somente o .txt 3, pois os dois últimos caracteres deles são diferentes de JJ e M3.

A: Quem me acompanha aqui no SOpt sabe que eu não curto muito funcionalidades além das previstas para linguagens regulares.
A resposta fornecida pelo @nunks.lol usa o negative lookbehind, que não é regular no sentido matemático. Mas essa com certeza é uma solução ótima.
Mas eu posso fazer sem lookbehind!
Expressão das palavras que não terminam com JJ
O fato de não conter essas duas letras no final torna a questão mais fácil. Só ver a resposta dessa questão para ver o trabalho que dá negar uma subpalavra em qualquer lugar.
Para não acabar com JJ, temos 4 alternativas:

*

*A linha está em branco, portanto casa com ^$

*A linha contém exatamente um caracter, portanto ^.$

*O último caracter é não J, ^.*[^J]$

*O penúltimo caracter é não J, ^.*[^J].$
Portanto, a expressão a seguir casa com isso:
^$|^.$|^.*[^J]$|^.*[^J].$

Feio, não é? Mas felizmente pode ser simplificado:
^(.|.*([^J]|[^J].))?$

eu poderia ter simplificado mais ainda [^J]|[^J]., mas aí eu perderia o formato a ser usado na próxima expressão

Expressão das palavras que não terminam com M3
Para não acabar com M3, temos 4 alternativas:

*

*A linha está em branco, portanto casa com ^$

*A linha contém exatamente um caracter, portanto ^.$

*O último caracter é não 3, `^.*[^3]$

*O penúltimo caracter é não M, ^.*[^M].$
Eu poderia colocar a versão feia e logo em seguida a simplificada, mas também posso abreviar:
^(.|.*([^3]|[^M].))?$

Juntando tudo
Para juntar tudo, tem alguns casos especiais a se levar em consideração:

*

*Pode terminar em J se a penúltima letra for M

*Pode terminar em 3 se a penúltima letra for J
De resto, aglutinar as listas negadas faz o serviço. Esses seriam o únicos casos não tratados pela abstração anterior.
^(.|.*([^J3]|[^JM].|J3|MJ))?$

A: Utilize a notação de "negative lookbehind" para garantir que a string não termina nos padrões que você definiu logo antes da quebra de linha, ou seja, um $ que não tem JJ ou M3 antes dele. Assim, a sua expressão regular fica:
^.*(?<!JJ|M3)$

Detalhando:
^          # início da linha
 .*        # qualquer caractere, zero ou mais vezes
   (?<!    # abertura do negative lookbehind
       JJ  # sequencia literal "JJ"
        |  # condicional "ou"
       M3  # sequencia literal "M3"
   )       # fechamento do negative lookbehind
$          # final da linha

Exemplo no regex101.com: https://regex101.com/r/2loAEN/2
(incluí algumas linhas com terminação variada em J e 3 para demonstrar que a expressão não nega mais do que deveria)
Explicação interessante de lookaround em expressões regulares: https://stackoverflow.com/questions/2973436/regex-lookahead-lookbehind-and-atomic-groups
Complementando: uma questão a ser levada em conta quando do uso de lookahead e lookbehind (os chamados lookaround) é a performance. O uso de lookaround tende a utilizar um pouco mais de CPU do que o match de expressões regulares "tradicionais". Caso você pretenda aplicar essa expressão de forma maciça, com muitas chamadas por segundo, pode ser vantajoso utilizar métodos de maior "verbosidade", como a resposta dada pelo @JeffersonQuesado.

A: Complementando as outras respostas, segue outra alternativa: para verificar se algo não é alguma coisa, muitas vezes é mais fácil verificar se é, e simplesmente inverter o resultado. Então você poderia usar esta regex:
String[] strings = { "4481;77831853;4461;60;CAD;VCP;M3", "4647;86940830;4847;35;FRA;VCP;M3",
                     "3287;69872804;3297;37;ANT;VCP;JJ", "3827;72247849;3857;38;DEC;VCP;JJ",
                     "5634;7082850;5634;40;MAR;VCP;PZ", "4362;3882867;4382;41;PAU;VCP;PZ",
                     "J", "3827;72247849;3857;38;DEC;VCP;AJ", "AJ", "JJ", "M3" };
for(String s : strings) {
    System.out.println(s + " = " + (! s.matches("^.*(JJ|M3)$")));
}

A regex é ^.*(JJ|M3)$.
Os marcadores ^ e $ são o início e fim da string, para garantir que ela só tem que está especificado na regex.
.* é "zero ou mais caracteres" (o ponto é qualquer caractere - exceto quebras de linha) e o quantificador * significa "zero ou mais ocorrências".
JJ|M3 é uma alternância, que corresponde aJJ ou M3.
Ou seja, a regex verifica se a string termina com "JJ" ou "M3". Portanto, ela serve para verificar o que você não quer. Por isso eu inverto o resultado do método matches, usando !: se a regex encontrar um match, ela corresponde ao que você não quer, e vice-versa.
A saída do código acima é:
4481;77831853;4461;60;CAD;VCP;M3 = false
4647;86940830;4847;35;FRA;VCP;M3 = false
3287;69872804;3297;37;ANT;VCP;JJ = false
3827;72247849;3857;38;DEC;VCP;JJ = false
5634;7082850;5634;40;MAR;VCP;PZ = true
4362;3882867;4382;41;PAU;VCP;PZ = true
J = true
3827;72247849;3857;38;DEC;VCP;AJ = true
AJ = true
JJ = false
M3 = false

Um porém do código anterior é que o método matches cria uma nova instância de Pattern, e como ele está sendo chamado em um loop, são criadas várias instâncias. Mas como todas elas usam a mesma regex, daria para melhorar isso usando - e reaproveitando - uma única instância, criando-a fora do loop:
Matcher matcher = Pattern.compile("^.*(JJ|M3)$").matcher("");
for (String s : strings) {
    System.out.println(s + " = " + (!matcher.reset(s).matches()));
}

A saída é a mesma do código anterior.

Este caso também dá para resolver sem regex:
for (String s : strings) {
    System.out.println(s + " = " + !(s.endsWith("JJ") || s.endsWith("M3")));
}

O método endsWith verifica se a string termina com determinados caracteres. No caso, basta verificar se ela termina com "JJ" ou "M3", e negar o resultado.

A: Creio que esteja lendo o arquivo linha a linha, então usando essa deve resolver.
A regex mais simples que imaginei foi (.*(?!(M3|JJ))..|^.)$.

*

*.*: Aceita os primeiros caracteres da linha

*(?!(M3|JJ)): Verifica se a string contém os caracteres M3 ou JJ

*..:  Garante que haverá dois caracteres no fim da linha, senão o M3 e o JJ iriam passar

*^.: Permite que haja uma linha com apenas um caractere

*$: Fim de entrada, para garantir que os últimos caracteres aceitos são os últimos da linha

A: Uma abordagem diferenciada será justamente buscar pelo resultado negativo:
...

String pattern = "/(JJ|M3)/";
Pattern regexp = Pattern.compile(pattern);
Matcher m = regexp.matcher(linhaLidaDoArquivo);

// Existe também o método find() para o objeto m
// o qual você poderá iterar e verificar quantas
// ocorrências encontrou no padrão fornecido
if(pattern.matches(m)) {
    System.out.println("O seu arquivo é INVÁLIDO");
else
    System.out.println("O seu arquivo é VÁLIDO");

Em outras palavras: você saberá e controlará o que você não quer que ocorra. O código acima busca pelas combinações (maiúsculas) com o padrão "JJ" e "M3" em qualquer posição da string. Caso eles ocorram dentro da linha lida, então as classes Pattern e Matcher irão identificar tal ocorrência. Se encontradas, o if retornará true e o tratamento do estado negativo poderá ser utilizado. Para os demais casos, você irá tratá-los com o cenário esperado e válido.


text:
Q: Python savemat only saves the last image feature I wrote a code to save image features to .mat files in python. However, although I added 'append' section in savemat function, it only saves the last image feature in .mat file. How can I save all image features (for example if I have 5 images, I will have 5 x 512 size .mat file)
  pics = {}
  for file in os.listdir(input_path):
    filename = os.fsdecode(file)
    img = Image.open(os.path.join(input_path, filename))
    vec = img2vec.get_vec(img)
    print(len(vec))
    pics[filename] = vec
    io.savemat('final.mat',{"foo":vec},'-append')


text:
Q: How to avoid Gerrit to automatically add authors as reviewers? I would like to push a series of patches that contain multiple "Singed-off-by" fields in their commit messages to Gerrit.
The problem is that Gerrit will automatically send e-mail to these authors and add them as reviewers. This is true because some of them are in my company directory, but I don't want to notify them because they are not working on the same project.
This series is a back-port of a full driver from the latest Linux kernel, so I don't want to remove any "Signed-off-by".
Here are the tracks I have explored for the moment:

*

*git push remote HEAD:refs/for/master%notify=NONE
This is supposed to push the changes without notifying anyone, but I got the following error message:

! [remote rejected] HEAD -> refs/for/master%notify=NONE ("--notify"
  is not a valid option)

--> I found this option in Gerrit documentation Version 2.12.2 and I am using Gerrit v2.8.5, so I guess this option has been removed now.

*git push remote HEAD:refs/for/master%r=NONE,cc=NONE
But these two options only take email addresses as parameters.

*Editing project.config
I found many ways to edit this file to automatically add specific reviewers, such as using [plugin "reviewers"], but all I could find was to add reviewers, not to REMOVE automatic reviewers.
Would you have any clue on how to prevent Gerrit to automatically add these reviewer who are in "Signed-off-by" ?
Thanks and Regards


text:
Q: Does GPS module need a wireless service? do I have to pay a service to get my gps module working? Hi I'm new in the GPS world, I'm looking for a GPS module to track X amount of object the question is do I have to pay any service (cellular, data,etc) to get my gps working?
I'm sorry for the dumby question but I'm new here
thanks

A: Don't confuse GPS with GPS trackers!
You cannot track any objects using GPS receivers. You need to track them using GPS trackers.
GPS receiver will track GPS satellites and calculate its own position. This service is free. Keep in mind that GPS receiver will not allow you to transfer the location data.
A GPS tracker will have a GPS receiver as its component. It will also allow you to send the location of the tracker. To actually send the location  you'll have to have a data service of some kind, which will cost. So it's not the GPS that needs subscription, it's the data transfer that costs.

A:
do I have to pay any service (cellular, data,etc) to get my gps working?

No, not a simple GPS, like a hand-held Garmin (other brands are available) or a USB GPS.
If you have a GPS integrated with a phone, and the software relies on other things delivered through the air interface, updated maps, resturants near here, then you will need to pay for that extra service.


text:
Q: How can I pass an URL location from a table row to simplemodal script I have the old script working at http://chesstao.com/about.php in the games table. Unfortunately it uses the href from each td repeated several times for each tr. I would like to click on the table row and have the href passed to the 'test_modal' script. So I think I need to assign a value to var hrefval from the onclick in the tr.
True or false?
Is there a better way to do this w/o breaking dataTables in http://chesstao.com/test.php?

07/17/1998

A: There is no need to put inline onclick. It would be better to put this URL in the rel attribute of each tr and take it in the on click handler. Example:

with js code:
$(".test_modal").click( function(e) { var href= $(this).attr("rel"); etc.... } );
I have not copied everything from your code but I believe that you see what I'm trying to achieve.
Jovan


text:
Q: C++ : Image sequence wrongly loaded I have thousand of images in a folder,
created using
file << output << counter << ".jpg";
counter++;

smtg1
smtg2
  .
  .
  .
smtg100
Now, using this line, I get
for (size_t i = 0; i < count; i++)
pic = imread(fn[i], CV_LOAD_IMAGE_COLOR);

smtg1
smtg10
smtg100
  .
  .
smtg109
smtg11
smtg110
It seems like it takes in images based on the first integer,   hence the image sequence are wrong.
Can anybody point out my mistake if I was doing anything wrong?
So that I am able to get the correct sequence from 1-1000?

A: Consider using cv::videoCapture.
You can specify a template string of your file names such as ".\\some\\folder\\smtg%d.jpg", and videoCapture will read the frames in the correct numerical order for you.
(Untested) code, to demonstrate the basic usage:
cv::VideoCapture images(".\\some\\folder\\smtg%d.jpg");
cv::Mat image;

while(true)
{
    images >> image;
    if (image.empty()) break;

    // do your processing...
}

For details on how the format specifiers work in the template string, you'll have to read up on the printf family of functions.


text:
Q: Changing the item orientation of a listview, datagrid, datalist or any other databound control? I have data that renders in a listview like this:
name address           city
Tom  200 George Street Sydney
i would like it to render like this:
name      Tom
address   200 George Street
city      sydney
Any suggestions on how I may do this?

A: There are many ways to do this. The implementations for ListView, DataList, and Repeater would be similar, but you could do something like this:
<asp:ListView ID="ListView1" runat="server">
    <ItemTemplate>

                Name:
                <%#Eval("Name")%>

                Address:
                <%#Eval("Address")%>

    </ItemTemplate>
</asp:ListView>


text:
Q: How to config xdebug with Vagrant and PhpStorm: Exit code 255? I am trying to configure xdebug to work with my Vagrant VM in PhpStorm. I tried using this guide but to no avail.
I've already got xdebug installed on my Vagrant box and the box is also registered and configured with PhpStorm
I have tried setting a break point and running the debugger on this basic test function with Laravel:
Route::get('/test', function()
{
    $a = [1, 2, 3, 4, 5];

    array_pop($a);

    return 'hello';
});

But it fails with the following error message:
vagrant://C:\Users\johndoe\Desktop\myproject/usr/bin/php -dxdebug.remote_enable=1 -dxdebug.remote_mode=req -dxdebug.remote_port=9000 -dxdebug.remote_host=10.0.2.2 /vagrant/app/routes.php
PHP Fatal error:  Class 'Route' not found in /vagrant/app/routes.php on line 6
PHP Stack trace:
PHP   1. {main}() /vagrant/app/routes.php:0

Process finished with exit code 255

I also tried running it on a function in one of my controllers but it gives a similar error
vagrant://C:\Users\johndoe\Desktop\myproject/usr/bin/php -dxdebug.remote_enable=1 -dxdebug.remote_mode=req -dxdebug.remote_port=9000 -dxdebug.remote_host=10.0.2.2 /vagrant/app/controllers/MyController.php
PHP Fatal error:  Class 'BaseController' not found in /vagrant/app/controllers/MyController.php on line 15
PHP Stack trace:
PHP   1. {main}() /vagrant/app/controllers/MyController.php:0

Process finished with exit code 255

/etc/php5/conf.d/20-xdebug.ini:
zend_extension=/usr/lib/php5/20100525/xdebug.so
xdebug.remote_enable = on
xdebug.remote_connect_back = on
xdebug.idekey = "vagrant"

Vagrantfile:
# -*- mode: ruby -*-
# vi: set ft=ruby :

# Config Github Settings
github_username = "johndoe"
github_repo     = "myrepo"
github_branch   = "master"

# Server Configuration

# Set a local private network IP address.
# See http://en.wikipedia.org/wiki/Private_network for explanation
# You can use the following IP ranges:
#   10.0.0.1    - 10.255.255.254
#   172.16.0.1  - 172.31.255.254
#   192.168.0.1 - 192.168.255.254
server_ip             = "192.168.22.10"
server_memory         = "384" # MB
server_timezone       = "UTC"

# HHVM Options
hhvm_use_fastcgi      = "false"  # Use HHVM as FastCGI (over php-fpm)
hhvm_over_php         = "false"  # Symlink HHVM to PHP, so calls to PHP run via HHVM

# PHP Options
php_version           = "previous" # Options: latest|previous|distributed   For 12.04. latest=5.5, previous=5.4, distributed=5.3

public_folder         = "" # If installing Symfony or Laravel, leave this blank to default to the framework public directory
laravel_version       = "4.1.27"
laravel_root_folder   = "/vagrant/laravel" # Where to install Laravel. Will `composer install` if a composer.json file exists
symfony_root_folder   = "/vagrant/symfony" # Where to install Symfony.

Vagrant.configure("2") do |config|

  # Set server to Ubuntu 12.04
  config.vm.box = "precise64"

  config.vm.box_url = "http://files.vagrantup.com/precise64.box"

  # Create a hostname, don't forget to put it to the `hosts` file
  # This will point to the server's default virtual host
  # TO DO: Make this work with virtualhost along-side xip.io URL
  config.vm.hostname = "vaprobash.dev"

  # Create a static IP
  config.vm.network :private_network, ip: server_ip

  # If using VirtualBox
  config.vm.provider :virtualbox do |vb|

    # Set server memory
    vb.customize ["modifyvm", :id, "--memory", server_memory]

    # Set the timesync threshold to 10 seconds, instead of the default 20 minutes.
    # If the clock gets more than 15 minutes out of sync (due to your laptop going
    # to sleep for instance, then some 3rd party services will reject requests.
    vb.customize ["guestproperty", "set", :id, "/VirtualBox/GuestAdd/VBoxService/--timesync-set-threshold", 10000]

  end

  # If using VMWare Fusion
  config.vm.provider "vmware_fusion" do |vb, override|
    override.vm.box_url = "http://files.vagrantup.com/precise64_vmware.box"

    # Set server memory
    vb.vmx["memsize"] = server_memory

  end

  # If using Vagrant-Cachier
  # http://fgrehm.viewdocs.io/vagrant-cachier
  if Vagrant.has_plugin?("vagrant-cachier")
    # Configure cached packages to be shared between instances of the same base box.
    # Usage docs: http://fgrehm.viewdocs.io/vagrant-cachier/usage
    config.cache.scope = :box

    config.cache.synced_folder_opts = {
        type: :nfs,
        mount_options: ['rw', 'vers=3', 'tcp', 'nolock']
    }
  end

  ####
  # Base Items
  ##########

  # Provision Base Packages
  config.vm.provision "shell", path: "https://raw.github.com/#{github_username}/#{github_repo}/#{github_branch}/scripts/base.sh"

  # Provision PHP
  config.vm.provision "shell", path: "https://raw.github.com/#{github_username}/#{github_repo}/#{github_branch}/scripts/php.sh", args: [php_version, server_timezone]

  ####
  # Web Servers
  ##########

  # Provision Apache Base
  config.vm.provision "shell", path: "https://raw.github.com/#{github_username}/#{github_repo}/#{github_branch}/scripts/apache.sh", args: [server_ip, public_folder]

  ####
  # Frameworks and Tooling
  ##########

  # Provision Composer
  config.vm.provision "shell", path: "https://raw.github.com/#{github_username}/#{github_repo}/#{github_branch}/scripts/composer.sh", privileged: false, args: composer_packages.join(" ")

  # Provision Laravel
  #config.vm.provision "shell", path: "https://raw.github.com/#{github_username}/#{github_repo}/#{github_branch}/scripts/laravel.sh", privileged: false, args: [server_ip, laravel_root_folder, public_folder, laravel_version]

end

PhpStorm version: 8.0.2
It seems like xdebug is not able to read any of the Laravel classes/facades. What can I do to get this fixed so I can use xdebug?


text:
Q: Disposing by setting to null? I'm aware of technique to handle IDisposable in a traditional manner. Say, in OnStop() method of windows service I close message queue client:
        if (client != null)
        {
            client.Dispose();
        }

For the first time today I saw one guy doing that this way:
        using (client)
        {
            client = null;
        }

What is exactly happening inside his "using" or does he dispose correctly at all?

A: The using(){} statement grabs a copy of the reference var so this assignment with null is ineffective.

A: Your using-based colleague's code will work, but is arguably overkill;
using(client) {
    client = null;
}

is essentially:
{ // scope here to denote that 'tmp' is not defined outside this scope
  var tmp = client;
  try {
      client = null;
  } finally {
      if(tmp != null) tmp.Dispose();
  }
}

(not quite that in all cases, as there are value-types and explicit interface implementation to think about).
Personally, I'd just use using for the whole thing where possible (i.e. in the code that initially allocates client).
One time I might use this is a lazy:
using(client as IDisposable) { client = null; } // dispose if needed

i.e. client is something outside my control, and I'm not sure if it implements IDisposable or not, but if it does, I need to release it.

A: Exiting from
using (client)
{
}

client.Dispose() is called automatically for you.
client = null should be called out of that code in my opinion.
Remember that to use using(object) the object should implement IDisposable interface.

A: To me it looks not effective at all. Since the client is set to null the using has nothing referenced to dispose anymore, even though the actual object is still in memory, just not referenced by any variable (it will be garbage collected later on, but what's the point of the using then?).

A: If the scope of "client" extends outside the "using" block, as it would appear to, the code as written will ensure that "client" gets disposed before control leaves the "using" block, and the reference to the newly-defunct "client" object will be destroyed.  Nulling out the reference to it may be important if it's a field, and may be critical if it's a property that attaches events.
My guess would be that "client" is a field or property, and that the author of the "using" code thought it was more concise than the version given by Marc Gravell.  I would grant the author that the code is concise, but would suggest that even more concise and clearer would be to define a generic "Zap" routine which accepts an IDisposable by reference, uses Interlocked.Exchange to read and null it, and disposes it if it wasn't null.  In that case, the "using" statement would be replaced with:

  Zap(ref client);

which has the benefit of being more concise while almost certainly being clearer.


text:
Q: .NET Core Razor pages change pages to anonymous I have a project with .NET Core 2.1 Razor Pages. It was built using the authentication option in the new project UI. So, when I type the URL and hit enter, the website opens the Microsoft login page, and I cannot see any page until I am signed in.
Now, I have a request to change the behavior of the authentication and I need to show the home page (Index) and other pages without the authentication process. So, I think I have to move the login page to a button and allow those pages to be accessible by anyone.
Can you please show me the right direction for this change?
I see that the [AllowAnonymous] directive is only for the controller (ASP.NET Core MVC), because it is not working in the Razor page, where the client and server code are combined in 2 files.
Also, I found a post talking about Service.AddRazorPage but I got an error showing that this method is for MVC, so I don't know if I have to continue with my research to work with this method.
Thanks!

A: You can try using Razor Pages authorization conventions in ASP.NET Core:
services.AddMvc()
    .AddRazorPagesOptions(options =>
    {
        // options.Conventions.AuthorizePage("/Contact");
        // options.Conventions.AuthorizeFolder("/Private");
        options.Conventions.AllowAnonymousToPage("/Index");
        // options.Conventions.AllowAnonymousToFolder("/Private/PublicPages");
    })
    // ...
    ;


text:
Q: Getting an error as Batch update returned unexpected row count from update I am getting the below error with my code.
Hibernate: insert into EMPLOYEE (FIRST_NAME, LAST_NAME, SALARY, ID) values (?, ?, ?, ?)
Hibernate: update CERTIFICATE set ID=? where ID=?
org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
    at org.hibernate.jdbc.Expectations$BasicExpectation.checkBatched(Expectations.java:81)
    at org.hibernate.jdbc.Expectations$BasicExpectation.verifyOutcome(Expectations.java:73)
    at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:63)

Here is my code.
Employee.java
@Entity
@Table(name="EMPLOYEE")
public class Employee {

    @Id
    @Column(name="ID")
   private int id;

    @Column(name="FIRST_NAME")
   private String firstName;
    @Column(name="LAST_NAME")
   private String lastName;
    @Column(name="SALARY")
   private int salary;

    @OneToMany
    @JoinColumn(name = "ID")
     @OrderBy("name ASC")
   private SortedSet<Certificate> certificates;
//getters and setters

}
Certificate.java
@Entity
@Table(name="CERTIFICATE")
public class Certificate implements Comparable <Certificate>{

    @Id
    @Column(name="ID")
       private int id;
    @Column(name="CERTIFICATE_NAME")
       private String name;
    //generate getters and setters
   }

I am trying to add users using below code.
ManageEmployee ME = new ManageEmployee();
      /* Let us have a set of certificates for the first employee  */
      TreeSet set1 = new TreeSet();
      set1.add(new Certificate("MCA"));
      set1.add(new Certificate("MBA"));
      set1.add(new Certificate("PMP"));

      /* Add employee records in the database */
      Integer empID1 = ME.addEmployee("Manoj", "Kumar", 4000, set1);

and with my addEmployee method I have below code
Employee employee = new Employee(fname, lname, salary);
         employee.setCertificates(cert);
         employeeID = (Integer) session.save(employee);

Please suggest what I should be changing from my end to get this fixed.

A: The issue was because of the id attribute not being set by default. I had to update my code to include GeneratedValue annotation and that fixed the issue.
   @Entity
@Table(name="EMPLOYEE")
public class Employee {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="ID")
   private int id;


text:
Q: Making leaflet control open by default I'm using leaflet to display a map.  I have a control section that I'd like to be open by default, but I can't find a way to do it through the API.
Is there a way to do this?

A: The collapsed option in the control will achieve this. You need that null for it to work though. An example:
var overlays = {
    "Title1": polyLayer1,
    "Title2": polyLayer1,
    "Title3": lineLayer,
    "Title4": pointLayer
            };

L.control.layers(overlays,null,{collapsed:false}).addTo(map);

A: The curly braces with the collapsed attribute did the trick!


text:
Q: How do I declare a Multi-set that contains arrays of a certain size? I'm relatively new to C++. I'm trying to declare a multiset that contains arrays of size 2. I've tried the following but I don't think it does what I want it to do:
multiset<int> nameOfSet[2];

Can someone please tell me what this line does? If this is wrong, please explain to me why and tell me how to do it correctly. Thanks in advance.

A:
multiset<int> nameOfSet[2];

Can someone please tell me what this line does?

It declares a variable that is an array of two multisets of int.

How do I declare a Multi-set that contains arrays of a certain size?

You cannot. Arrays cannot be elements of any standard container.
However, arrays can be members of classes, and classes can be elements of containers. There is a standard template for such array wrapper: std::array. So, you can do:
std::multiset<std::array<int, 2>> nameOfSet;


text:
Q: Transforming the field strength tensor - Why do we need to use $\Lambda^T$, instead of a row times row multiplication? The transformation law is
\begin{align}
F'^{\mu\nu} = {\Lambda^{\mu}}_{\alpha} {\Lambda^{\nu}}_{\beta} F^{\alpha \beta} = {\Lambda^{\mu}}_{\alpha}  F^{\alpha \beta} {\Lambda^{\nu}}_{\beta}
\end{align}
We are given $F$ as a matrix with respect to the basis $e_\mu \otimes e_\nu$, the entries of this matrix are then essentially also the coefficients $F^{\mu \nu}$.
In the same way, we are given the Lorentz transformation $\Lambda$ as a matrix as well. We can then interpret ${\Lambda^{\mu}}_{\alpha}  F^{\alpha \beta}$ as the usual matrix multiplication:
\begin{align}
{\Lambda^{\mu}}_{\alpha}  F^{\alpha \beta} = (\Lambda \times F)^{\mu \beta} = G^{\mu \beta}
\end{align}
However, for the 2nd tensor contraction
\begin{align}
G^{\mu \beta} {\Lambda^\nu
}_\beta \end{align}
the wrong order of indices doesn't permit such a way of calculating the coefficients at first glance. However, doesn't the Einstein summation convention (that is implicitly used in the tensor contraction operation) allow us to write:
\begin{align}
G^{\mu \beta} {\Lambda^\nu}_\beta = G^{\mu 0} {\Lambda^\nu}_0 + G^{\mu 1} {\Lambda^\nu}_1 + G^{\mu 2} {\Lambda^\nu}_2 + G^{\mu 3} {\Lambda^\nu}_3
\end{align}?
I tried to calculate it this way, using the entries of $\Lambda$ as the coefficients ${\lambda^{\nu}}_0$, but I don't get the right result, that I would get by calculating $\Lambda F \Lambda^T$. So where is my mistake? Is the Einstein summation convention not applicable here?

A: I'm not sure what you are confused about, but the tensor transformation law is $$F'_{\alpha\beta}=\Lambda^\mu_{\phantom\mu \alpha}\Lambda^\nu_{\phantom \nu\beta}F_{\mu\nu}\tag{1}$$
Then you notice that $\Lambda^\mu_{\phantom\mu\alpha}=(\Lambda^T)_{\alpha}^{\phantom \alpha\mu}$. As such this is
$$F'_{\alpha\beta}=(\Lambda^T)_\alpha^{\phantom \alpha \mu}F_{\mu\nu}\Lambda^\nu_{\phantom \nu\beta}\tag{2}$$
and this is exactly the formula for matrix multiplication so that $F'=\Lambda^T F \Lambda$. This is the tensor transformation law in matrix form, there is nothing wrong with it or with the summation convention. In fact it is just (1) written in a different notation.


text:
Q: How to use video filters (cropdetect) with ffprobe Checking the ffprobe docs apparently there is an option to use cropdetect with it. I am already aware that I could do this with ffmpeg like:
ffmpeg -ss 900 -i "foo.mkv" -vframes 100 -vf cropdetect -f null - 2>&1

but I'd like to do it with ffprobe simply because I'm trying to use this in a bash script, I have a bunch of ifs and elses depending on quality and format of the input before composing the final ffmpeg command and I want to leverage the json output from ffprobe
Regardless of what ever I tried I cannot use any of the video filters listed in documentation, and there are no examples listed there either. Does anyone know how to run a similar cropdetect filter with ffprobe?
I had some luck with:
ffprobe -f lavfi -i "movie=foo.mkv,cropdetect" -show_entries frame=pkt_pts_time:frame_tags -print_format json

But this seemingly print cropdetect for every frame in the video.

A: set packet_tags.
ffprobe -f lavfi -i movie=foo.mkv,cropdetect -show_entries packet_tags=lavfi.cropdetect.x1,lavfi.cropdetect.x2,lavfi.cropdetect.y1,lavfi.cropdetect.y2,lavfi.cropdetect.w,lavfi.cropdetect.h,lavfi.cropdetect.x,lavfi.cropdetect.y -print_format json


text:
Q: Regions of intersected hyperplanes
Let $\mathcal{A}$ be a linear arrangement of hyperplanes in
  $\mathbb{R}^n$ and $\mathcal{B} := \bigcap_{h \in \mathcal{A}} h$.
  Show that $ \mathcal{C} := \{ h / \mathcal{B} : h \in
 \mathcal{A}\}$ is an arrangement of hyperplanes in $\mathbb{R}^n
 / \mathcal{B}$ with the same number of regions as
  $\mathcal{A}$.

I'm not really sure what $\mathcal{B}$ contain, maybe vectors? If e.g. I take the $\mathbb{R}^2$ and set $\mathcal{A}$ to the two hyperplanes along the two coordinate axis, woud $\mathcal{B}$ then (only) contain the point $(0,0)$? If I am right, then the idea behind this is trivial, as $\mathcal{C}$ wouldn't change the regions, as it just removes single vectors from as well the hyperplanes as the space, but how can I prove that formally?
[Edit]
Question fixed as Andreas Blass suggested.


text:
Q: setting google map from and to direction from input fields I have two fields a from and to and I just simply want to display the from and to on the map upon submitting.
I am having trouble figuring out the origin and destination options for the map.
HTML:
    <!DOCTYPE html>

    <meta charset="UTF-8">
    <title>test</title>
    <link rel="stylesheet" href="main.css">

        <input type="text" name="from" placeholder="From" class="special">
        <input type="text" name="from" placeholder="To">
        <input type="submit">

A: // change form code like this

<form>

        <input type="text" name="from" placeholder="From" class="special">
        <input type="text" name="to" placeholder="To">
        <input type="submit" >

 </form>

// using jquery update your map


text:
Q: Onsager's hypothesis: why is true that correlations decay with increasing time? I am studying from Chandler's book (Introduction to Modern Statistical Mechanics) the fluctuation-dissipation theorem. Before introducing it, the book states something without really demonstrating it. It says that the time correlation function of fluctuations goes to zero when the time difference between the two instants that appear in the formula goes to infinity, namely:
$$C(t)=\int dxf(x)\delta A(t';x)\delta A(t'+t;x) \rightarrow0 \quad as \quad t\rightarrow +\infty$$
where $\delta A(t)$ is the fluctuation  at time $t$ of $A(t)$ from the time-independent average value $\langle A\rangle$, and $f(x)$ is the probability density function of phase space points. This comes from stating that for large $t$ we have
$$\langle \delta A(t')\delta A(t'+t)\rangle\rightarrow\langle\delta A(t')\rangle\langle\delta A(t'+t)\rangle$$
I cannot justify this last statement. Where does it come from? Is it an axiom?

A: At equilibrium, one would expect fluctuations $\delta A$ at a time $t'$ and fluctuations at a time $t'+t$ would become statistically independent when $t \rightarrow + \infty$.
The average of a product of statistically independent variables is the product of the averages.


text:
Q: Are the lifts of homotopic curves necessarily homotopic? Studying for an exam I fail to understand (this among many things) the connection between the homotopy of functions to that of their lifts.
Let $X, Y$ be path-connected topological spaces.
$p:X\to Y$ is a covering map, and $f,g:[0,1]\to Y$ are two loops with same origin such that $f(0)=f(1)=g(0)=g(1)=y_0$,
$\hat f,\hat g:[0,1]\to X$ their lifts with $\hat f(0)=\hat g(0) = x_0$
Is the fact that $[f]=[g]$ (homotopy relation) means $[\hat f]=[\hat g]$ (homotopy of lifts)?
What are the conditions for that to happen, and why?

*

*I struggled a bit trying to define a homotopy between the two lifts, but I needed some inverse projection from $Y$ to $X$. meaning - I can project $\hat f$ using $p$ to get $p\circ \hat f=f$, then deform it using the given homotopy $H$ until I reach $g$, but then what?

*I know the lift is unique (given an anchor $x_0$), so there is a function $h$ that send a curve to its lift anchored in $x_0$, but how can tell if that function is continuous (or having some other interesting property)? I such $h$ was continuous, I could maybe use it to define the mentioned homotopy...

A: This always happens and is due mostly to the homotopy lifting property a property which covering spaces are guaranteed:

Given a covering space $p:\tilde X \rightarrow X$, a homotopy $f:Y \times I \rightarrow X$ and a map $\tilde f_0:X \rightarrow E$ lifting $f_0$ then there is a unique homotopy $\tilde f:Y \times I \rightarrow E$ of $\tilde f_0$ that lifts $f$.

The proof should be in your course text but goes something like this. For each point $y\in Y$ you build a lift $\tilde f: N\times I \rightarrow E$ for a small neighborhood $N$ of $y$ then notice each $f(N \times I)$ is contained in some $U_i$ from the corresponding open cover $\{U_{\alpha}\}$ of $X$ that gets disjoint homeomorphic copies by $p^{-1}(U_i)$. So that $\tilde f(N\times I)$ must be in one of these sheets and hence for overlapping $N$, $\tilde f$ agrees and we build a lift on all $Y\times I$.
To finish by directly addressing your situation, you have $[f] = [g]$ so we have a homotopy $F:I\times I \rightarrow Y$ with $F(t,0) = f$, $F(t,1)=g$ and further a lift $\hat f$ of $f$ then by the homotopy lifting property we have a homotopy $\tilde F:I\times I \rightarrow X$ that lifts $F$. Giving us $\tilde g = \tilde F(t,1)$ is a lift of $g$ with $[\hat f] = [\tilde g]$. But how do we know $\tilde g = \hat g$ the given lift of $g$? Because of a second easily proven theorem about lifts:

Given a covering space $p:\tilde X \rightarrow X$ and map $f:Y \rightarrow X$ with two lifts $\tilde f_1,\tilde f_2:Y \rightarrow \tilde X$ that agree at one point, then if $Y$ is connected they must agree on all $Y$.

Now with the fact that $I$ is connected and since $\hat g(0) = x_0 = \hat f(0) = \tilde F(0,s) = \tilde g(0)$ we have that $\hat g = \tilde g$ and finally $[\hat f] = [\hat g]$.


text:
Q: how to add picture on above text how I put a picture on top the hyperlinks  like in the middle and I want to put two text  between the picture  above the hyperlinks  but I   try it, but its always going on top the orange bar how I do code this so it goes  in front the orange bar? Thanks.

        #nav {
        width: 110%;
            height: 150px;
          float: left;
        padding: 0px;
        list-style: none;
        background-color: darkorange;
         }
        #nav li {
        float: left; }

        #nav li a {
        display: block;
        padding: 55px 55px;
        text-decoration: none;
        font-weight: bold;
        color: #069;
            margin-right: 284px;
           padding-top: 105px;
            font-size: 25px
         }
        #nav li a: {
        color: blue;
        background-color: darkorange; }

    <title> Malta Youth Group</title>

About Us

Lastest activties

How to join

Contact us

A: I'm not sure is this what you want to do, but let's try this:

   #nav {
    width: 110%;
        height: 150px;
      float: left;
    padding: 0px;
    list-style: none;
    background-color: darkorange;
     }
    #nav li {
    float: left; }

    #nav li a {
    display: block;
    padding: 55px 55px;
    text-decoration: none;
    font-weight: bold;
    color: #069;
        margin-right: 284px;
       padding-top: 105px;
        font-size: 25px
     }
    #nav li a: {
    color: blue;
    background-color: darkorange;
    }
    img {
      position: absolute;
      top: 75px;
      }
    }

About Us

Lastest activties

How to join

Contact us


text:
Q: How to re-index documents in Solr without knowing last modified time? How to handle the following scenario in Solr's DataImportHandler? We do a full import of all our documents once daily (the full indexing takes about 1 hour to run). All our documents are in two classes, say A and B. Only 3% of the documents belong to class A and these documents get modified often. We re-index documents in class A every 10 mins via deltaQuery by using the modified time. All fine till here.
Now, we also want to re-index ALL documents in class A once every hour (because we have a view_count column in a different table and the document modified time does not change when we update the view_count). How to do this?
Update (short-term solution): For now we decided to not use the modified time in the delta at all and simply re-index all documents in class A every 10 mins. It takes only 3 mins to index class A docs so we are OK for now. Any solution will be of help though.

A: Rather than using separate query an deltaQuery parameters in your DIH DB config, I chose to follow the suggestion found here, which allows you to use the same query logic for both full and partial updates by passing different parameters to Solr to perform either a full import or a delta import.
In both cases, you would pass ?command=full-import, but for a full import you would pass &clean=true as a URL parameter, for a delta you would pass &clean=false, which would affect the # of records returned from the query as well as tell Solr whether or not to flush and start over.

A: I found one can use ExternalFileField to store the view count and use a function query to sort the results based on that field. (I asked another question about this on SO: ExternalFileField in Solr 3.6.)  However, I found that these fields cannot be returned in the Solr result set, which meant I needed to do a DB call to get the values for the fields. I don't want to do that.
Found an alternate solution: When trying to understand Mike Klostermeyer's answer, I found that command=full-import can also take an additional query param: entity. So now I set up  two top-level entities inside the <document> tag in data-config.xml - the first one will only index docs in class A and the second one will only index docs in class B. For class A documents we do a delta import based on last modified time every 5 mins and a full import every hour (to get the view_count updated). For class B documents, we only do one full import every day and no delta imports.
This essentially gives three different execution plans to run at different time intervals.
There is also one caveat though: need to pass query param clean=false every time I run the import for an entity; otherwise the docs in the other entity get deleted after indexing completes.
One thing I don't like about the approach is the copy-pasting of all the queries and sub-entities from one top entity to the other. The only difference between the queries in the top-level entities is whether the doc is in class A or class B.


text:
Q: Can I use Yii2 classes to get the raw database table schema? Can I use the Yii2 core classes to read the raw schema for a database table? So that I get the list of columns, types, lengths, etc?
Have tried looking at yii\db\mysql\Schema but can't figure out how to use it manually. I know Yii2 does it internally since the models automatically reflect the columns in the table...

A: You can use Yii::$app->db->getSchema() or Yii::$app->db->schema to get instance of yii\db\Schema. Then you can use its getTableSchema() method to get instance of yii\db\TableSchema for specific table and so on.


text:
Q: Running Java Program from Folder Mac with Terminal So I'm used to creating a single Java file and putting it into the desktop and running it from the terminal on mac (cd Desktop/, javac HelloWorld.java, java HelloWorld). Now I have a program that has multiple classes. My question is how to run a program from a folder. I have around 5 .java files in my folder and I need to run the one with the main class.

A: Writing multiple classes in single file or writing them in different .java files changes nothing. Finally, you have no. of .class files equal to no. of classes you have defined in your .java files.
The JVM checks for the public static void main(String[] args) in your class file to run the program(BTW you can also overload it but the above one is what is called first). You can also write main() method in every class. I believe that's why you use class name to run the program like java HelloWorld.

A: You should just use the name of the entry point class instead of HelloWorld, other classes will be compiled and used automatically.
The entry point class is the one that contains method
public static void main(String[] args)


text:
Q: subgroups is normal if it is the only subgroups that has order n? In my last lecture in Abstract Algebra the lecturer used this proposition:

Let $G$ be a group and $H \leq G$ subgroup of G. if $H$ is the only
  subgroup that $\mid H \mid = n$ of G then $H \lhd G$

I cant understand why..
P.S: we proved before that:
For all $g \in G$ then $ gH g^{-1} \cong H $ and   $gH g^{-1} \leq G$

A: Here automatically $H=gHg^{-1}$ for each $g$. This because $|gHg^{-1}|=n$

A: I suggest you to show that under problem's conditions, $gHg^{-1}\leq G$ and $$|g^{-1}Hg|=|H|=n$$

*

*$gHg^{-1}\neq \emptyset$.

*$(gh_1g^{-1})(gh_2g^{-1})=gh_1h_2g^{-1}\in gHg^{-1}$.

*$(ghg^{-1})^{-1}=gh^{-1}g^{-1}\in gHg^{-1}$.


text:
Q: Prevent Label to be re-aligned after askdirectory() is closed I built a window which display some labels, an entry field and a button. The button opens a tkinter.filedialog.askdirectory(). After I choose a directory and close the dialog another label is updated along with the text entry with the choice.
The problem is that after this happens the description of the text entry (another Label on its left) is realigned in its cell. I don't know why this happens, is there any behind-the-scenes behaviour which I'm not aware of?
Here's the sample code I use.
from tkinter import *
from tkinter import filedialog
from tkinter import ttk

def folderDiag():
    scanfolder.set(filedialog.askdirectory())

c = (N, W, S, E)
scanfolder = StringVar()

root = Tk()
root.title("Testing")
root.columnconfigure(0, weight=1)
root.rowconfigure(0, weight=1)

frame = ttk.Frame(root, padding="3")
frame.grid(column=0, row=0, sticky=c)
frame.columnconfigure(0, weight=1)
frame.columnconfigure(1, weight=1)
frame.columnconfigure(2, weight=1)
frame.rowconfigure(0, weight=1)
frame.rowconfigure(1, weight=1)
frame.rowconfigure(2, weight=1)
ttk.Label(frame, text="Welcome!",
          font="TkDefaultFont 24 bold").grid(column=0, row=0, columnspan=4,
                                             sticky=c)
# This label will be centered after dialog is closed
ttk.Label(frame, text="Select folder to scan:").grid(column=0, row=1, sticky=E)
ttk.Label(frame, textvariable=scanfolder).grid(column=2, row=2)

scan_folder_entry = ttk.Entry(frame, textvariable=scanfolder).grid(column=3,
                                                                   row=1)
browse_button = ttk.Button(frame, text="Browse...",
                           command=folderDiag).grid(column=4, row=1)

root.mainloop()
exit(1)

A: if I understand correctly, you need this:
|    0    |         1         |      2     |  # Column number
|                Welcome!                  |
| Select  |       Entry       |   Button   |
| Your label                               |

So:
from tkinter import *
from tkinter import filedialog
from tkinter import ttk

def folderDiag():
    scanfolder.set(filedialog.askdirectory())

root = Tk()

c = (N, W, S, E)
scanfolder = StringVar()

root.title("Testing")
root.columnconfigure(0, weight=1)
root.rowconfigure(0, weight=1)

frame = ttk.Frame(root, padding="3")
frame.grid(column=0, row=0, sticky=c)
frame.columnconfigure(0, weight=0)
frame.columnconfigure(1, weight=1)
frame.columnconfigure(2, weight=0)
frame.rowconfigure(0, weight=1)
frame.rowconfigure(1, weight=1)
frame.rowconfigure(2, weight=1)
ttk.Label(frame, text="Welcome!",
          font="TkDefaultFont 24 bold").grid(column=0, row=0, columnspan=3,
                                             sticky=c)
ttk.Label(frame, text="Select folder to scan:").grid(column=0, row=1, sticky=E)
ttk.Label(frame, textvariable=scanfolder, justify=LEFT).grid(column=0, columnspan=3, row=2, sticky=W)

scan_folder_entry = ttk.Entry(frame, textvariable=scanfolder)
scan_folder_entry.grid(column=1, row=1, sticky=EW)
browse_button = ttk.Button(frame, text="Browse...",
                           command=folderDiag)
browse_button.grid(column=2, row=1)

root.mainloop()

Your code create this layout:
|   0    | 1 |    2    |    3   |    4   |
| Welcome                       |  ---   |
| Select | - |   ---   | Entry  | Button |
|   ---  | - |  Label  |   ---  |   ---  |

For some reason you leave #1 empty. Its width = const = 0. Forget about it.
Select doesn't attached to Entry. Columns #1 and #2 separate them. Select attached to right edge of #0 column.
When you update Label you increase width of #2 column => you increase space between #0 (Select) and #3 (Entry). Select stay attached to right edge of #0.


text:
Q: Key and Required data annotations When using the entity framework there are the following data annotations:

*

*System.ComponentModel.DataAnnotations.KeyAttribute

*System.ComponentModel.DataAnnotations.RequiredAttribute
Just for reference, I using the definitions from this wiki article:

Primary Key

*

*A primary key cannot allow null values. (You cannot define a primary key on columns that allow nulls.)

*Each table can have at most one primary key.

  Unique Key

*

*A unique key can allow null values. (You can define a unique key on columns that allow nulls.)

*Each table can have multiple unique keys.

Is the KeyAttribute used to denote a primary key or is it used to denote a unique key?
When using annotations would the following be considered reduntant or necessary?
class Example
{
    [Required(), Key()]
    public int Id { get; set; }
    ...
}

A: In your example, that would be redundant as your models require a key value to uniquely identify them once they have been annotated with Key.
And as an aside, if you are using Code-First, even Key would be redundant as by convention a property called Id or ModelNameId would be used for your primary key.


text:
Q: Python set parameter value for subsequent function calls Is there an option in Python to define a parameter values for some functions so that those values are used when the mentioned functions are called?
Something like this in TF Slim: https://www.tensorflow.org/api_docs/python/tf/contrib/framework/arg_scope
Example:
set_default_params(functions=[func_1, func_2], params=[param_1=value_1, param_2=value_2, param_3=value_3])

After this, when  I call func_1() which has default params param_1=0 and param_2=None, it would actually get param_1=value_1 and param_2=value_2 without the need to set it manually when calling func_1().

A: You can use functools.partial to set default parameters. This partially applies parameters to a given function.
import functools

def func(param, *args, **kwargs):
    print('param:', param)
    print('args:', *args)
    print('kwargs:', kwargs)

g = functools.partial(func, 21)      # sets default value for param to 21
g('arg1', 'arg2', 'arg3', kw='kwarg1')

Output:
param: 21
args: arg1 arg2 arg3
kwargs: {'kw': 'kwarg1'}

Note that a new function is returned from functools.partial and the default parameters aren't set in-place as your set_default_params call implies.

A: If you want to be able to set params in the future, you can use some kind of decorators to do it.
def kind_of_decorator(func, params):
    def wrapper(*args, **kwargs):
        return func(*args, **dict(kwargs, **params))
    return wrapper

def foo(x, y=2):
    return x + y

print(foo(1, 5)) # prints 6
print(foo(3))    # prints 5

new_foo = kind_of_decorator(foo, {'y': 0})

print(new_foo(1, y=5))  # prints 6
print(new_foo(3))       # prints 3
#print(new_foo(1, 5))   # an error "TypeError: bar() got multiple values for argument 'y'" be careful there. Now only kwargs are allowed for `y`

A: Maybe not quite in that form, but if you define a function with def function(arg={}), then the arg argument's default value will persist between calls rather than being set to a new object. That means you could use:
def function1(arg1, arg2=None, arg3=None, args={"arg2": 42, "arg3": 43}):
    if arg2 is not None:
        args["arg2"] = arg2
    if arg3 is not None:
        args["arg3"] = arg3
    arg2, arg3 = args["arg2"], args["arg3"]
    print(arg1, arg2, arg3)

function1(1)  # prints 1 42 43; using default values for arg2 and arg3
function1(1, 2) # prints 1 2 43; replace arg2 but keep arg3
function1(1, arg3=3) # prints 1 2 3; replace arg3 but keep arg2 from previous call
function1(0)  # prints 0 2 3; both arg2 and arg3 persist from previous calls.