text:
Q: Winword: Connection to Word Add-In (dotm file) does not stick after closing and re-opening Word file I have written some Word macros stored in an .dotm file saved in a folder on my computer (not the default personal folder of Word).
I then went to File - Options - Add-Ins - Word Add-In and connect to this file.

Now I can run macros from the .dotm file
I then save, close and re-open the Word file. But everytime I do so, I have to reonnect to the .dotm file again.
Anyway to make this connection permanent?
I tried to trust Add-In and added this folder to Trusted Locations in Word Options but that did not help.


text:
Q: Email delivery fails for email which does not exist I want to know what happens if an email delivery fails because email account does not exist and if someone creates same account later then what happens to failed mail delivery. Does email server keeps trying to send that email or it tries only one time?

A: Mail Daemon will return the e-mail when the recipient can't be found. It will not keep trying to send that e-mail if the account is made later.

A: When the receiving SMTP server reports that the account does not exist the mail is "bounced" immediately and the sender is informed. No further actions are carried out unless the sender resends the mail.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Ebean Finder: find items NOT matching criteria I would like to search items with Ebean in Play Framework 2.1 using Finder and find the one that are not mathing the criteria. Some kind of left join a_table t ... where t.id is null (or maybe a where not exists).
I could not find how to do that by reading Ebean's API. Google does not help either.
Is it possible to do it?
If yes, how?
To give an exemple, let's say I have persons that have year-subscriptions. I would like to retrieve the persons that do not have a current subscription.
public class Person {
    @OneToMany(mappedBy = "person", cascade = CascadeType.ALL)
    public List<Subscription> subscriptions;
}

Thanks!
Alban

A: I finally used com.avaje.ebean.Query.
For my example:
String q = "find * fetch subscriptions "
         + "where subscriptions.startDate > :today "
         + "   or subscriptions.endDate < :today "
         + "   or subscriptions.id is null";
Query<Person> query = Ebean.createQuery(Person.class, q);
query.setParameter("today", LocalDate.now());
return query.findList();

And it seems to work.


text:
Q: keras_vggface: No module named 'keras.engine.topology' There are several tutorials online that import a VGGFace model from keras_vggface like this:
from keras_vggface.vggface import VGGFace

However, I get the following error:
ModuleNotFoundError: No module named 'keras.engine.topology'

This problem happens on my local machine, but also on Google Colab after installing keras_vggface with
!pip install keras_vggface

A: I solved this issue in Google Colab by changing the import from
from keras.engine.topology import get_source_inputs

to
from keras.utils.layer_utils import get_source_inputs

in usr/local/lib/python3.7/dist-packages/keras_vggface/models.py

A: ! pip install git+https://github.com/rcmalli/keras-vggface.git
!pip install keras_applications --no-deps
filename = "/usr/local/lib/python3.7/dist-packages/keras_vggface/models.py"
text = open(filename).read()
open(filename, "w+").write(text.replace('keras.engine.topology', 'tensorflow.keras.utils'))
import tensorflow as tf

from keras_vggface.vggface import VGGFace

vggface = VGGFace(model='resnet50') # or VGGFace() as default

worked for me and colab

A: I think you need to install it as below:
!pip install keras_vggface

It should work


text:
Q: Need all rights to my MySQL user I was trying to create a new db when suddenly it said I don't have rights. The user I am logged in is root . I tried giving all the privileges with grant all Permission but my user doesn't have rights to execute it. I even tried select * from MySQL.user And as I expected I don't have rights. This is my local test system where I had done the setup and I remember that I have not created any other user. I am totally lost and have no idea where to look. Need help !

A: Stop mysqld and restart it with the --skip-grant-tables option.
Connect to the mysqld server with just: mysql (i.e. no -p option, and username may not be required).
Issue the following commands in the mysql client:
UPDATE mysql.user SET Grant_priv='Y', Super_priv='Y' WHERE User='root';

FLUSH PRIVILEGES;

After that, you should be able to run GRANT ALL ON . TO 'admin'@'localhost'; and have it work.
or
Stop MySQL service
Run mysqld_safe --skip-grant-tables &
Type mysql -u root -p and press enter.
Enter your password
At the mysql command line enter:
use mysql;

Then execute this query:
insert into `user` (`Host`, `User`, `Password`, `Select_priv`, `Insert_priv`, `Update_priv`, `Delete_priv`, `Create_priv`, `Drop_priv`, `Reload_priv`, `Shutdown_priv`, `Process_priv`, `File_priv`, `Grant_priv`, `References_priv`, `Index_priv`, `Alter_priv`, `Show_db_priv`, `Super_priv`, `Create_tmp_table_priv`, `Lock_tables_priv`, `Execute_priv`, `Repl_slave_priv`, `Repl_client_priv`, `Create_view_priv`, `Show_view_priv`, `Create_routine_priv`, `Alter_routine_priv`, `Create_user_priv`, `ssl_type`, `ssl_cipher`, `x509_issuer`, `x509_subject`, `max_questions`, `max_updates`, `max_connections`, `max_user_connections`)
values('localhost','admin','','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','','','','','0','0','0','0');


text:
Q: Vertically Aligning Input Elements I'm having a bit of trouble with the following code. I have an absolutely positioned div, inside of which I have 3 elements: 1 text input, 1 password and a button containing an image. The markup is as follows:

            <input type="text" id="username" />
            <input type="password" id="password" />
            <button type="submit" id="login"></button>

And the CSS:
div#credentials
{
    position: absolute;
    right: 5px;
    top: 10px;
    background-color: #494949;
}

#username
{
    font-family: 'Lucida Sans', Arial, Helvetica, sans-serif;
    font-size: 8pt;
    color: #AAA;
    padding: 3px;
    margin: 0px;
}

#password
{
    font-size: 8pt;
    color: #AAA;
    padding: 3px;
    margin: 0px;
}

#login
{   background: transparent;
    border: 0px;
    padding: 3px;
    cursor: pointer;
}

It looks as though the two first elements are situated at bottom of the div, and the button is situated at the top. I'd like to vertically align all 3 elements in the middle of the div, but after trying a number of different padding/margin combinations couldn't find anything that looks presentable across browsers. Does anyone have any experience with this issue?

A: Try the vertical-align property
input, button {
    vertical-align:middle;
}

A: Good vertical layout with display: list-item; at Align vertically input elements in div
No luck in Chrome/FireFox/Opera/Safari with vertical-align: …;


text:
Q: AWS SSM Parameters Store Is there anyway to just nuke / remove all items in AWS Parameters Store?
All the command line I found are to remove it either one by one or remove it given a list of names.
I also tried using
aws ssm delete-parameters --cli-input-json test.json

with test.json file looks like this
{
    "Names": [
        "test1",
        "test2"
    ]
}

still does not work..
Ideally if I can use --query and use it as is, that'd be great.
I'm using --query like so
aws ssm get-parameters-by-path --path / --max-items 2 --query 'Parameters[*].[Name]'

A: When you need to delete all parameters by path in AWS Systems Manager Parameter Store and there are more than 10 parameters you have to deal with pagination.
Otherwise, an the command will fail with the error:
An error occurred (ValidationException) when calling the DeleteParameters operation: 1 validation error detected: Value '[/config/application/prop1, ...]' at 'names' failed to satisfy constraint: Member must have length less than or equal to 10

The following Bash script using AWS CLI pagination options deletes any number of parameters from AWS SSM Parameter Store by path:
#!/bin/bash

path=/config/application_dev/

while : ; do
  aws ssm delete-parameters --names $(aws ssm get-parameters-by-path --path "$path" --query "Parameters[*].Name" --output text --max-items 10 $starting_token | grep -v None)
  next_token=$(aws ssm get-parameters-by-path --path "$path" --query NextToken --output text --max-items 10 | grep -v None)
  if [ -z "$next_token" ]; then
    starting_token=""
    break
  else
    starting_token="--starting-token $next_token"
  fi
done

A: You can combine get-parameters-by-path with delete-parameters:
aws ssm delete-parameters --names `aws ssm get-parameters-by-path --path / --query Parameters[].Name --output text`

I tested it by creating two parameters, then running the above command. It successfully deleted by parameters.

A: try this and execute multiple times
aws ssm delete-parameters --names `aws ssm get-parameters-by-path --path / --recursive --query Parameters[].Name --output text --max-items 9`

A: Adding to the above. I had to delete around 400 params from the parameter store. Ran the below in command line and it did it! (Change 45 in for loop to whatever number you like);
for ((n=0;n<**45**;n++)); do
    aws ssm delete-parameters --names `aws ssm get-parameters-by-path --path / --recursive --query Parameters[].Name --output text --max-items 9`
done

A: This is my one line solution for this:
$ for key in $(aws ssm get-parameters-by-path --path "/" --recursive | jq -r '.Parameters[] | .Name' | tr '\r\n' ' '); do aws ssm delete-parameter --name ${key}; done

NOTE: Be careful if you copy & paste this as it will remove everything under "/"


text:
Q: Java. Scanner requests an additional line but does not print it just entered this community and this is my first question here, so please bear with a noob. I created two classes, first is Student, a basic one with fields, constructor and getters. The second one has the main method, a LinkedList, a multiple-entry Scanner (for...) and two simple methods.
My problem is that despite the fact that the For loop has maximum index 1 (x = 0; x < 2), the Scanner expects a third row input and an enter but does not print the third line. I add the two classes, maybe I made a mistake and I would appreciate your help. Thank you in advance.
public class Student {

private String name;
private String surname;
private int firstMark;
private int secondMark;
private int finalExamMark;

public Student(String name, String surname, int firstMark, int secondMark, int finalExamMark) {
    this.name = name;
    this.surname = surname;
    this.firstMark = firstMark;
    this.secondMark = secondMark;
    this.finalExamMark = finalExamMark;
}

public String getName() {
    return name;
}

public String getSurname() {
    return surname;
}

public int getFirstMark() {
    return firstMark;
}

public int getSecondMark() {
    return secondMark;
}

public int getFinalExamMark() {
    return finalExamMark;
}

@Override
public String toString (){
    return this.name + " " + this.surname + " got " + this.firstMark + " at English, " + this.secondMark + " at Math and " + this.finalExamMark + " at the final exam.";
}

}

public class StudentMain {
static LinkedList<Student> courseAttend = new LinkedList<>();
static Scanner scanner = new Scanner(System.in);

public static void main(String[] args) {
    addStudent();
    printList(courseAttend);
}

private static void addStudent()  {
    for (int x = 0; x < 2; x++) {
        String s1 = scanner.nextLine();
            String[] split = s1.split("\\s");
            courseAttend.add(new Student(split[0], split[1], Integer.parseInt(split[2]), Integer.parseInt(split[3]), Integer.parseInt(split[4])));
            scanner.nextLine();
    }
    scanner.close();
    }

private static void printList(LinkedList<Student> lista) {
    for (Student elem : lista) {
        System.out.println(elem);
    }
}

}

For example, if I input (without quotes)
"Young John 9 9 9"
"Johnson Anne 8 8 8" and I press enter, the cursor moves to next line and waits another input. Only after that third line and the final enter, the message is displayed but the third line is not shown.

A: *

*courseAttend should be a List<Student> courseAttend = new ...List<>(); like your methode argument printList(List<Student> students) because both could be also a ArrayList and it is the normal way to in implement variables if they have not to be sepciefied, like in your case.

*The loop has two nextLine() but you ignore the second one so you are creating a student and waiting of the next input and not saving the input

*When a User has to enter multiple arguments for any given prompt, you can expect to have typos. Your prompt expects the User to enter 5 arguments and they are not even from the same typ on a single line delimited with a whitespace. What if the user accidentally give you an ivalid input like a integer as name or a String as mark.
public class StudentMain {
    static List<Student> courseAttend = new LinkedList<>();
    static Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        for (int x = 0; x < 2; x++) {
            courseAttend.add(createStudent());
        }
        scanner.close();
        printList(courseAttend);
    }

    private static Student createStudent(){
        System.out.print("name: ");
        String name = scanner.nextLine();
        System.out.print("surname: ");
        String surname = scanner.nextLine();
        System.out.print("first mark: ");
        int firstMark = scanner.nextInt();
        System.out.print("second mark: ");
        int secondMark = scanner.nextInt();
        System.out.print("final exam mark: ");
        int finalExamMark = scanner.nextInt();

        return new Student(name, surname, firstMark, secondMark ,finalExamMark);
     }

     private static void printList(List<Student> students) {
         for (Student elem : students) {
             System.out.println(elem);
         }
     }
}


text:
Q: Segmentation fault when looking up host name and IP address I have the following piece of code for getting the hostname and IP address,
#include <stdlib.h>
#include <stdio.h>
#include <netdb.h> /* This is the header file needed for gethostbyname() */
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

int main(int argc, char *argv[])
{
struct hostent *he;

if (argc!=2){
printf("Usage: %s <hostname>\n",argv[0]);
exit(-1);
}

if ((he=gethostbyname(argv[1]))==NULL){
printf("gethostbyname() error\n");
exit(-1);
}

printf("Hostname : %s\n",he->h_name); /* prints the hostname */
printf("IP Address: %s\n",inet_ntoa(*((struct in_addr *)he->h_addr))); /* prints IP address */
}

But I am getting a warning during compilation:
$cc host.c -o host
host.c: In function 'main':
host.c:24: warning: format '%s' expects type 'char *', but argument 2 has type 'int'

Then there is a segmentation fault when I run the code:
./host 192.168.1.4
Hostname : 192.168.1.4
Segmentation fault

What is the error in the code?

A: I had a similar code (if not the same) and it compiled fine in a machine in our school laboratory, but when I compiled it on my machine at home, it had the same error (I didn't edit the code).  I read the man page for inet, and found that I had one header file missing, which is the #include <arpa/inet.h>. After I added that header to my C program, it compiled and run fine.

A: The warning about the mismatch for the printf format is an important warning.
In this case, it comes because the compiler is thinking that the function inet_ntoa returns an int, but you specified to expect a string in the format-string.
The incorrect return-type for inet_ntoa is the result of an old C rule that states that if you try to use a function without a prior declaration, then the compiler must assume the function returns an int and takes an unknown (but fixed) number of arguments.
The mismatch between the assumed return type and the actual return type of the function results in undefined behaviour, which manifests itself as a crash in your case.
The solution is to include the correct header for inet_ntoa.

A: Break this code:
printf("IP Address: %s\n",inet_ntoa(*((struct in_addr *)he->h_addr)));

Into this:
struct in_addr* address = (in_addr*) he->h_addr;
char* ip_address = inet_ntoa(*address);
printf("IP address: %s\n", ip_address);

It also makes it easier to debug and pinpoint the problem.

A: Actually, I just compiled that code on my FreeBSD machine at home and it works.

A: You could try dumping the value of he->h_addr before trying to dereference it and pass it to inet_ntoa.  If it was NULL, that would result in a seg fault.
How about running it through strace?


text:
Q: Enter matched front of value with key to element in dataframe pandas I'm creating a dataframe using
data_df = pd.DataFrame(
        {'time_stamp': pd.date_range(date_fromx, date_tox, freq=time_length, tz=timezone)}
    )
    data_df['data'] = np.nan

Where I'm making time_stamp column timezone aware to match the data in list of dictionaries like below
I have a lists of dictionaries like
[{'time_stamp': '2022-10-07T00:00:00.000Z', 'data': 8044.849457711932}, {'time_stamp': '2022-10-07T00:15:00.000Z', 'data': 4997.691731774312}, {'time_stamp': '2022-10-07T00:30:00.000Z', 'data': 6984.109211541678}, {'time_stamp': '2022-10-07T00:45:00.000Z', 'data': 5492.891985861485}, {'time_stamp': '2022-10-07T01:00:00.000Z', 'data': 5473.0496118099745}, {'time_stamp': '2022-10-07T01:15:00.000Z', 'data': 6501.250396808703}, {'time_stamp': '2022-10-07T01:30:00.000Z', 'data': 6017.03827304475}, {'time_stamp': '2022-10-07T01:45:00.000Z', 'data': 7511.133012466583}, {'time_stamp': '2022-10-07T02:00:00.000Z', 'data': 5942.32914821161}]

The problem
I have few missing dates in list of dictionaries with time_stamp and data. I want to show the missing dates with empty data in front of it.
I'm trying to match the key in list of dictionaries with the dates in my dataframe and enter data in from the matching key in front of the matched date in dataframe.
I have tried creating a new dataframe using lists of dictionaries and merge using that with
usage_df = pd.DataFrame(usage_data) #usage_data is list of dictionaries

map_dict = dict(zip(usage_df['time_stamp'], usage_df['data']))
data_df['data'] = data_df['time_stamp'].map(usage_data)

But this is missing few of the datas at the end.
Also by concating like
merged_df = pd.concat([data_df, usage_df], ignore_index=True)


text:
Q: Calculate bezier curve control points with given angle Lets assume we have a bezier curve with a start p0 of (0, 0) and an end p4 of (100, 0). Right now it would basically be a line with no curve yet. Now lets assume I want to calculate the two missing control points (p1 p2) based on a given angle. What is the best way to achieve this?
Lets assume I wanted something like this:
https://1.bp.blogspot.com/_W3ZUYKgeEpk/SDcAerq1xkI/AAAAAAAAAAc/W9OnovkzgPI/s400/RectanglularControlPoly.jpg
I mean depending on the position of the control points it forms a triangle of some sort, that is why I was wondering if its possible.

A: Controls points that go through a Bezier point with a given angle, lie on the tangent with that angle.
The resulting bending will be the softer the farther away the control point is chosen, so there are many different solutions with the same angle and different curvature..

To find control points with equally soft curvatures for two Bezier points simply find the crossing of the two tangents! Use the crossing as the common control point for both segments, i.e. have C1 = C2.
For any sort of symmetrical curve you need to keep the deviations from the crossing symmetrical, i.e. 50%, 10% etc..
Note that for optimizing the overall shape one also needs to look at the neighbouring points; in general the provided GDI function does a good job; so it is worth considering simply adding more Bezier points for controlling the shape; but of course using the perfect set of control points is the most economic solution.
Update: I have added an example of how well a circle (orange) gets approximated by the math in this interesting post.
Short version: An exact solution isn't really possible but the best fit for a quarter circle is to move the control point to ~0.55% of the crossing point. (d=r*4*(sqrt(2)-1)/3). Sometimes instead of using a 4 segment solution an 8 segment solution is used for even closer approximation..
private void button_Click(object sender, EventArgs e)
{
    int w = Math.Abs(P2.Left - P1.Left);
    int h = Math.Abs(P2.Top - P1.Top);
    C2.Left =  (int) (P2.Left + w * 0.5523f);
    C2.Top = P2.Top;
    C1.Left = P1.Left;
    C1.Top = (int) (P1.Top + h * 0.5523f);
    C1.Parent.Invalidate();
}

The code uses Labels for the points and control points..
Btw: Adding ellipses/circles to a GraphicsPath will create bezier curves that seem to be approximated just like that.


text:
Q: C - char* is null? This is probably something simple, but I can't figure out why I can't get the value from this char*.
Here is my issue:
static char* DIR_ENTRY_PATH = NULL;

...
while (1) // infinite loop

    {

      // accept a client connection

      clientFd = accept (serverFd, clientSockAddrPtr, &clientLen);

      if (fork() == 0) // Create child proc to get dir entry info

        {

          //read dir entry info
readInfo(clientFd);
printf("dpath: %s\n", DIR_ENTRY_PATH); //prints out the the correct value (DIR_ENTRY_PATH set in readInfo)
int test = 1;
      //get dir entry info and write back
      DIR *dir;
      struct dirent *entry; //pointer to dir entry
      struct stat stbuf; //contains file info

      if((dir = opendir(DIR_ENTRY_PATH)) == NULL){ //make sure entry is valid
        printf("error with dirent\n");
            exit(1);
      }
      else{
        printf("gathering directory entry info...\n");
        while((entry = readdir(dir)) != NULL){
            char *entryname = entry->d_name;
printf("path: %s\n", DIR_ENTRY_PATH); /*prints nothing out.. */ - PROBLEM IS HERE
printf("int: %d\n", test); //*prints 1 out.. */

...
readInfo():
//reads info from the client
void readInfo(int fdesc){
  int fd = fdesc;
  char str[200];

  readLine(fd, str); //read line in from socket
  DIR_ENTRY_PATH = str;
  printf("received path: %s\n", DIR_ENTRY_PATH); //displays correct value
}
//reads a single line
int readLine(int fdesc, char *strng){
 int fd = fdesc;
 char *str = strng;
 int n;

 do{
   n = read(fd,str, 1); //read a single character
 }while(n > 0 && *str++ != 0);
 return (n>0); //return false if eoi
}//end readLine

Why am I able to get the value of the test int but not the dir_entry_path?  Thanks for any help.

A: You are assigning a pointer to a local variable to your global variable, but once the function returns, the local variable is gone!
void readInfo(int fdesc){
  int fd = fdesc;
  char str[200];             // Local variable

  readLine(fd, str);
  DIR_ENTRY_PATH = str;      // Pointer assigned to global
  printf("received path: %s\n", DIR_ENTRY_PATH); //displays correct value
}

After the function returns, the local variable is undefined, and its storage can be reused by the next function, etc.
How to fix the problem?  There are many possible ways, but the simplest might be:
static char DIR_ENTRY_PATH[1024];

void readInfo(int fdesc){
  int fd = fdesc;
  char str[200];                  // Local variable

  readLine(fd, str);
  strcpy(DIR_ENTRY_PATH, str);    // Copy local string into global string

  printf("received path: %s\n", DIR_ENTRY_PATH); //displays correct value
}

As a stylistic point, ALL_CAPS normally denotes a macro, or an enum value (because enum is a bit like #define which uses ALL_CAPS).
I hope you have proper bounds checking on readLine().  I got lazy with my modification and simply ensured the global was (five times) longer than the local variable.  Tune to suit yourself.  I'd also use an enum for the buffer size (and a lower-case name instead of DIR_ENTRY_PATH).

A: You can allocate memory to your global pointer DIR_ENTRY_PATH before calling readInfo() or inside the function readInfo() depending on your wish.
#define DIR_ENTRY_LEN 200

void readInfo(int fdesc){
....

// Add below code <br>
strncpy(DIR_ENTRY_PATH, str, DIR_ENTRY_LEN);


text:
Q: check if two dates fall within schedule of two different dates I have a schedule per day:
8:30AM-5:30PM
Now I have downtime:
2017-03-01 10:00AM to 2017-03-02 1:00PM
I want to compute the total downtime between this two dates that falls within the schedule provided above

A: Breaking this problem to separate part will make it easy to solve. You can sum up the downtime in the first day, last day and all the days in the middle.
a = Calculating the downtime on first day is min(0,[schedule end time] - [max(downtime start hour, schedule start time)]).
b = Last day is min(0,[min(downtime end hour, schedule end time ] - [schedule start time]).
c = All the day between are: ([downtime end day] - [downtime start day] -1) * ([schedule time in 1 day])
a + b + c = downtime in schedule


text:
Q: How does Postgres atomically updates secondary indices? I understand that when a transaction performs a change, Postgres mvcc scheme stores a new row with the updated data, and an associated version.
Other transactions know which versions they should see, and they pick the appropriate row.
I also understand that that the primary index of a table stores all the versions of the row.
I can see how the primary index can be updated (you lock it for writing, append the row, and unlock. I'm not sure if this is how it works, but that is a potential way).
But how does Postgres atomically updates the secondary indexes?
I imagine that when a transaction commits, all the indices need to be updated with the new data in the row.
Is Postgres acquiring a lock on all the secondary indices to atomically update them?
If so, is the granularity of the lock at the index level or at the value level (lock only the part of the index for a specific value)?
Is the approach the same in other DB engine, like InnoDB?
I'm building a toy DB, and I'm having a hard time understanding how to efficiently update the secondary indexes.
Any paper on the topic is also welcomed!
Thanks a lot!

A: PostgreSQL does not support index-organized-tables.  So all indexes are secondary indexes.
The indexes are not updated atomically.  A process which sees an interesting entry in an index will chase it down to the table. In the table it sees that that tuple is not yet committed, so ignores it.  The system arranges to present the user with an experience of atomicity, but at the level where indexes operate there is not actual atomicity.


text:
Q: How can we add entity framework in one project and use it as a service in another project? I want a project to has entity framework nuget package ,and other project just register this service  in start-up with name of their models. I Have seen mongo version of this approach but I couldn't find any ef one.
mongo example:
In Service project:
using Autofac;
using DShop.Common.Types;
using Microsoft.Extensions.Configuration;
using MongoDB.Driver;

namespace DShop.Common.Mongo
{
 public static class Extensions
    {
        public static void AddMongo(this ContainerBuilder builder)
        {
            builder.Register(context =>
            {
                var configuration = context.Resolve<IConfiguration>();
                var options = configuration.GetOptions<MongoDbOptions>("mongo");

                return options;
            }).SingleInstance();

            builder.Register(context =>
            {
                var options = context.Resolve<MongoDbOptions>();

                return new MongoClient(options.ConnectionString);
            }).SingleInstance();

            builder.Register(context =>
            {
                var options = context.Resolve<MongoDbOptions>();
                var client = context.Resolve<MongoClient>();
                return client.GetDatabase(options.Database);

            }).InstancePerLifetimeScope();

            builder.RegisterType<MongoDbInitializer>()
                .As<IMongoDbInitializer>()
                .InstancePerLifetimeScope();

            builder.RegisterType<MongoDbSeeder>()
                .As<IMongoDbSeeder>()
                .InstancePerLifetimeScope();
        }

        public static void AddMongoRepository<TEntity>(this ContainerBuilder builder, string collectionName)
            where TEntity : IIdentifiable
            => builder.Register(ctx => new MongoRepository<TEntity>(ctx.Resolve<IMongoDatabase>(), collectionName))
                .As<IMongoRepository<TEntity>>()
                .InstancePerLifetimeScope();
    }
}

In Start up of web project:
 var builder = new ContainerBuilder();
            builder.RegisterAssemblyTypes(Assembly.GetEntryAssembly())
                .AsImplementedInterfaces();
            builder.Populate(services);
            builder.AddMongo();
            builder.AddMongoRepository<Cart>("Carts");
            builder.AddMongoRepository<Customer>("Customers");
            builder.AddMongoRepository<Product>("Products");

            Container = builder.Build();

A: An usual solution has multiple project like the web project if you are creating a web app, the test project, DAL project and so on. I have created a sample to show you how can connect project in the same solution.

*

*First create lets say an web application

*Create the Class Library project where you can create the EntityFramework part

*Install Microsoft EntityFramework in this project.

*Right click on Dependecies =>  Add Reference on web project and select the EntityFramework project.

*Open the Startup.cs in web project add the namespace using EntityFramework;of the Class Library with EntityFramework name.

*In the same file add the code to connect with database.
  services.AddDbContext<YourContext>(options => options
                        .UseSqlServer(Configuration
                        .GetConnectionString("DefaultConnectionString")));

With the same way you can connect multiple projects.


text:
Q: Edit FLASH animation I want to edit Flash animation.
I have fla, swf and swf fiels, but How I should open them?
Is there any possibility to edit swf file without fla or swd file?

A: I opened source FLA with CS3.
Also I managed to decompile SWF and delete or change frames, sprites, images, texts and scripts I need.
So to edit ready swf, we need to decompile it, and then compile again.


text:
Q: Superscript text_Grob I have a fiddley little problem! I am trying to get a superscript (i.e. the -1 in "Mg:Ca(µmol mol-1)" into a text grob but can't find the correct annotation of the script:
Axis labels
   yleft<- textGrob("Mg:Ca(µmol mol-1)",rot = 90, gp = gpar(fontsize = 12))
   bottom <- textGrob("Distance from Core (μm))", gp = gpar(fontsize = 12))

I'm a bit of a newbie, any help would be greatly appreciated!


text:
Q: How can I restore a .bak file to a new server without using the .mdf or .ldf files, programmatically with C#? Some info to get started:

*

*I am using SQL Server Express 2014

*I am using C#

*I can't use SMO functions to accomplish the following task

I am trying to restore a .bak file that I got from computer A, onto computer B.
I want to do this programmatically using C#, but not using SMO functions.
In SSMS (SQL Server Management Studio), I can manually restore a database with nothing more than a .bak file. I would like to be able to do the same running a program with C#.
I am able to restore a .bak file as long as I have the .mdf and .ldf files, but not without them. Manually doing this in SSMS seems to work so I assume that there must be a way to do this with C# as well. Here is what I have:
DBConnection connect1 = new DBConnection();
connect1.connectionString = "Data Source=" + textBox1.Text + "; Integrated Security=SSPI"; // textbox1 contains a user entered server name.

// Create a new database.
using (SqlConnection myConnection = new SqlConnection(connect1.connectionString))// set the connection to sql.
{
    SqlCommand createDB = new SqlCommand("Create Database [" + dbName + "]", myConnection);
    createDB.Connection.Open();
    createDB.ExecuteNonQuery();
}

// Restore the data from the backup into the new database.
connect1 = new DBConnection();
connect1.connectionString = "Data Source=" + textBox1.Text + "; Initial Catalog=Master; Integrated Security=SSPI";
using (SqlConnection myConnection = new SqlConnection(connect1.connectionString))// set the connection to sql.
{
    //SqlCommand createDB = new SqlCommand("Restore Database [" + dbName + "] FROM DISK = " + bakDirctory + " "
    //    + "WITH MOVE '" + oldDBName + "' TO '" + mdfDirectory + "', "
    //    + "MOVE '" + oldDBName + "_log' TO '" + ldfDirectory + "', "
    //    + "REPLACE", myConnection);
    // oldDBName contains what the name of the database was when the .bak file was created.

    SqlCommand createDB = new SqlCommand("Restore Database [" + dbName + "] FROM DISK = " + bakDirectory, myConnection);
    createDB.Connection.Open();
    createDB.ExecuteNonQuery();
}

The commented part of the code snippet works, but requires the use of the .mdf and .ldf files. The part just below only uses the .bak file but I get an unhandled exception when attempting to run that code:
The backup set holds a backup of a database other than the existing 'dbname' database
I believe this is because the database structure of the newly created database doesn't match the structure of the database in the .bak file. (please correct me if I have that wrong). Is there a way for me to restore the backup using only the .bak file? Thank you in advance for taking the time to look at this.

A: As @DanGuzman stated, there was no need to create a new database beforehand.
Following (@ScottChamberlain)'s instructions in the comments, I was able to find the script needed to restore the database without using the .mdf or .ldf files. The exact script was:
SqlCommand createDB = new SqlCommand("RESTORE DATABASE [" + dbName + "] FROM  DISK = N'" + bakDirectory + "' " +
"WITH  FILE = 2,  MOVE N'" + oldDBName + "' TO N'C:\\Program Files\\Microsoft SQL Server\\MSSQL12.ANTSQLSERVER\\MSSQL\\DATA\\" + dbName + ".mdf',  " +
"MOVE N'" + oldDBName + "_log' TO N'C:\\Program Files\\Microsoft SQL Server\\MSSQL12.ANTSQLSERVER\\MSSQL\\DATA\\" + dbName + "_log.ldf',  NOUNLOAD,  STATS = 5", myConnection);

The (C:\Program Files\Microsoft SQL Server\MSSQL12.ANTSQLSERVER\MSSQL\DATA\) path was the default location where .mdf and .ldf files are created.


text:
Q: Is there any way to get s3 uri from aws web console? I want to download a directory from my s3.
When I need a file, the s3 management console (aws web console) allows me to download it, but when a directory, I have to use aws-cli, like:
$ aws s3 cp s3://mybucket/mydirectory/ . --recursive

My question is: Is there any way to get the s3 uri (s3://mybucket/mydirectory/) from s3 management console?
It's URL is available, but it is slightly different from s3 URI required by aws-cli. I could not find any menu to get the uri.
Thank you in advance!

A: No, it is not displayed in the console. However, it is simply:
s3://<bucket-name>/<key>

Directories are actually part of the key. For example, foo.jpg stored in an images directory will actually have a key (filename) of images/foo.jpg.

A: To convert an S3 URL displayed in the console such as https://s3.us-east-2.amazonaws.com/my-bucket-name/filename to an S3 URI, remove the https://s3.us-east-2.amazonaws.com/ portion and replace it with s3://, like so:
s3://my-bucket-name/filename

A: It looks like this feature is now available in the AWS Web Console.
It is accessible in two ways:

*

*Selecting the checkbox next to the file and clicking on "Copy S3 URI" button.

*Clicking on the file, and clicking on the "Copy S3 URI" button on the top right.

A: You can get the value from the console by selecting the file in the console. Choose Copy path on the Overview tab to copy the S3:// link to the object.

A: It is possible to get the S3-URI for a proper key/file in the console, by selecting the key and clicking on the Copy path button, this will place the s3-URI for the file on the clipboard.
However, directories are not keys as such but just key prefixes, so this will not work for them.

A: (self-answer)
Because it seems there was no such way, I have created one:
pip install aws-s3-url2uri

And command aws_s3_url2uri will be available after installation.
This command internally converts the web console URLs to S3 URIs, so works with URLs and URIs and local paths:
aws_s3_url2uri ls "https://console.aws.amazon.com/s3/home?region=<regionname>#&bucket=mybucket&prefix=mydir/mydir2/"

calls
aws s3 ls s3://mybucket/mydir/mydir2/

internally.

A: You may fail to get s3uri if you are created a new bucket.
You can get s3uri after creating a new folder in your bucket >> select check box to the newly created folder >> then copy the s3uri that appears at the top.


text:
Q: How to write a generic forwarding lambda in C++14? How do I write a generic forwarding lambda in C++14?
Try #1
[](auto&& x) { return x; }

Inside the function body, x is an lvalue, so this doesn't work.
Try #2
[](auto&& x) { return std::forward<decltype(x)>(x); }

This properly forwards references inside the lambda, but it will always return by value (unless the compiler elides the copy).
Try #3
[](auto&& x) -> decltype(x) { return std::forward<decltype(x)>(x); }

This returns the same type as the argument (probably -> auto&& would work as well) and appears to work properly.
Try #4
[](auto&& x) noexcept -> decltype(x) { return std::forward<decltype(x)>(x); }

Does adding noexcept make this lambda more applicable and thus strictly better than #3?

A: A return type of decltype(x) is insufficient.
Local variables and function parameters taken by value can be implicitly moved into the return value, but not function parameters taken by rvalue reference (x is an lvalue, even though decltype(x) == rvalue reference if you pass an rvalue). The reasoning the committee gave is that they wanted to be certain that when the compiler implicitly moves, no one else could possibly have it. That is why we can move from a prvalue (a temporary, a non-reference qualified return value) and from function-local values. However, someone could do something silly like
std::string str = "Hello, world!";
f(std::move(str));
std::cout << str << '\n';

And the committee didn't want to silently invoke an unsafe move, figuring that they should start out more conservative with this new "move" feature. Note that in C++20, this issue will be resolved, and you can simply do return x and it will do the right thing. See http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/p0527r0.html
For a forwarding function, I would attempt to get the noexcept correct. It is easy here since we are just dealing with references (it is unconditionally noexcept). Otherwise, you break code that cares about noexcept.
This makes the final ideal forwarding lambda look as follows:
auto lambda = [](auto && x) noexcept -> auto && { return std::forward<decltype(x)>(x); };

A return type of decltype(auto) will do the same thing here, but auto && better documents that this function always returns a reference. It also avoids mentioning the variable name again, which I suppose makes it slightly easier to rename the variable.
As of C++17, the forwarding lambda is also implicitly constexpr where possible.

A: Your first two tries don't work because return type deduction drops top-level cv-qualifiers and references, which makes generic forwarding impossible. Your third is exactly correct just unnecessarily verbose, the cast is implicit in the return type. And noexcept is unrelated to forwarding.
Here are a few more options worth throwing out for completeness:
auto v0 = [](auto&& x) -> decltype(x) { return x; };
auto v1 = [](auto&& x) -> auto&& { return x; };
auto v2 = [](auto&& x) -> auto&& { return std::forward<decltype(x)>(x); };
auto v3 = [](auto&& x) -> decltype(auto) { return std::forward<decltype(x)>(x); };

v0 will compile and look as if it returns the correct type, but will fail at compilation if you call it with an rvalue reference due to the requested implicit conversion from lvalue reference (x) to rvalue reference (decltype(x)). This fails on both gcc and clang.
v1 will always return an lvalue reference. If you call it with temporary, that gives you a dangling reference.
Both v2 and v3 are correct, generic forwarding lambdas. Thus, you have three options for your trailing return type (decltype(auto), auto&&, or decltype(x)) and one option for the body of your lambda (a call to std::forward).

A: The fewest characters, yet fully featured, version I can generate is:
[](auto&&x)noexcept->auto&&{return decltype(x)(x);}

this uses an idiom I find useful -- when forwarding auto&& parameters in a lambda, do decltype(arg)(arg).  Forwarding the decltype through forward is relatively pointless if you know that the arg is of reference type.
If x was of value type, decltype(x)(x) actually produces a copy of x, while std::forward<decltype(x)>(x) produces an rvalue reference to x.  So the decltype(x)(x) pattern is less useful in the general case than forward: but this isn't the general case.
auto&& will allow references to be returned (matching the incoming references).  Sadly, reference lifetime extension won't work properly with the above code -- I find that forwarding rvalue references into rvalue references is often the wrong solution.
template<class T>struct tag{using type=T;};
template<class Tag>using type=typename Tag::type;
template<class T> struct R_t:tag<T>{};
template<class T> struct R_t<T&>:tag<T&>{};
template<class T> struct R_t<T&&>:tag<T>{};
template<class T>using R=type<R_t<T>>;

[](auto&&x)noexcept->R<decltype(x)>{return decltype(x)(x);}

gives you that behavior.  lvalue references become lvalue references, rvalue references become values.


text:
Q: Woocommerce 'My orders' add/remove column In the Woocommerce customer account, I'd like to remove the following columns:

*

*Order number

*Order total

And add a column to display attached files (thanks to the WooCommerce Attach Me! plugin). The developer gave me this information:

"To get all the order attachments use the following snippet:"

global  $wcam_order_model;
$order_attachments = $wcam_order_model->get_attachments_metadata($order_id , array());

Where $order_id is the order id for which you want to retreive attachments. Then to get each attachment title use the following shippet:

foreach($order_attachments as $order_attachment)
$file_name = basename($order_attachment['absolute_path']);
I have found a tutorial here: https://www.skyverge.com/blog/adding-columns-woocommerce-orders-list/
But I can't get it work. As you imagine, I am not a developer :/
Thank you very much!

A: Put this in your functions.php
function sv_wc_add_my_account_orders_column( $columns ) {
    $new_columns = array();
    foreach ( $columns as $key => $name ) {

        if( 'order-number' === $key || 'order-total' === $key ) {
            echo ' name '.$name . ' key ' . $key ;
            continue;
        }

        $new_columns[ $key ] = $name;

        /*if( 'order-date' === $key) {
            $new_columns['order-number'] = __( 'Order', 'textdomain' );
            $new_columns['order-rental-period'] = __( 'Rental Period', 'textdomain' );
            $new_columns['order-detail'] = __( 'Order or Quotation Detail', 'textdomain' );
         }*/

    }

    add_filter( 'woocommerce_my_account_my_orders_columns', 'sv_wc_add_my_account_orders_column' );

    return $new_columns;

}


text:
Q: PostgreSQL как преобразовать bytea в guid Есть поле в таблице с типом bytea. Нужно правильно его переобразовать в guid.
Сами данные в поле - ]\213\000\036\311\353\323\341\021\345\203\272Lw\376\206
Конвертирую в uuid следующим образом:
select encode(']\213\000\036\311\353\323\341\021\345\203\272Lw\376\206', 'hex') :: uuid

На выходе получаю: 5d8b001e-c9eb-d3e1-11e5-83ba4c77fe86
Как-бы вроде, то что нужно. Но guid должен быть вида: 4c77fe86-83ba-11e5-5d8b-001ec9ebd3e1. Если присмотреться, то сам запрос encode почему-то меняет части гуида местами. Почему это происходит и как получить нужный мне формат?


text:
Q: How to take the square root of a number in a negative base? For example, in negadecimal (base -10): how to take the square root of $185_{-10}=25_{10}$?
Or in negabinary (base -2): the square root of $1100100_{-2}=36_{10}$?
Converting to another base, taking the square root and converting back to the negative base is not an option. I'm looking for an algorithm fully done in the negative base.
I take the square root of a binary number by dividing a number like $11001_2=25_{10}$ as follows:
$01|10|01$
And then conditionally subtracting $01$ from each segment from left to right, adding a $1$ to the answer and appending the answer to the $01$ subtraction.

A: The standard positive base $b$ square root algorithm is:

*

*Split the input digits into groups of two (such that the decimal point is one of the split points).

*Initialize $\mathit{remainder}$ to $0$ and $\mathit{output}$ to $0$.

*Append the next digit group to the end of $\mathit{remainder}$.

*Find the largest digit $d$ such that $(2 \cdot b \cdot \mathit{output} + d) \cdot d \le \mathit{remainder}$.

*Subtract $(2 \cdot b \cdot \mathit{output} + d) \cdot d$ from $\mathit{remainder}$.

*Append $d$ to $\mathit{output}$.

*While more digits are desired, repeat from step 3.

The reason this fails in a negative base is that step 4 is really looking for the first digit of the real-number solution to
$$\begin{align*}
(b \cdot \mathit{output} + x)^2 &= b^{2n} \cdot \mathit{input} \\
\iff (2 \cdot b \cdot \mathit{output} + x) \cdot x &= b^{2n} \cdot \mathit{input} - (b \cdot \mathit{output})^2,
\end{align*}$$
where $\mathit{remainder}$ is maintained as the integer part of the right side.  A negative base presents four difficulties:

*

*Because we're outputting one digit at a time, on any given iteration, output may be of either sign, which means that $(2 \cdot b \cdot \mathit{output} + x) \cdot x$ may be either increasing or decreasing in $x$.

*The first digit of $x$ may now be greater than $x$.  The set of numbers starting with a digit $d$ is no longer $[d.000000\cdots, d.999999\cdots) = [d, d + 1)$, but rather $[d.909090\cdots, d.090909\cdots) = \left[d + \frac{b}{1 - b}, d + \frac{1}{1 - b}\right)$.

*For the same reason, we might sometimes need more than two input digits to produce one output digit: $\sqrt{02.9921_{-10}} = 1.09_{-10}$ starts with $1$, but $\sqrt{02.81_{-10}} = 2.9_{-10}$ starts with $2$.

*Without taking into account whether we're outputting a digit of positive or negative place value, it's easy to inadvertently produce the negative square root instead of the positive square root.

One strategy for addressing these difficulties involves building $\mathit{remainder}$ from the digits of $\mathit{input} \cdot (1 - b)$ instead of $\mathit{input}$.  The points at which the first digit of $x$ changes are described by $x = d + \frac{1}{1 - b}$:
$$\left(2 \cdot b \cdot \mathit{output} + d + \frac{1}{1 - b}\right) \cdot \left(d + \frac{1}{1 - b}\right) = b^{2n} \cdot \mathit{input} - (b \cdot \mathit{output})^2 \\
\begin{multline}
\iff (2 \cdot b \cdot \mathit{output} + d) \cdot d \cdot (1 - b) + 2 \cdot b \cdot \mathit{output} + 2 \cdot d + \frac{1}{1 - b} \\
= b^{2n} \cdot \mathit{input} \cdot (1 - b) - (b \cdot \mathit{output})^2 \cdot (1 - b).
\end{multline}$$
The pre-decimal part of the right side also changes here (since the right side equals an integer plus $\frac{1}{1 - b}$), so maintaining that pre-decimal part as $\mathit{remainder}$ guarantees sufficient precision to pin down the first digit of $x$ correctly.
Taking this all into account, we can update the algorithm for negative base $b$ as follows:

*

*Multiply the input by $1 - b$.

*Split the resulting digits into groups of two (such that the decimal point is one of the split points).

*Initialize $\mathit{remainder}$ to $0$ and $\mathit{output}$ to $0$.

*Append the next digit group to the end of $\mathit{remainder}$.

*
*

*If $\mathit{output} = 0$ and we're outputting a digit of negative place value, set $d = 0$.

*Otherwise if $\mathit{output} \le 0$, find the smallest digit $d$ such that $$(2 \cdot b \cdot \mathit{output} + d) \cdot d \cdot (1 - b) + 2 \cdot b \cdot \mathit{output} + 2 \cdot d \ge \mathit{remainder}.$$

*Otherwise, find the smallest digit d such that $$(2 \cdot b \cdot \mathit{output} + d) \cdot d \cdot (1 - b) + 2 \cdot b \cdot \mathit{output} + 2 \cdot d < \mathit{remainder}.$$

*Subtract $(2 \cdot b \cdot \mathit{output} + d) \cdot d \cdot (1 - b)$ from $\mathit{remainder}$.

*Append $d$ to $\mathit{output}$.

*While more digits are desired, repeat from step 4.


text:
Q: Unable to scroll LinearLayout which is placed in ScrollView I referred most of the questions in Stackoverflow related to this topic and successfully placed my Linear Layout in a ScrollView. But I can't scroll it. The outline of my Activity is-

Here is the XML code of ScrollView-
<ScrollView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="1" >

                <LinearLayout
                    android:id="@+id/linearLayoutUP1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="5dp"
                    android:layout_weight="1"
                    android:orientation="vertical" >

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginTop="5dp"
                        android:orientation="vertical" >

                        <TextView
                            android:id="@+id/textViewUP1"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:background="@color/Chocolate"
                            android:gravity="center"
                            android:padding="10dp"
                            android:text=" "
                            android:textAppearance="?android:attr/textAppearanceLarge"
                            android:textColor="@color/Black"
                            android:textStyle="bold" />
                    </LinearLayout>

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginTop="5dp"
                        android:orientation="vertical" >

                        <TextView
                            android:id="@+id/textViewUP2"
                            android:layout_width="match_parent"
                            android:layout_height="match_parent"
                            android:background="@color/Chocolate"
                            android:gravity="center"
                            android:padding="10dp"
                            android:text="User ID : "
                            android:textColor="@color/White"
                            android:textSize="16sp"
                            android:textStyle="bold" />
                    </LinearLayout>

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginTop="5dp"
                        android:orientation="vertical" >

                        <TextView
                            android:id="@+id/textViewUP4"
                            android:layout_width="match_parent"
                            android:layout_height="match_parent"
                            android:background="@color/Chocolate"
                            android:gravity="center"
                            android:padding="10dp"
                            android:text="Gender : "
                            android:textColor="@color/White"
                            android:textSize="16sp"
                            android:textStyle="bold" />
                    </LinearLayout>

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginTop="5dp"
                        android:orientation="vertical" >

                        <TextView
                            android:id="@+id/textViewUP3"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:background="@color/Chocolate"
                            android:gravity="center"
                            android:padding="10dp"
                            android:text="Your Groups"
                            android:textColor="@color/White"
                            android:textSize="16sp"
                            android:textStyle="bold" />

                        <GridView
                            android:id="@+id/gridViewUP1"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:numColumns="1"
                            android:padding="5dp" >
                        </GridView>
                    </LinearLayout>
                </LinearLayout>
                </ScrollView>

As you can see there is a GridView in the last LinearLayout. This GridView was scrollable before adding ScrollView. After adding ScrollView the layout named 'linearLayoutUP1' cannot be scrolled. How can I make it scrollable vertically ?

A: I think nesting scrollable views in Android is considered bad design, and may not work properly. GridViews are inherently scrollable.
If you want to keep it, try looking here: Problems with GridView inside ScrollView in android

A: Try hardcoding the height for the first LinearLayout..ie change wrap_content to some 1000dp or so. This will make it scrollable. I'm not at all sure whether this is the right way to solve the problem..But was telling you what I did when I faced the same situation.
Also, if you are using android:theme="@android:style/Theme.NoTitleBar.Fullscreen" ..try changing that to android:theme="@android:style/Theme.NoTitleBar" ..ie without fullscreen...
Again,  check if there is android:windowSoftInputMode="adjustPan" for your activity tag in manifest..if yes try after removing that.
These are the solutions which i tried and worked when i faced a similar situatuion.
android activity always start scrolled to the bottom-to solve this problem please add  android:focusableInTouchMode="true" to your LinearLayout..

A: It is not recommended to you any kind of scrollable view inside a ScrollView.
You may want to check this out in your case and see if it works.
http://lubosplavucha.com/java/2014/05/05/gridview-scrollview-issue/


text:
Q: Is it possible to run vim in remote mode on another machine? I run an Ubuntu server virtualbox under a Windows host for web development.
At the moment I do all editing in Vim running inside PuTTY. It runs pretty well, but lacks some useful features like native copypasting from the host.
I know about the remote mode of Vim, but afaik it can only operate on the same machine.
Question is, is it possible to make gVim on the windows host proxy all the commands (and the editing) to a Vim instance running on the Linux guest?
UPDATE: final solution:

*

*apt-get install vim-gtk on the client

*install XMing on the host

*create a shortcut with XLaunch, providing gvim as the program name and your PuTTY saved session name as the computer name.

*done!

A: Have you tried setting up a XServer (like XMing or cygwin/X) on your windows machine and use X forwarding?
This way you can run an instance of gVim on your linux host and have it displayed on your Windows machine.
See http://www.cs.caltech.edu/courses/cs11/misc/xwindows.html for a short guide how to make this work in windows.


text:
Q: Working with ASPX pages If I connect via FTP and make edits to a .aspx file and upload it do I need to have the webhost do any type of complile or something?

A: Assuming the file worked before (IIS is set up to allow asp.net sites here), it will be re-compiled automatically.

A: No. You don't need to do anything.


text:
Q: how to use classwt in randomForest of R? I have a highly imbalanced data set with target class instances in the following ratio 60000:1000:1000:50 (i.e. a total of 4 classes). I want to use randomForest for making predictions of the target class.
So, to reduce the class imbalance, I played with sampsize parameter, setting it to c(5000, 1000, 1000, 50) and some other values, but there was not much use of it. Actually, the accuracy of the 1st class decreased while I played with sampsize, though the improvement in other class predictions was very minute.
While digging through the archives, I came across two more features of randomForest(), which are strata and classwt that are used to offset class imbalance issue.
All the documents upon classwt were old (generally belonging to the 2007, 2008 years), which all suggested not the use the classwt feature of randomForest package in R as it does not completely implement its complete functionality like it does in fortran. So the first question is:
Is classwt completely implemented now in randomForest package of R? If yes, what does passing c(1, 10, 10, 10) to the classwt argument represent? (Assuming the above case of 4 classes in the target variable)
Another argument which is said to offset class imbalance issue is stratified sampling, which is always used in conjunction with sampsize. I understand what sampsize is from the documentation, but there is not enough documentation or examples which gave a clear insight into using strata for overcoming class imbalance issue. So the second question is:
What type of arguments have to be passed to stratain randomForest and what does it represent?
I guess the word weight which I have not explicitly mentioned in the question should play a major role in the answer.

A: classwt is correctly passed on to randomForest, check this example:
library(randomForest)
rf = randomForest(Species~., data = iris, classwt = c(1E-5,1E-5,1E5))
rf

#Call:
# randomForest(formula = Species ~ ., data = iris, classwt = c(1e-05, 1e-05, 1e+05))
#               Type of random forest: classification
#                     Number of trees: 500
#No. of variables tried at each split: 2
#
#        OOB estimate of  error rate: 66.67%
#Confusion matrix:
#           setosa versicolor virginica class.error
#setosa          0          0        50           1
#versicolor      0          0        50           1
#virginica       0          0        50           0

Class weights are the priors on the outcomes. You need to balance them to achieve the results you want.

On strata and sampsize this answer might be of help: https://stackoverflow.com/a/20151341/2874779
In general, sampsize with the same size for all classes seems reasonable. strata is a factor that's going to be used for stratified resampling, in your case you don't need to input anything.

A: You can pass a named vector to classwt.
But how weight is calculated is very tricky.
For example, if your target variable y has two classes "Y" and "N", and you want to set balanced weight, you should do:
wn = sum(y="N")/length(y)
wy = 1

Then set classwt = c("N"=wn, "Y"=wy)
Alternatively, you may want to use ranger package. This package offers flexible builds of random forests, and specifying class / sample weight is easy. ranger is also supported by caret package.

A: Random forests are probably not the right classifier for your problem as they are extremely sensitive to class imbalance.
When I have an unbalanced problem I usually deal with it using sampsize like you tried. However I make all the strata equal size and I use sampling without replacement.
Sampling without replacement is important here, as otherwise samples from the smaller classes will contain many more repetitions, and the class will still be underrepresented. It may be necessary to increase mtry if this approach leads to small samples, sometimes even setting it to the total number of features.
This works quiet well when there are enough items in the smallest class. However, your smallest class has only 50 items. I doubt you would get useful results with sampsize=c(50,50,50,50).
Also classwt has never worked for me.


text:
Q: Objective-C loop to compare two textfields for passwords I am trying to extend one of my iOS projects to ask the user to input a password and then re-type the password and if the passwords don't match, keep doing it until they do. I can do it by setting up IBOutlets in my project and then do the comparison, but then how do I loop the comparison if they don't match? I've searched a lot for this but haven't found a simple answer other than a github project called PTPasscodeController, which is too complicated for what I want do, i.e., simple input and comparison, not extensive security.
I tried to get this to work by UIAlertController, but it doesn't seem possible to initialize and then check the loop for the comparison of the two textfields. That is, I know how to get an array of textfields through UIAlertController, but not how to keep putting up the alert when the two textfields don't match.
If there is code to accomplish this, or a better way, I would appreciate the help a lot!

A:
how do I loop the comparison if they don't match?

You don't loop at all. In UI environments you accomplish "ask again" behavior by disabling actions and showing errors.
I am assuming that in addition to the "password" and "retype password" fields you have some kind of the "I am done" button (e.g. "Next", "Done", etc.) which should be disabled initially.
You should respond to textField:shouldChangeCharactersInRange:replacementString: in the protocol of text fields, check the two passwords for equality, and do one of two things:

*

*If both passwords are non-empty, valid, and equal, enable the "Next" button

*Otherwise, put red border or some other visual feedback on the "retype password" field, to tell end-user that they made a mistake while entering their password the second time.

A: Here is my code that works.
I have two view controllers. The first view controller is a tableView Controller that checks for a password required in the settings bundle.  If a password is required, it performs a segue to the second view controller.
The second view controller compares a password to a re-entered password and sets the text color depending on whether the two match. Also, if a password was previously set, it deletes the second password request from the view (by checking the subview tags from the storyboard) and just compares the previously entered password against the password the user now enters.
Not very elegant, but it works for my purposes.
The first view controller's relevant code:
NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
                                               NSLog(@"defaults %@", [defaults
                                                                      dictionaryRepresentation]);
                                               BOOL passwordProtect = [[defaults valueForKey:@"password"]boolValue];
                                               if(passwordProtect)
                                               {
                                                   self.passwordEntered = YES;
                                                   [self performSegueWithIdentifier:@"passcodeViewController" sender:self];
                                               }

    -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    if([segue.identifier isEqualToString:@"passcodeViewController"]){
        NRCPasscodeControllerViewController *destViewController = segue.destinationViewController;
        destViewController.password = self.password;
    }
}

The second view controller's code:
    @interface NRCPasscodeControllerViewController : UIViewController <UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *password1;
@property (weak, nonatomic) IBOutlet UITextField *password2;
@property (strong, nonatomic) NSString *password;
@property (nonatomic) BOOL passwordWasEntered;
@end

implementation file:
#import "NRCPasscodeControllerViewController.h"

@interface NRCPasscodeControllerViewController ()

@end

@implementation NRCPasscodeControllerViewController

- (IBAction)checkPasswords:(id)sender {
    // if a password has not been entered, display
    // both password fields

    if((self.passwordWasEntered == NO)){

        // password1 must be 4 characters in length

    if ([self.password1.text length] == 4) {
        self.password1.textColor = [UIColor greenColor];
    } else {
        self.password1.text =@"Invalid!";
        self.password1.textColor = [UIColor redColor];
    }
        // password2 must be 4 characters in length

    if ([self.password2.text length] == 4) {
        self.password2.textColor = [UIColor greenColor];
    } else {
        self.password2.text =@"Invalid!";
        self.password2.textColor = [UIColor redColor];
    }
        // passwords must match

    if([self.password1.text isEqual:self.password2.text]){
        self.password2.textColor = [UIColor greenColor];
        // passwords match, so set the password and segue back

        self.password = self.password1.text;
        [self performSegueWithIdentifier:@"unwindToTableView" sender:self];
    }
    else{
        self.password2.textColor = [UIColor redColor];
    }

    }
    // if password has already been entered, just check the first password
    // field against the entered password.
    else if (self.password == self.password1.text){

        // password matches entered password, so set the password and segue back
        self.password1.textColor = [UIColor greenColor];
        [self performSegueWithIdentifier:@"unwindToTableView" sender:self];
    }
        else{
            // password does not match entered password
            self.password1.textColor = [UIColor redColor];
            self.password = self.password1.text;
        }

}
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}
- (void)viewDidLoad {
    [super viewDidLoad];

    self.password1.delegate = self;
    self.password2.delegate = self;
    [self.navigationItem setHidesBackButton:YES animated:YES];

    // Do any additional setup after loading the view from its nib.
}
-(void)viewWillAppear:(BOOL)animated{
    // if self.password is not nil, a password has already been entered
    // so only display one password field to check.

    if(self.password){
    [[self.view viewWithTag:3] removeFromSuperview];
    [[self.view viewWithTag:2] removeFromSuperview];
    self.passwordWasEntered = YES;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end

and in the first controller that receives the unwind segue:
    -(IBAction)unwindFromPasscodeController:(UIStoryboardSegue*)segue{
    NSLog(@"Unwound from passcode controller");
    NRCPasscodeControllerViewController *sourceViewController = segue.sourceViewController;
    self.password = sourceViewController.password;
}


text:
Q: Positive semi-definite conditional covariance matrix Let $X$ be an $n\times m$ random matrix, where each entry is a real square integrable random variable on the probability space $(\Omega,\mathcal A,P)$. Consider the following matrix:
$$E[XX'\mid\mathcal F],$$ where $\mathcal F$ is a sub-$\sigma$ algebra of $\mathcal A$. If $a\in\mathbb{R}^{n}$, then from the linearity of conditional expectations we have
$$a'E[XX'\mid\mathcal F]a=E[(a'X)^2\mid\mathcal F]\geq 0 \quad P\text{-almost surely,}$$
but the null set might depend on $a$. Can I find a version of $E[XX'\mid\mathcal F]$ which is positive semi-definite almost surely?

A: The null set might depend on $a$, and therefore let
$$
a'E[XX'|\mathcal F]a=E[(a'X)^2|\mathcal F]\geq 0,
$$
on the set $L_a$, where $P(L_a^c)=0$. Now consider all rational numbers $\mathbf{Q}$, and for each $a\in \mathbf{Q}^n$ you will have an $L_a$, also note that
$$
P(\cup_{a \in \mathbf{Q}^n} L_a^c) \leq \sum_{a \in \mathbf{Q}^n} P(L_a^c)=0,
$$
Therefore $P(\cap_{a \in \mathbf{Q}^n} L_a) =1$. Define $L:=\cap_{a \in \mathbf{Q}^n} L_a$. For each fixed $\omega\in L$,
$$
a'E[XX'|\mathcal F]a\geq 0
$$
for all $a \in \mathbf{Q}^n$. Now take any number $x\in \mathbb{R}^n$ and let $a_n$ be a sequence of rationals (vector) converging to $x$. By the previous argument for each fixed $\omega\in L$,
$$
a_n'E[XX'|\mathcal F]a_n\geq 0.
$$
Now taking the limit $n \to \infty$,
$$
x'E[XX'|\mathcal F]x\geq 0.
$$


text:
Q: Aliasing regular array with vector intrinsics in gcc I'm playing around with the vector instrinsics in GCC, particularly for AVX, and I'm tempted to write something like this to do a vector multiply between two arrays:
#include <unistd.h>

void __attribute__((target("avx"))) vmul(float* __restrict__ cc, const float* __restrict__ aa, const float* __restrict__ bb, ssize_t size) {
    const ssize_t VECSIZE=8;
    typedef float vfloat __attribute__((vector_size(sizeof(float)*VECSIZE)));

    // duff's device, process any remainder up front
    ssize_t rem = size % VECSIZE;
    switch (rem) {
        case 7: cc[6] = aa[6]*bb[6]; /* FALLTHRU */
        case 6: cc[5] = aa[5]*bb[5]; /* FALLTHRU */
        case 5: cc[4] = aa[4]*bb[4]; /* FALLTHRU */
        case 4: cc[3] = aa[3]*bb[3]; /* FALLTHRU */
        case 3: cc[2] = aa[2]*bb[2]; /* FALLTHRU */
        case 2: cc[1] = aa[1]*bb[1]; /* FALLTHRU */
        case 1: cc[0] = aa[0]*bb[0]; /* FALLTHRU */
        case 0: break;
    }
    size -= rem;

    // process rest of array
    const vfloat *va = (const vfloat*)(aa+rem);
    const vfloat *vb = (const vfloat*)(bb+rem);
    vfloat *vc = (vfloat*)(cc+rem);

    for (ssize_t ii=0; ii < size; ii++) {
        vc[ii] = va[ii]*vb[ii];
    }
}

int main() {
}

The problem is the pointer-aliasing required to get data into the vector type.  GCC happily lets you do it (no warning with -Wall -Wextra -ansi -pedantic), but then assumes the underlying memory alignment is appropriate.  So it generates vmovaps instructions in the inner loop:
   0x0000000000400660 <+176>:   vmovaps (%rsi,%rax,1),%ymm0
   0x0000000000400665 <+181>:   vmulps (%rdx,%rax,1),%ymm0,%ymm0
   0x000000000040066a <+186>:   vmovaps %ymm0,(%rdi,%rax,1)
   0x000000000040066f <+191>:   add    $0x20,%rax
   0x0000000000400673 <+195>:   cmp    %r8,%rax
   0x0000000000400676 <+198>:   jne    0x400660 <_Z4vmulPfPKfS1_l+176>

Which is fine, until you pass in some non-aligned memory (or a size not a multiple of 8 in my case), and then it happily segfaults your program trying to load unaligned memory with an aligned instruction.
Is there a proper way to do this with the vector extensions?

A: You can reduce the alignment like this:
typedef float vfloat __attribute__((vector_size(sizeof(float)*VECSIZE),
    aligned(4)));

With that change, I get vmovups instructions.


text:
Q: Why are there no continued fraction representation for $\pi$ obeying mathematical rules? There are several irrational numbers that can be represented with continued fraction such that a mathematical rule arises in this continued fraction. For example, the Euler number $e$ can be represented as follows:
$$e=[2,1,2,1,1,4,1,1,6,1,1,8,1,1,10,\ldots]= 2+ \cfrac{1}{1+ \cfrac{1}{2 + \cfrac 1 \ddots}}$$
It's very fascinating that in the case where the number sequence after the $,$ is chaotic, it does exists a well-ordered scheme when considering continued fractions. Every three steps in the continued fraction, the parameter increases by $2$ and elsewhere the parameter is $1$. Why it is so? Another popular mathematical constant $\pi$ however, does not have a regular structure in the continued fraction:
$$\pi = [3,7,15,1,292,1,1,1,\ldots].$$
But I can see many $1$-s in this series of parameters. May it be that $\pi$ has an irregular continued fraction, but not a very intensive irregularity? Why these structural differences in continued fractions arise between $\pi$ and $e$?
And what is with other mathematical constant like the Euler-Mascheroni-constant $\Gamma$; is there also a regularity in the continued fractions?
I would be happy for any comments and answers.

A: If you allow generalised continued fractions, then you can actually. This one is courtesy of Lord Brouncker is 1654:
$$
\frac{1}{4}\pi=\cfrac{1}{1+\cfrac{1^2}{3+\cfrac{2^2}{5+\cfrac{3^2}{7+\dotsb}}}}
$$
This has very slow convergence. Apparently people didn't believe it initially. It takes nearly 50 terms for five decimal places of accuracy and nearly 120 for six! (It convergence in an oscillatory manner: above, below, above, below, etc.)

If you have a decimal expansion $x=0.x_1x_2x_3...$, then, given that $x$ was chosen uniformly randomly in $[0,1]$, we can see that each of the $x_i$ is uniform on $\{0, 1, ..., 9 \}$. This is not the case, however, with continued fractions. In essence, we can see this best with an example. If you simply start to calculate, say $101/37$, then you'll see that to get a large number in the fraction (in the standard type as you have in your question) you need to have the number that you're inverting close to $0$. Let me explain:
$${101 \over 37} = 2 + {27 \over 37} \ \ \text{giving a 2},$$
$${37 \over 27}  = 1 + {10 \over 27} \ \ \text{giving a 1},$$
and so we continue; however, suppose that at some point we have
$${1003 \over 1000} = 1 + {3 \over 1000}  \ \ \text{giving a 1},$$
$${1000 \over 3}    = 333 + {1 \over 3}   \ \ \text{giving a 333}.$$
We can actually show, with quite a bit of work, what the distribution is: it has density
$$f(x) = {1 \over {\log 2}}{1 \over {1+x}}.$$
(You can either try to prove this yourself or I'm sure you can look it up - in fact, there's probably a related SE question.)

Hopefully this helps! :)


text:
Q: Know the just incremented value We everybody know how to increment a column in MySQL:
update table set col = col + 1 where id = 15;
But ... is there anyway to know the new value WITHOUT doing a SELECT query ?
Thank you

A: Trying to understand your question.
Taken from Posted by Justin Swanhart on July 29 2004 5:32pm@Mysql UPDATE refman.
Maybe this is what you trying to achieve for
update table set
col = col + 1
where id = 15
and @value := col

The @value := col will always
  evaluate to true and will store the
  col value before the update in the
  @value variable.

You could then do
select @value;

A: Not that I'm aware of.
If you think about it, since multiple rows could be affected by an UPDATE, it's not trivial nor necessarily attractive to think about the database returning all of that data in the context of an UPDATE.
The MySQL docs also address the "can I do UPDATE and SELECT in the same subquery" question:

Currently, you cannot update a table
  and select from the same table in a
  subquery.

http://dev.mysql.com/doc/refman/5.5/en/update.html
One alternative that may work for you is to rely on the SELECT..FOR UPDATE approach:
http://dev.mysql.com/doc/refman/5.5/en/innodb-locking-reads.html


text:
Q: I needed help to convert below R dataframe I needed help to convert below R dataframe. Can anyone can help me to do it?
I tried
df:
YRMONTH  | ABC | BCD | CDA | ING
---------------------------------
Jan-2021 | 123 | 123 | 123 | 123
FEB-2021 | 124 | 124 | 0   | 124
MAR-2021 | 125 | 125 | 125 | 125
APR-2021 | 126 | 126 | 126 | 0

Output:
YRMONTH | Jan-2021 | FEB-2021 | MAR-2021 | APR-2021 ...
---------------------------------------------------
ABC     | 123      | 124      | 125      | 126
BCD     | 123      | 124      | 125      | 126
CDA     | 123      | 0        | 125      | 126
ING     | 123      | 124      | 125      | 0

Thank you in advance for your help.

A: We could use data.table::transpose
data.table::transpose(df, make.names = 'YRMONTH', keep.names = 'YRMONTH')

-output
   YRMONTH Jan-2021 FEB-2021 MAR-2021 APR-2021
1     ABC      123      124      125      126
2     BCD      123      124      125      126
3     CDA      123        0      125      126
4     ING      123      124      125        0

data
df <- structure(list(YRMONTH = c("Jan-2021", "FEB-2021", "MAR-2021",
"APR-2021"), ABC = 123:126, BCD = 123:126, CDA = c(123L, 0L,
125L, 126L), ING = c(123L, 124L, 125L, 0L)), class = "data.frame",
   row.names = c(NA,
-4L))


text:
Q: Cauchy-Schwarz inequality in terms of intensity measurements Hi I was reading Introductory Quantum Optics by Gerry and Knight, particularly the part about higher degrees of coherence (Section 5.4), and in there they write:

Now according to Cauchy's inequality applied to a pair of measurements at times
$t_1$ and $t_2$, we have:
$$2I(t_{1}) I(t_{2}) ≤ I(t_{1})^{2} I(t_{2})^{2} .$$

It is not clear to me how the Cauchy-Schwarz inequality is used here and where exactly this equation comes from, could someone please explain this for me?

A: Cauchy-Schwarz inequality state that in any inner product space: ${\displaystyle \left|\left\langle \mathbf {u} ,\mathbf {v} \right\rangle \right|^{2}\leq \langle \mathbf {u} ,\mathbf {u} \rangle \cdot \langle \mathbf {v} ,\mathbf {v} \rangle}$ for any u,v.
In the special case of L2 space (the inner product space of function that we use in quantom mechanics) the inner product between two functions $f(x)$ and $g(x)$ is the integral :${\displaystyle \int _{\mathbb {R} ^{n}}f(x){\overline {g(x)}}\,dx}$ and it follows that Cauchy-Schwarz inequality in this case become: ${\displaystyle \left|\int _{\mathbb {R} ^{n}}f(x){\overline {g(x)}}\,dx\right|^{2}\leq \int _{\mathbb {R} ^{n}}|f(x)|^{2}\,dx\int _{\mathbb {R} ^{n}}|g(x)|^{2}\,dx.}$
In quantum mechanics, the expectation values of any measurable quantity (correspond to $I(t_1),I(t_2)$) is given by the integral $I_i=∫_{R^n}|I`(x,t_i)|dx$ when $I'$ is the operator of the measurable value $I$. Similarly, The measurable value $I(t_1)I(t_2)$ So when applying Cauchy-Schwarz inequality we get:  $I(t_1)I(t_2)≤I(t_1)^2I(t_2)^2$.
The 2 factor though look suspicious. Can you provide more details about I operator?

A: I believe you are correct - Gerry and Knight does have a typo. I believe it should be the sum of the two squared intensities, which comes from the Cauchy-Schwartz inequality for real numbers. We can show this by considering intensity to be a real value, such that
$$ (I(t_1) - I(t_2))^2 \geq 0 $$
$$ I^2(t_1) + I^2(t_2) - 2 I(t_1) I(t_2) \geq 0 $$
$$ I^2(t_1) + I^2(t_2) \geq I(t_1) I(t_2) $$
I would recommend checking out Fox's Quantum Optics, p143 (problem 6.3/6.4), for a step-by-step derivation of these limits, as well as Loudon's Quantum Theory of Light, p108 (eq 3.7.3) for verification.


text:
Q: Distribution of the $pn$ shortest edges out of $n$ uniform points, $p\to 0$ Suppose I sample $n$ points independently and uniformly at random in the unit square, and then I select the $pn$ shortest edges between all pairs of points, for fixed $0<p<1$.  For large $n$ and small $p$, what does the sum of the lengths of these edges look like (in a distributional sense)?  Geometric intuition says that the sum looks like $C(p)\sqrt{n}$ and that $C(p)\to0$ as $p\to0$, and I'm wondering what $C(p)$ looks like (say to first order)

A: Here is a heuristic that agrees with the power proposed by @Bullet51 in the comments above, showing that $C(p)$ should grow like $p^{3/2}$. The sum should look like $pn$ times the typical order of the $(pn)$th smallest distance.
To estimate that distance, consider a simpler problem, where the points are put in $Kn$ bins (each representing a sub-square of the unit square of side $(Kn)^{-1/2}$). Of course, this ignores the possibility that two points could be in neighbouring bins, and closer than points in their own bin, but I don't think it changes the order.
If $n$ points are distributed between the $Kn$ bins, the distribution is approximately that each bin receives a Poisson number of points with mean $1/K$. Let $X_1,\ldots, X_{Kn}$ be the number of points in each bin, and assume these are independent Poisson random variables with mean $1/K$. Now the number of pairs of points lying in the same bin is $\sum_{i=1}^{Kn} \frac 12X_i(X_i-1)\sim Kn/2(\mathbb EX^2-\mathbb EX)$. For a Poisson with mean $1/K$, the term in parentheses is $1/K^2$, so the expected number of pairs of points lying in the same bin is $n/(2K)$.
If we set this equal to $pn$, it tells you how big the bins have to be in order to have $pn$ pairs, that is $K=1/(2p)$. Hence our crude model suggests that the $(pn)$th smallest distance is of size roughly $\sqrt {1/(Kn)}\sim \sqrt{p/n}$. So the sum of the first $pn$ distances should grow like $p^{3/2}\sqrt n$.


text:
Q: Number Sequence Announcer I would like to ask if anyone could please suggest me accurate ( ! ) sequence number announcer tool. It can be web based application, working within website, or desktop software. It can be free of charge (preferable) or paid. Would be willing to pay for it but it has to announce the number correctly. There are no math formulas behind the sequence. Numbers are ordered from left to right - the first number is the oldest one and the last number is the most recent one. I would like to use it mainly for binary digits (0 or 1 only) but sometimes also for ''normal'' numbers. So far the only website I know is:
http://oeis.org
But everything is announced wrong. I am testing like 50+ situations and being aware of the most recent number (the one listed on the most right side so the last one). Obviously I am testing the said website without typing in the most recent number, even if I know it. But it is all the time giving me wrong announcement.
I am Not asking for assistance regarding accurately announcing first next number in the sequence but, to clarify again and to avoid misunderstanding, I am asking for suggestion about which other website/tool/software could I use for this. So it will tell me which number will occur next.
Your reply would be highly appreciated, thank you in advance.

A: Claim. If you give me an arbitrary sequence, I can produce a random number and prove that it is, in fact, the next term of the sequence. Indeed, suppose your terms are $a_1, a_2, a_3, ..., a_n$. Then I choose a random number $X$. We can construct a polynomial of degree $n$ that satisfies the sequence $a_1, a_2, ..., a_n, X$; that is, a polynomial $p$ such that $p(k) = a_k$.
Proof sketch. First, we fit the points $(1, a_1)$ and $(2, a_2)$ with a line:
$$f_1(x) = (x-1)(a_2-a_1) + a_2$$
Now consider the quadratic function
$$f_2(x) = Q_1 \cdot (x-1)(x-2) + f_1(x)$$
Observe that regardless of the value of $Q_1$, $f(1) = a_1$ and $f(2) = a_2$, as needed. Consider $$f_2(3) = 2Q_1 + f_1(3)$$ which we need to equal $a_3$. Then let  $$Q_1 = \frac{a_3 - f_1(3)}2$$ and so $f_2(x)$ satisfies the sequence for $a_1, a_2, a_3$.
Now consider the cubic function
$$f_3(x) = Q_2 \cdot (x-1)(x-2)(x-3) + f_2(x)$$
We can solve for $Q_2$ such that $f_3(4) = a_4$:
$$Q_2 = \frac{a_4 - f_2(4)}6$$
Notice a pattern? We can do this indefinitely for any sequence, which means regardless of the $X$ chosen, we can create a function that gives the next term in the sequence $a_1, a_2, a_3, ..., a_n, X$.
More succinctly: Suppose your terms are $a_1, a_2, a_3, ..., a_n$. Then I choose a random number $X$. Then the polynomial that satisfies the sequence $a_1, a_2, ..., a_n, X$ is $f_n(x)$, where $f$ satisfies the recurrence relation
$$f_n(x) = \frac{a_{n+1} - f_{n-1}(n+1)}{n!} \prod_{k=1}^n (x-k) + f_{n-1}(x)$$ with the basis $$f_1(x) = (x-1)(a_2-a_1) + a_2$$

Because the next term in an arbitrary sequence can be proven to be arbitrary, a more meaningful request might be to find the next entry in a well-known sequence of numbers (e.g. 1, 1, 2, 3, 5, 8, X), and OEIS is almost certainly the best tool for this.


text:
Q: QGIS merge vector layers and add a group field Is there any way to merge several vector layers into a single layer while adding an attribute column that groups the points by the layers they belonged to prior?
So I have multiple delimited txt files with coordinates loaded into my project. I have figured out a couple of ways to merge them into a single shapefile but a group # or name would make it a lot quicker for me to use Points2One to create line data from my many sets of points.


text:
Q: Unable to include file from library Clion I've been trying to include the JSON for modern c++ (GitHub page) library for a school project. The integration part of the README requires the user to add a simple line of code to the .cpp file that will be using the library. However, the lines provide an error since within the included file, the designer included other files using the #include<>. I am using Clion which uses Cmake. I am currently unable to run the program without receiving the following error message:
fatal error: nlohmann/json.hpp: No such file or directory
#include <nlohmann/json.hpp>

My code goes as follows:
#include <nlohmann/json.hpp>

// for convenience
using json = nlohmann::json;

My Cmake:
cmake_minimum_required(VERSION 3.8)
project(assingment_5)

set(CMAKE_CXX_STANDARD 11)

include_directories( CMAKE_CURRENT_SOURCE_DIR/nlohmann)

set(SOURCE_FILES main.cpp sample Item.cpp Item.h)
add_executable(assingment_5 ${SOURCE_FILES})

The nlohmann folder is within the root directory of the project

UPDATE:
Thanks all for the answers.
The problem CMake problem has been solved by @Justin (Complete fix in the comments). I am aware that there are multiple ways of solving it but this is the one that I chose.
The new CMakeLists.txt now looks like:
cmake_minimum_required(VERSION 3.8)
project(assingment_5)

set(CMAKE_CXX_STANDARD 11)
set(SOURCE CMAKE_SOURCE_DIR)

#[[include_directories(${PROJECT_SOURCE_DIR})   <------ works as well]]

set(SOURCE_FILES main.cpp sample Item.cpp Item.h)
add_executable(assingment_5 ${SOURCE_FILES})

target_include_directories(assingment_5 PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})

A: For simplicity, I started using that header like this:
I have the header within my current directory which makes for a simple CMakeLists.txt. After all, I just wanted to explore the library.

Now you can use the described using declaration like so and be off and running.


text:
Q: Deleting Events with Tombstones and Public / Private Data in an Event-Sourced System David Schmitz mentions a solution for deleting user data in an event-sourced system in this talk. It works like this:

*

*Delete all events of the user

*Emit a Tombstone Event for this specific user

*Other services might listen to the Tombstone event and clean up data, too

Question #1
To which stream is the tombstone event written?
The event stream of the specific user? Or is there an event stream specifically for tombstone events?

Furthermore, to keep some data (e.g. the users' id), he advises to split the user stream into a public and private event stream. (Reference to the talk)
Question #2
How would you practically append events to both streams?
Let's say a command needs to append an event to both, the public and private user stream. How can you make sure that both events have been appended? Does the event store publish both, SomeUserEventHapppendPrivate and SomeUsererEventHappendPublic, to the event bus? Would you create snapshots for both stream independently? This seems to me like a lot of overhead.

P.S. I would like the hear about other strategies (besides encrypting events and then deleting the key) to deleting data in an event-sourced system, too.

A: Question 1: You can start with one event, UserDeleteRequested which has two flags, one for public and one for private. You would have a BoundedContext (and associated stream) responsible for this change. Other services can listen to that event as you described.
Question 2: As for separating the the data into two streams, that sounds like two Aggregates within the same BC. How would you practically append events to both streams? You would use a process/saga to load each aggregate and raise tombstone events in what is effectively a two phase commit.


text:
Q: Add custom row as 1st row in grid extjs I want to add custom row as 1st row in grid.Supose in this link
http://ngs.woc.noaa.gov/storms/scripts/ext-3.2.1/examples/grid/row-editor.html
I want to insert custom hardcorded value as first row in this grid .How to do this i dont want to do it with store.Bascially i want to add div after header and populate my string into that
Thanks

A: grid.getStore().insert( index, records ) will do this if you set index = 0

A: you can use this code:
var grid = Ext.getCmp("yourGridId").getStore()
var myArray=new Array()
myArray['id'] = '1';
myArray['value'] = 'Dummy';
var rec = new Ext.data.Record(myArray);
grid.insert(0, rec);


text:
Q: Needs clarification about Nmap and OpenSSL results I have configured the below cipher list in Apache's ssl.conf file. And my application is running on RHEL 8.5 OS with OpenSSL version 1.1.1k.
SSLCipherSuite ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES256-CCM:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-CHACHA20-POLY1305

I'm running the below Nmap command to test the strength of the cipher suites which I used in my application,
nmap -sV --script ssl-enum-ciphers -p 8443 <IP_ADDRESS>
Please find the below output snippet.
 TLSv1.2:
|     ciphers:
|       TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 (secp256r1) - A
|       TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 (secp256r1) - A
|     compressors:
|       NULL
|     cipher preference: client
|_  least strength: A

And I knew that the certificates which I used in the application are signed with RSA. so it displays the ciphers which are having RSA authentication.
Also, When I try to execute the below command, I got "error:14094410:SSL routines:ssl3_read_bytes:sslv3 alert handshake failure:ssl/record/rec_layer_s3.c:1544:SSL alert number 40" error.

openssl s_client -connect XX.XX.XX.XX:8443 -cipher ECDHE-RSA-CHACHA20-POLY1305

My queries,

*

*Why "ECDHE-RSA-CHACHA20-POLY1305 and DHE-RSA-AES256-CCM" are not displayed by Nmap command even though they have RSA authentication?

*Why the handshake failure happened with that cipher?

Thanks.


text:
Q: How to display images from Photo gallery on uiwebview ios swift? Using Photos API(PHImageManager) i am able to get list of photos url and photo object.
When I am trying to use that url in webview , image is not displaying
Consider the following image url which I got from Photos API(PHImageManager)

A: you just have to take that burl in string and then load that string in webview in viewdidload
like
urlStr = obj["url"] as! String
and then load that url in uiwebview
webview.loadRequest(NSURLRequest(URL: NSURL(string: urlStr)!))


text:
Q: Magento 1.5.0.1 - Where does the Google Sitemap get created? I am using Mangento 1.5.0.1 and have configured the admin section to export Google XML Sitemaps daily.
Mangento uses cron to execute this however the cron job runs but never outputs a sitemap nor does it email me an error.
I was thinking maybe I need to manually create the folders / files and then maybe they would then be populated by the cron job.
So my question is, where in the file system does Magento create these files?
Thanks
Paul

A: From memory I think sitemap.xml normally gets created in the Magento directory - usually whatever is the public root of your website. Of course this is configurable.


text:
Q: python and pyqt5 - pass through variable once button is clicked I have 2 py files: my.py (this is my py created from ui - script where I have windows and input line, buttons) and vat.py (this is second script which needs to be started when pushButton_2 is clicked). I would like to run all lines from vat script but my.py needs to transfer some variables to vat.py. This is a issue - how I can do this?
my.py
    # -*- coding: utf-8 -*-
# Created by: PyQt5 UI code generator 5.13.2
#
# WARNING! All changes made in this file will be lost!

#import vat

import os
import openpyxl

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QFileDialog, QMessageBox, QDialog, QInputDialog

global glob
glob = "empty"

class Ui_MainWindow(QtWidgets.QWidget):

    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.setEnabled(True)
        MainWindow.resize(633, 392)

        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap("icon01.webp"), QtGui.QIcon.Selected, QtGui.QIcon.On)
        MainWindow.setWindowIcon(icon)

        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit.setGeometry(QtCore.QRect(20, 40, 561, 20))
        self.lineEdit.setObjectName("lineEdit")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(590, 40, 25, 19))
        self.pushButton.setObjectName("pushButton")

        self.pushButton.clicked.connect(self.browsefiles)

        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(20, 20, 141, 16))
        font = QtGui.QFont()
        font.setPointSize(10)
        self.label.setFont(font)
        self.label.setObjectName("label")
        self.mdiArea = QtWidgets.QMdiArea(self.centralwidget)
        self.mdiArea.setGeometry(QtCore.QRect(10, 10, 611, 81))
        self.mdiArea.setObjectName("mdiArea")
        self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_2.setGeometry(QtCore.QRect(20, 110, 75, 23))
        self.pushButton_2.setObjectName("pushButton_2")

        **self.pushButton_2.clicked.connect(self.start_app)**

        self.mdiArea.raise_()
        self.lineEdit.raise_()
        self.pushButton.raise_()
        self.label.raise_()
        self.pushButton_2.raise_()
        MainWindow.setCentralWidget(self.centralwidget)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 633, 21))
        self.menubar.setObjectName("menubar")
        self.menuKonwerter = QtWidgets.QMenu(self.menubar)
        self.menuKonwerter.setObjectName("menuKonwerter")
        MainWindow.setMenuBar(self.menubar)
        self.menubar.addAction(self.menuKonwerter.menuAction())

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def browsefiles(self):
        path = "~"
        full_path = os.path.expanduser(path)
        filename = QFileDialog.getOpenFileName(None, "Plik excel do zaimportowania", full_path, "Excel (*.xls *.xlsx)")
        filepath = filename[0]
        self.lineEdit.setText(filepath)

    def start_app(self):
        filepath = self.lineEdit.text()
        glob = filepath

        try:
            import vat
        except:
            infoBox = QMessageBox()  ##Message Box that doesn't run
            infoBox.setIcon(QMessageBox.Question)
            infoBox.setText("Błąd pliku!")
            infoBox.setInformativeText("Użyj rozszerzenia .xlsx.")
            infoBox.setWindowTitle("Załadowano błędny plik")
            #infoBox.setDetailedText("Detailed Text")
            #infoBox.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
            infoBox.setEscapeButton(QMessageBox.Close)
            infoBox.exec()

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "Spradzenie podatników VAT"))
        self.pushButton.setText(_translate("MainWindow", "..."))
        self.pushButton_2.setText(_translate("MainWindow", "Uruchom"))
        self.label.setText(_translate("MainWindow", "Plik wejściowy (excel):"))
        self.menuKonwerter.setTitle(_translate("MainWindow", "Konwerter"))

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

vat.py
from my import *
print(glob)
#imp = Ui_MainWindow.setupUi.__getattribute__(lineEdit.text()) - dosent work

All looks fine but when I run my.py and click button2 (where as you can see I am taking path from line edit) this is not working. I see in vat.py script that "glob = empty". Of course vat.py file has more functions and doing something but I need to make all steps from vat.py file (but I need to transfer some variable. Is it possible to also make a feedback from vat to my when vat finish all steps?
TIA

A: You need to create a function in vat.py and move your code into that. That way you can import the function at the top of your script but call it only when you need it. You can also call it multiple times (unlike importing). And of course you can pass arguments to your function.
vat.py would look something like:
def vat(glob):
    print(glob)

In my.py you can then do:
from vat import vat

vat(glob)


text:
Q: How can I add one DataColumn in two different DataTable? I am trying to add one DataColumn in two different DataTable, but it is giving me error and saying that "Column 'imgCount' already belongs to another DataTable". Can I do this? here is my code.
DataTable dtS = new DataTable();
DataTable dtF = new DataTable();
DataColumn imgCount = new DataColumn("imgCount",Type.GetType("System.Int32"));
imgCount.DefaultValue = 0;
dtS = dvSho.ToTable("shooters");
dtS.Columns.Add(imgCount);
dtF = dvFys.ToTable("fyshwick");
dtF.Columns.Add(imgCount);

A: You can not add a single column instance to the DataTables.
Create separate instances for the two tables.
DataColumn imgCount = new DataColumn("imgCount",Type.GetType("System.Int32"));
DataColumn imgCount2 = new DataColumn("imgCount",Type.GetType("System.Int32"));

dtS = dvSho.ToTable("shooters");
dtS.Columns.Add(imgCount);

dtF = dvFys.ToTable("fyshwick");
dtF.Columns.Add(imgCount2);