text:
Q: How to efficiently find the largest perfect square dividing a given large integer? Given a number $n$. I need to find the largest $q$ such that $q^2$ divides $n$. I need the fastest method to find $q$. $q$ can be any number prime or composite.
At present I am factorizing the number $n$ to find the highest number $q$. I need a better approach which does not involve to factorize the number $n$ completely or by some other approach which is less than $O(\sqrt n)$. Constraint: $n\leq 10^{18}$
some test cases:

*

*if $n=180$ then $q=6$

*if $n=17$ then $q=1$

*if $n=10000$ then $q=100$

A: It is trivial to to compute square/squarefree parts if we are given the prime factorization. Currently we do not know any better way, and it is widely suspected that there is none, i.e the problem may prove to be equivalent to factorization.
This problem is important because one of the main tasks of computational algebraic number theory reduces to it (in deterministic polynomial time). Namely the problem of computing the ring of integers of an algebraic number field depends upon the square-free decomposition of the polynomial discriminant (when computing an integral basis).
Contrast this difficulty with the trivial squarefree decomposition of polynomials by way of gcd with its derivative. The availability of derivatives for polynomials opens up a powerful toolbox that is not available for integers. For example once derivatives are available so are Wronskians - which provide powerful measures of dependence in transcendence theory and diophantine approximation. A simple yet stunning example is the elementary proof of Mason's ABC theorem for polynomials, which yields as a very special case a high-school-level proof of FLT for polynomials.
For references see my post here.


text:
Q: OSX service menu entry: How to localize? I have setup an OSX service based on an Automator workflow that contains (among others) an Obj-C action.
I have successfully localized the Obj-C action, but I am not able to localize the service menu entry.
The Services implementation guide says one has to create a ServicesMenu.strings file for every localization. Other docs, e.g. this, say the same, and this SO entry suggests in an answer to apply some console commands to refresh a system file, but I am afraid to do so without understanding.
I have created the localized ServicesMenu.strings files in the Xcode project of the Obj-C action (because the Automator does not have an localization function), but these files are surely in the wrong bundle.
The problem is that I don't know where to place these files.
Any help is appreciated.
EDIT:
One of the links cited above says:
Adding a Localized ServicesMenu.strings file
To localize this text, you will need to add a UTF-16 encoded strings file named ServicesMenu.strings to your application project or Automator workflow bundle resources (details on how to do this are below). This strings file will contain, for each service menu item you are providing, an entry that uses the default text as the key, and the translated text as the value. For each language you wish to support, you will provide a translated ServicesMenu.strings file in a language-specific project (.lproj) directory in your project resources.
...
If you are providing a service from an Automator created workflow, you will need to manually add the strings files and .lproj resource directories to the workflow bundle. You can find Automator created workflow bundles in your home directory under ~/Library/Services.
I have done exactly this, but the localization does not work.
Below I added my Info.plist content, the folder structure and the ServiceMenu.strings file contents.

A: Here is my own solution. Maybe it helps somebody else.
The 1st problem was that I did not read the docs carefully enough. The text cited in my question continues:
Refreshing the Services menu
Once you have provided localized text for your service menu item title, you may need to refresh the Services menu list to see the changes. One way to refresh the list of services shown in the Services menu is by using the services debugging tool pbs. This is a command-line tool located in /System/Library/CoreServices that provides useful services debugging features, such as refreshing the list of services or printing out the current list of registered services. Listing 3 shows an example of a command-line you can enter into the Terminal application to refresh the list of services for English and French.
Listing 3  Example use of pbs to refresh services.
/System/Library/CoreServices/pbs -existing_languages en fr
The 2nd problem was that the command given in Listing 3 above did not work for me. However the command
/System/Library/CoreServices/pbs -update

actually updated the service menu and the localized menu entry was displayed.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Decimal to Hexadecimal conversion of a number with fractional part, in python? I want to change decimal with fraction to hexadecimal in python, I tried hex() function but works just for integer number

A:
Python uses the float class to represent the real numbers.
CPython implements float using C double type. The C double type
usually implements IEEE 754 double-precision binary float, which is
also called binary64.
Python float uses 8 bytes (or 64 bits) to represent real numbers.
Unlike the integer type, the float type uses a fixed number of bytes.
Technically, Python uses 64 bits as follows:
1 bit for sign (positive or negative) 11 bits for exponent 1.5e-5 1.5
x 10-5 (exponent is -5) the range is [-1022, 1023]. 52 bits for
significant digits

quotes from this site
Take integer part convert it to hexa decimal

And for fractional part use below algorithm:

*

*Take a fractional part of the number

*Multiply by 16

*Convert integer part of the number to hexadecimal and remove it

*Go to step 1
Finally join the integer and floating part together
please visit this link of stackoverflow for more details.
"""
Converts from float to hexadecimal
"""
def toHex(value:float):
    result = ""
    l = list()
    #converting to positive number and storing the - sign to the list
    if value < 0:
        value = -value;
        l.append('-')

    ivalue = int(value)#represent the integer part
    fvalue = value - ivalue#represent the floating part

    l.append(hex(ivalue))#storing the hexadecimal representation of integer part
    l.append('.')

    #float is 8 bytes and so has at most 16 hexadecimal values
    for i in range(16):
        fvalue = fvalue * 16
        digit = int(fvalue)
        l.append(format(digit,'X'))
        fvalue -= digit#removing the integer part
        if fvalue == 0:
          break
    #converting the result to a string
    for v in l:
        result += str(v)

    return result;

print(toHex(3.141592653))

Output:
$ python3 hexa.py
0x3.243F6A85FD27


text:
Q: Page number top left on all pages I want to put the page number on the left corner of the pages. I've already achieved it using fancyhdr:
\usepackage{fancyhdr}
\pagestyle{fancy}
\fancyhf{} % clear all header and footers
\renewcommand{\headrulewidth}{0pt} % remove the header rule
\lfoot{\thepage}

The problem is that the first page remains with the page number on center. Can anyone solve this? Thanks in advance.

A: Please always provide a minimal example which can be used to reproduce the issue. You can always edit your question to include further information. Code pasted in comments is essentially unreadable by human beings.
The reason the problem doesn't show up in a minimal completion of your fragment is the lack of any document element which triggers the plain page style. In article this is activated by \maketitle. In other classes it may be triggered by other commands such as \chapter.
To change the page number on plain pages, just read the fancyhdr documentation and redefine the plain style with the commands it provides.
\documentclass{article}
\usepackage{fancyhdr}
\pagestyle{fancy}
\fancyhf{} % clear all header and footers
\renewcommand{\headrulewidth}{0pt} % remove the header rule
\lfoot{\thepage}
\fancypagestyle{plain}{%
  \fancyhf{}%
  \fancyhf[lf]{\thepage}%
}
\usepackage{kantlipsum}
\author{me}
\title{this}
\begin{document}
\maketitle
\kant[1-10]
\end{document}

A: Please provide a running minimal example. Creating it might have already revealed the problem: I cannot reproduce your problem as my code (see below) does not show the behavior that you described.
\documentclass{article}
\usepackage{fancyhdr}

\begin{document}

\pagestyle{fancy}
\fancyhf{} % clear all header and footers
\renewcommand{\headrulewidth}{0pt} % remove the header rule
\lfoot{\thepage}

test for first page \clearpage
test for second page

\end{document}

A: Since you're using article that by default states \pagestyle{plain} everywhere, you can just redefine the plain page style.
\documentclass{article}
\usepackage{fancyhdr}
\usepackage{kantlipsum} % just for the example

\fancypagestyle{plain}{%
  \renewcommand{\headrulewidth}{0pt}%
  \fancyhf{}%
  \fancyfoot[L]{\thepage}%
}
\pagestyle{plain} % so LaTeX updates the definition

\author{me}
\title{this}

\begin{document}

\maketitle

\kant[1-10]

\end{document}

Add the rest of your setup to this simple template. What you show in the comments scattered among the question and other answers shows nothing that can conflict with this.


text:
Q: load csv file from cloud storage to big query I am trying to load a simple cvs file in Cloud Storage to a BigQuery table using apps script. I have already created the table and want to append the file to existing data in the table. When I run the script I get the following error message 'The mediaData parameter only supports Blob types for upload'. I'm not sure how to progress with this and have hit a brick wall searching for answers. Here is the code snippet I'm using:
function loadCloudStorageFileToBigQuery(source, datasetId, tableId, schema) {
    try{
        var tableReference = BigQuery.newTableReference();
        tableReference.setProjectId(MY_PROJECT);
        tableReference.setDatasetId(datasetId);
        tableReference.setTableId(tableId);

        var load = BigQuery.newJobConfigurationLoad();
        load.setDestinationTable(tableReference);
        load.setSourceUris([source]);
        load.setSourceFormat('CSV');
        load.setSchema(schema);
        load.setMaxBadRecords(0);
        load.setWriteDisposition('WRITE_TRUNCATE');

        var configuration = BigQuery.newJobConfiguration();
        configuration.setLoad(load);

        var newJob = BigQuery.newJob();
        newJob.setConfiguration(configuration);

        var job = BigQuery.Jobs.insert(newJob, null, {projectId:MY_PROJECT});

    }catch(err){
        Logger.log('Table upload error: %s', err);
    }
}

Any advice or help would be most appreciated.

A: I solved the problem by simply changing the actual load insert to the following:
var job = BigQuery.Jobs.insert(newJob, MY_PROJECT);
I also removed the schema as the table already exists
The working function is as follows:
        var tableReference = BigQuery.newTableReference();
        tableReference.setProjectId(MY_PROJECT);
        tableReference.setDatasetId(datasetId);
        tableReference.setTableId(tableId);

        var load = BigQuery.newJobConfigurationLoad();
        load.setDestinationTable(tableReference);
        load.setSourceUris([source]);
        load.setSourceFormat('CSV');
        load.setMaxBadRecords(0);
        load.setWriteDisposition('WRITE_APPEND');

        var configuration = BigQuery.newJobConfiguration();
        configuration.setLoad(load);

        var newJob = BigQuery.newJob();
        newJob.setConfiguration(configuration);

        var job = BigQuery.Jobs.insert(newJob, MY_PROJECT);


text:
Q: How do i Fetch this data inside json array I want to fetch data from this http://gdata.youtube.com/feeds/api/users/velosofy?v=2&alt=json
I can get all the other data but i can't get the "countHint" inside the json array.
This is what i use to get for example the "display":
$realUserName = 'velosofy';
$data = file_get_contents('http://gdata.youtube.com/feeds/api/users/' . $realUserName . '
v=2&alt=json');
$data = json_decode($data, true);

echo 'displayname = '. $data['entry']['yt$username']['display'].'<br />';
My questions is: How can i echo the countHint of for example Subscriptions?

A: I'm getting count for your code:
echo $data["entry"]['gd$feedLink'][0]["countHint"];

If you use double quotation for gd$feedLink, it won't work as index string contain $feedlink. $feedlink will be consider as php variable.  So Try with single quote.

A: i believe the json structure changed: echo $data["entry"]['gd$comments']['gd$feedLink']["countHint"];


text:
Q: How do I get PHP to properly URL encode a numerically indexed array? I have a PHP service that pulls in POST data from the client like so:
if($_POST['data']) {
    $uid = $_POST['data'][0];
    $cid = $_POST['data'][1];
    // ...
}

The client sends URL encoded POST data like this:
'data%5B%5D=58&data%5B%5D=17'

Client Javascript passes an array to form the above string:
var data = [58,17];

Now I'm writing another PHP script where I want to call the former service from within PHP using cURL. However, the following attempts to properly URL encode this simple array are not creating the format that I know the client sends:
// Valid, expected URL encoded result
echo "
data%5B%5D=58&data%5B%5D=17
";

// User-submitted function from PHP.net
// that's supposed to do it right, but doesn't
function cr_post($a, $b = '', $c = 0) {
    if (!is_array($a)) return false;

    foreach ((array)$a as $k=>$v) {
        if($c) {
            if(is_numeric($k)) {
                $k = $b."[]";
            } else {
                $k = $b."[$k]";
            }
        } else if (is_int($k)) {
            $k = $b.$k;
        }

        if(is_array($v)||is_object($v)) {
            $r[] = cr_post($v,$k,1);
            continue;
        }

        $r[] = urlencode($k)."=".urlencode($v);
    }

    return implode("&",$r);
}

echo '
'.cr_post(array(58,17)).'
'; // Outputs '0=58&1=17' incorrectly

// Another attempt
$data = array(58,17);
$query = http_build_query($data);
$query = preg_replace('/%5B[0-9]+%5D/simU', '%5B%5D', $query);

echo '
'.$query.'
'; // Outputs '0=58&1=17' incorrectly

Is there a better or easier way to do this? What's wrong with my approach?

A: You were close at second attempt:
$data = array(58,17);
//equivalent to $string = 'data%5B0%5D=58&data%5B1%5D=17';
$string = http_build_query(array('data' => $data));

You could strip those numeric indexes with preg_replace, but I would try if it changes anything first.


text:
Q: How can I force entity framework to insert identity columns? I want to write some C# code to initialize my database with some seed data.  Clearly, this is going to require the ability to be able to set the values of various Identity columns when inserting.  I'm using a code-first approach.  By default, DbContext handles the database connection and so you can't SET IDENTITY_INSERT [dbo].[MyTable] ON.  So, what I've done so far is use the DbContext constructor that lets me specify a DB connection to be used.  Then, I set IDENTITY_INSERT to ON in that DB connection, and then try to insert my records using entity framework.  Here's an example of what I've got so far:
public class MyUserSeeder : IEntitySeeder {
    public void InitializeEntities(AssessmentSystemContext context, SqlConnection connection) {
        context.MyUsers.Add(new MyUser { MyUserId = 106, ConceptPersonId = 520476, Salutation = "Mrs", Firstname = "Novelette", Surname = "Aldred", Email = null, LoginId = "520476", Password="28c923d21b68fdf129b46de949b9f7e0d03f6ced8e9404066f4f3a75e115147489c9f68195c2128e320ca9018cd711df", IsEnabled = true, SpecialRequirements = null });
        try {
            connection.Open();
            SqlCommand cmd = new SqlCommand("SET IDENTITY_INSERT [dbo].[MyUser] ON", connection);
            int retVal = cmd.ExecuteNonQuery();
            context.SaveChanges();
        }
        finally {
            connection.Close();
        }
    }
}

So close and yet so far - because, although cmd.ExecuteNonQuery() works fine, when I then run context.SaveChanges(), I'm informed that "Explicit value must be specified for identity column in table 'MyUser' either when IDENTITY_INSERT is set to ON or when a replication user is inserting into a NOT FOR REPLICATION identity column."
Presumably, because MyUserId (which is the Identity column in the MyUser table) is the primary key, entity framework doesn't try to set it when I call context.SaveChanges(), even though I gave the MyUser entity a value for the MyUserId property.
Is there a way to force entity framework to try and insert even primary key values for an entity, then?  Or maybe a way to temporarily mark MyUserId as not being a primary key value, so EF tries to insert it?

A: EF 6 method, using the msdn article:
using (var dataContext = new DataModelContainer())
using (var transaction = dataContext.Database.BeginTransaction())
{
    var user = new User()
    {
        ID = id,
        Name = "John"
    };

    dataContext.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [dbo].[User] ON");

    dataContext.User.Add(user);
    dataContext.SaveChanges();

    dataContext.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [dbo].[User] OFF");

    transaction.Commit();
}

Update: To avoid error "Explicit value must be specified for identity column in table 'TableName' either when IDENTITY_INSERT is set to ON or when a replication user is inserting into a NOT FOR REPLICATION identity column", you should change value of StoreGeneratedPattern property of identity column from Identity to None in model designer.
Note, changing of StoreGeneratedPattern to None will fail inserting of object without specified id (normal way) with error "Cannot insert explicit value for identity column in table 'TableName' when IDENTITY_INSERT is set to OFF".

A: Here is the solution of the problem. I have tried it on EF6 and it worked for me. Following is some pseudo code that should work.
First of all you need to create the overload of the default dbcontext. If you check the base class, you will find the one with passing existing dbConnection.
Check following code-
public MyDbContext(DbConnection existingConnection, bool contextOwnsConnection)
        : base(existingConnection, contextOwnsConnection = true)
    {
        //optional
        this.Configuration.ProxyCreationEnabled = true;
        this.Configuration.LazyLoadingEnabled = true;
        this.Database.CommandTimeout = 360;
    }

And in On modelcreating remove the db generated option like,
protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<MyTable>()
            .Property(a => a.Id)
            .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);

        base.OnModelCreating(modelBuilder);
    }

Now in code you need to pass a connection object explicitly,
using (var connection = new System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringName"].ConnectionString))
        {
            connection.Open();
            using (var context = new MyDbContext(connection, true))
            {
                context.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [dbo].[MyTable] ON");
                context.MyTable.AddRange(objectList);
                context.SaveChanges();
                context.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [dbo].[MyTable] OFF");
            }

            connection.Close();
        }

A: After careful consideration, I've decided that entity framework's refusal to insert identity columns is a feature, not a bug.  :-)  If I were to be inserting all entries in my database including their identity values, I'd also have to create an entity for every link table that entity framework had created automatically for me!  It's just not the right approach.
So what I'm doing is setting up seeding classes that just use C# code and create EF entities, then use a DbContext to save the newly-created data.  It takes a bit longer to take the dumped SQL and turn it into C# code, but there isn't (and shouldn't be) too much data just for "seeding" data - it should be a smallish amount of data which is representative of the kind of data that would be in a live DB that can quickly be put into a fresh DB for debugging/development purposes.  This does mean that if I want to link entities together, I do have to do queries on what has already been inserted or my code wouldn't know their generated identity value, eg. This kind of thing will appear within the seeding code, after I have set up and done context.SaveChanges for MyRoles:
var roleBasic = context.MyRoles.Where(rl => rl.Name == "Basic").First();
var roleAdmin = context.MyRoles.Where(rl => rl.Name == "Admin").First();
var roleContentAuthor = context.MyRoles.Where(rl => rl.Name == "ContentAuthor").First();

MyUser thisUser = context.MyUsers.Add(new MyUser {
    Salutation = "Mrs", Firstname = "Novelette", Surname = "Aldred", Email = null, LoginUsername = "naldred", Password="c1c966821b68fdf129c46de949b9f7e0d03f6cad8ea404066f4f3a75e11514748ac9f68695c2128e520ca0275cd711df", IsEnabled = true, SpecialRequirements = null
});
thisUser.Roles.Add(roleBasic);

Doing it this way also makes it more likely I will update my seeding data when I change the schema, because I will likely break the seeding code when I change it (if I remove a field or entity, the existing seeding code that uses that field/entity will fail to compile).  With a SQL script for doing seeding, that wouldn't be the case, and nor would the SQL script be database-agnostic.
So I think that if you're trying to set the identity fields of entities for doing DB seeding data, you've definitely taken the wrong approach.
If I were actually dragging a load of data from say SQL Server to PostgreSQL (a full live DB, not just some seeding data), I could do it via EF, but I'd want to have two contexts open at the same time, and write some code to grab all the various entities from the source context and put them into the destination context, then save changes.
Generally, the only time it's appropriate to insert identity values is when you're copying from one DB to another DB within the same DBMS (SQL Server -> SQL Server, PostgreSQL -> PostgreSQL, etc.), and then you'd do it in a SQL script and not EF code-first (the SQL script wouldn't be DB-agnostic, but it wouldn't need to be; you're not going between different DBMSs).

A: This idea only works reliably if the target table is empty, or records are being inserted with ids higher than all already existing ids in the table!
3 years on and I hit a similar problem transferring production data into a test system. The users wanted to be able to copy the production data into the test system whenever they wanted to, so instead of setting up a transfer job in SQL Server I looked for a way to accomplish the transfer in the application using the existing EF classes. This way I could provide the users a menu item to start the transfer whenever they wanted.
The application uses a MS SQL Server 2008 database and EF 6. As the two databases generally have the same structure I thought I could easily transfer data from one DbContext instance to another by reading the records of each entity using AsNoTracking() and just Add() (or AddRange()) the records to the appropriate property on the target DbContext instance.
Here is a DbContext with one entity to illustrate:
public class MyDataContext: DbContext
{
    public virtual DbSet<Person> People { get; set; }
}

To copy the People data I did the following:
private void CopyPeople()
{
    var records = _sourceContext.People.AsNoTracking().ToArray();
    _targetContext.People.AddRange(records);
    _targetContext.SaveChanges();
}

As long as the tables were copied in the right order (to avoid problems with foreign key constraints) this worked very well. Unfortunately tables using identity columns made things a little difficult, as EF ignored the id values and just let SQL Server insert the next identity value. For tables with identity columns I ended up doing the following:

*

*Read all the records of a given entity

*Order the records by id in ascending order

*set the identity seed for the table to the value of the first id

*keeping track of the next identity value, add the records one by one. If the id is not the same as the expected next identity value set the identity seed to the next required value

As long as the table is empty (or all the new records have ids higher that current hisghest id), and the ids are in ascending order, EF and MS SQL will insert the required ids and neither system will complain.
Here is a bit of code to illustrate:
private void InsertRecords(Person[] people)
{
    // setup expected id - presumption: empty table therefore 1
    int expectedId = 1;

    // now add all people in order of ascending id
    foreach(var person in people.OrderBy(p => p.PersonId))
    {
        // if the current person doesn't have the expected next id
        // we need to reseed the identity column of the table
        if (person.PersonId != expectedId)
        {
            // we need to save changes before changing the seed value
            _targetContext.SaveChanges();

            // change identity seed: set to one less than id
            //(SQL Server increments current value and inserts that)
            _targetContext.Database.ExecuteSqlCommand(
                String.Format("DBCC CHECKIDENT([Person], RESEED, {0}", person.PersonId - 1)
            );

            // update the expected id to the new value
            expectedId = person.PersonId;
        }

        // now add the person
        _targetContext.People.Add(person);

        // bump up the expectedId to the next value
        // Assumption: increment interval is 1
        expectedId++;
    }

    // now save any pending changes
    _targetContext.SaveChanges();
}

Using reflection I was able to write a Load and a Save method that worked for all the entities in the DbContext.
It's a bit of a hack, but it allows me to use the standard EF methods for reading and writing entities and overcomes the problem of how to set identity columns to particular values under a set of given circumstances.
I hope this will be of help to someone else faced with a similar problem.

A: You don't need to do any funny business with the connection, you can cut out the middle man and just use ObjectContext.ExecuteStoreCommand.
You could then achieve what you want by doing this:
context.ExecuteStoreCommand("SET IDENTITY_INSERT [dbo].[MyUser] ON");

I don't know of any inbuilt way of telling EF to set identity insert on though.
It's not perfect, but it'd be more flexible and less "hacky" than your current approach.
Update:
I just realised that there is a second part to your problem.  Now that you've told SQL that you want to do identity inserts, EF isn't even trying to insert values for said identity (why would it? we haven't told it to).
I've not got any experience with a code first approach, but from some quick searches it seems that you need to tell EF that your column shouldn't be generated from the store.  You'll need to do something like this.
Property(obj => obj.MyUserId)
    .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None)
    .HasColumnName("MyUserId");

Hopefully this will get you pointed in the right direction :-)

A: Bit late to the party, but in case somebody encounters this problem in EF5 with DB first: I couldn't get either solution to work, but found another workaround:
Before the running the .SaveChanges() command, I reset the table's identity counter:
Entities.Database.ExecuteSqlCommand(String.Format("DBCC CHECKIDENT ([TableNameHere], RESEED, {0})", newObject.Id-1););
Entities.YourTable.Add(newObject);
Entities.SaveChanges();

This means that .SaveChanges() needs to be applied after every addition - but at least it works!

A:
Is there a way to force entity framework to try and insert even primary key values for an entity?

Yes, but not as cleanly as I would like to see.
Assuming you are using an auto-generated identity key, EF will completely ignore your attempt to store the key value. This appears to be "By design" for the many good reasons detailed above, but there are still times when you want to fully control your seed data (or an inital load). I suggest EF accomidate this kind of seeding in a future version. But until they do, just write a little code that works within the framework and automates the messy details.
Eventho VendorID is ignored by EF, you can use it with basic looping and counting to determine how many place holder records to add between your live records. The place holders are assigned the next available ID number when they are added. Once your live records have the requested IDs, you just need to delete the junk.
    public class NewsprintInitializer: DropCreateDatabaseIfModelChanges<NewsprintContext>
    {
        protected override void Seed(NewsprintContext context)
        {
            var vendorSeed = new List<Vendor>
            {
                new Vendor { VendorID = 1, Name = "#1 Papier Masson / James McClaren" },
                new Vendor { VendorID = 5, Name = "#5 Abitibi-Price" },
                new Vendor { VendorID = 6, Name = "#6 Kruger Inc." },
                new Vendor { VendorID = 8, Name = "#8 Tembec" }
            };

            //  Add desired records AND Junk records for gaps in the IDs, because .VendorID is ignored on .Add
            int idx = 1;
            foreach (Vendor currentVendor in vendorSeed)
            {
                while (idx < currentVendor.VendorID)
                {
                    context.Vendors.Add(new Vendor { Name = "**Junk**" });
                    context.SaveChanges();
                    idx++;
                }
                context.Vendors.Add(currentVendor);
                context.SaveChanges();
                idx++;
            }
            //  Cleanup (Query/Find and Remove/delete) the Junk records
            foreach (Vendor del in context.Vendors.Where(v => v.Name == "**Junk**"))
            {
                context.Vendors.Remove(del);
            }
            context.SaveChanges();

            // setup for other classes

        }
    }

It worked as expected, except I had to do "SaveChanges" frequently to keep the IDs in order.

A: After experimenting several options found on this site, the following code worked for me (EF 6). Notice that it first attempts a normal update if the item already exists.  If it does not, then tries a normal insert, if the error is due to IDENTITY_INSERT then tries the workaround.  Notice also that db.SaveChanges will fail, hence the db.Database.Connection.Open() statement and optional verification step.  Be aware this is not updating the context, but in my case it is not necessary.  Hope this helps!
public static bool UpdateLeadTime(int ltId, int ltDays)
{
    try
    {
        using (var db = new LeadTimeContext())
        {
            var result = db.LeadTimes.SingleOrDefault(l => l.LeadTimeId == ltId);

            if (result != null)
            {
                result.LeadTimeDays = ltDays;
                db.SaveChanges();
                logger.Info("Updated ltId: {0} with ltDays: {1}.", ltId, ltDays);
            }
            else
            {
                LeadTime leadtime = new LeadTime();
                leadtime.LeadTimeId = ltId;
                leadtime.LeadTimeDays = ltDays;

                try
                {
                    db.LeadTimes.Add(leadtime);
                    db.SaveChanges();
                    logger.Info("Inserted ltId: {0} with ltDays: {1}.", ltId, ltDays);
                }
                catch (Exception ex)
                {
                    logger.Warn("Error captured in UpdateLeadTime({0},{1}) was caught: {2}.", ltId, ltDays, ex.Message);
                    logger.Warn("Inner exception message: {0}", ex.InnerException.InnerException.Message);
                    if (ex.InnerException.InnerException.Message.Contains("IDENTITY_INSERT"))
                    {
                        logger.Warn("Attempting workaround...");
                        try
                        {
                            db.Database.Connection.Open();  // required to update database without db.SaveChanges()
                            db.Database.ExecuteSqlCommand("SET IDENTITY_INSERT[dbo].[LeadTime] ON");
                            db.Database.ExecuteSqlCommand(
                                String.Format("INSERT INTO[dbo].[LeadTime]([LeadTimeId],[LeadTimeDays]) VALUES({0},{1})", ltId, ltDays)
                                );
                            db.Database.ExecuteSqlCommand("SET IDENTITY_INSERT[dbo].[LeadTime] OFF");
                            logger.Info("Inserted ltId: {0} with ltDays: {1}.", ltId, ltDays);
                            // No need to save changes, the database has been updated.
                            //db.SaveChanges(); <-- causes error

                        }
                        catch (Exception ex1)
                        {
                            logger.Warn("Error captured in UpdateLeadTime({0},{1}) was caught: {2}.", ltId, ltDays, ex1.Message);
                            logger.Warn("Inner exception message: {0}", ex1.InnerException.InnerException.Message);
                        }
                        finally
                        {
                            db.Database.Connection.Close();
                            //Verification
                            if (ReadLeadTime(ltId) == ltDays)
                            {
                                logger.Info("Insertion verified. Workaround succeeded.");
                            }
                            else
                            {
                                logger.Info("Error!: Insert not verified. Workaround failed.");
                            }
                        }
                    }
                }
            }
        }
    }
    catch (Exception ex)
    {
        logger.Warn("Error in UpdateLeadTime({0},{1}) was caught: {2}.", ltId.ToString(), ltDays.ToString(), ex.Message);
        logger.Warn("Inner exception message: {0}", ex.InnerException.InnerException.Message);
        Console.WriteLine(ex.Message);
        return false;
    }
    return true;
}

A: I had this work by creating a inherited context:
My regular context with EF migrations :
public class MyContext : DbContext
{
    public MyContext() : base("name=MyConnexionString")
    {...}

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        // best way to know the table names from classes...
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        ...
    }
}

My alternate context used to override identity.
Do not register this context for EF migrations
(I use it to transfer data from another database) :
public class MyContextForTransfers : MyContext
{
    public MyContextForTransfers() : base()
    {
        // Basically tells the context to take the database as it is...
        Database.SetInitializer<MyContextForTransfers >(null);
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
         // Tells the Context to include Isd in inserts
         modelBuilder.Conventions.Remove<StoreGeneratedIdentityKeyConvention>();
         base.OnModelCreating(modelBuilder);
    }
}

How to insert (error management is highly simplified...):
public void Insert<D>(iEnumerable<D> items)
{
    using (var destinationDb = new MyContextForTransfers())
    {
        using (var transaction = destinationDb.Database.BeginTransaction())
        {
            try
            {
                destinationDb.Database.ExecuteSqlCommand($"SET IDENTITY_INSERT [dbo].[{typeof(D).Name}] ON");
                destinationDb.Set<D>().AddRange(items);
                destinationDb.SaveChanges();
                destinationDb.Database.ExecuteSqlCommand($"SET IDENTITY_INSERT [dbo].[{typeof(D).Name}] OFF");
                transaction.Commit();
             }
             catch
             {
                transaction.Rollback();
             }
         }
    }
}

Checking for migrations before any transaction might be a good idea, with the "regular" context and configuration :

A: I'm just a DBA, but whenever something like this pops up, I consider it a code smell. That is, why do you have anything that relies on certain rows having certain identity values? That is to say, in your above example, why does Mrs Novelette need an identity value of 106? Rather than rely on that always being the case, you can get her identity value and use that wherever you'd have hardcoded 106. A little more cumbersome, but way more flexible (in my opinon).

A: This did the trick (I happen to be using EFCore 3.x at the moment, surely is valid for later versions). Call this with input of true (i.e. set IDENTITY_INSERT to ON) sometime before your first call to SaveAsync. Call it again with false when done (maybe not required). Key point is that OpenConnection had to be set to make this work. If saving multiple times on one context, in my experience one still only needs to call this once, at the start, but even if this is called / set to true multiple times it didn't hurt.
public void Set_IDENTITY_INSERT(bool turnOn, DbContext context, string tableName)
{
    var db = context.Database;

    string command = $"SET IDENTITY_INSERT {tableName} {(turnOn ? "ON" : "OFF")}";

    if(turnOn)
        db.OpenConnection();

    db.ExecuteSqlCommand(command);

    if(!turnOn)
        db.CloseConnection();
}

A: I couldn't find a way to insert records into a table. Basically, I created a SQL script with something like this...
            sb.Append("SET IDENTITY_INSERT [dbo].[tblCustomer] ON;");

            foreach(...)
            {
                var insert = string.Format("INSERT INTO [dbo].[tblCustomer]
                     ([ID],[GivenName],[FamilyName],[NINumber],[CustomerIdent],
                      [InputterID],[CompanyId],[Discriminator])
                      VALUES({0}, '{1}', '{2}', '{3}', '{4}', 2, 2, 'tblCustomer'); ",
                          customerId, firstName, surname, nINumber, Guid.NewGuid());

            sb.Append(insert);
                ...
            }

            sb.Append("SET IDENTITY_INSERT [dbo].[tblCustomer] OFF;");
            using (var sqlConnection = new SqlConnection(connectionString))
            {
                var svrConnection = new ServerConnection(sqlConnection);
                var server = new Server(svrConnection);
                server.ConnectionContext.ExecuteNonQuery(sb.ToString());
        }

I am using EF 6.

A: My solution for EF6 Code First. Depends on the table not requiring any other column to be filled in.
  db.Database.ExecuteSqlCommand($"SET IDENTITY_INSERT [**table**] ON; insert into [**table**] ([ID]) values (@id)", new SqlParameter("id", entity.ID));

  db.Entry(entity).State = EntityState.Modified;

  await db.SaveChangesAsync();

First line creates an empty row in the table, with the desired ID. Second line marks the model as dirty, otherwise no changes would be detected. Third line saves the changes.
This solution is not perfect, but resolves the NOT FOR REPLICATION error for Code First.
Update 16/08/22
To explain my reasoning for the 'limited' solution, and why it I thought it was worth posting it here.
Our requirement was for a maintenance script, I did not want to affect either our models or our context class permanently. Our identity column is there for a reason.
Luckily (I guess), I was in a position where I already knew the table had no required columns other than the primary key. As has been pointed out, this isn't always the case, but it was this time.
Had I have had additional columns to worry about, I would have been reluctant to add them to the SQL script. Even though the table question rarely changes, it is still clearly a code smell.
But with all things, it is a trade off (see every other answer), and if you're reading this and wondering how to deal with additional columns.
I think my first choice would be to look at inheriting my main context class, and deconstructing identify column there. Overkill for my immediate requirements, as the initial solution works very well.
My second choice, as I alluded to above, would be to add the extra column(s) to the SQL script with sensible defaults. Then perhaps come up with a manual process, ensuring that SQL stayed in sync.


text:
Q: Modal not displayed when clicking a navbar link I'm currently trying to implement a modal that would show up when clicking a link in a navbar. I'm aware that similar questions have already been asked, but none of the solutions could work.

  My Tool

FAQ

About

Add Something

    <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Modal title

    ...

    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
    <button type="button" class="btn btn-primary">Save changes</button>

Scripts I'm using are : bootstrap.js, bootstrap.min.js, jquery-2.1.4.min.js
P.S : I've already tried the href="#" in the link.
Thanks for the help!

A: Try this:
(I only inserted the correct dependencies, your code is working)

<link type="text/css" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">

  My Tool

FAQ

About

Add Something

    <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Modal title

    ...

    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
    <button type="button" class="btn btn-primary">Save changes</button>


text:
Q: Is it possible to have private functions (let definitions) in F# modules? I'd like to make applyAndTruncate hidden from the outside world (that is, from anything outside the Scoring module), as I really only use it as backbone for bestKPercent and worstKPercent. Is it possible to hide it? If not, what is the F#ish way of accomplishing what I want to do?
module Scoring
    let applyAndTruncate f percentage (scoredPopulation:ScoredPopulation) : ScoredPopulation =
      if (percentage < 0.0 || percentage > 1.0) then
        failwith "percentage must be a number between 0.0 and 1.0"

      let k = (int)(percentage * (double)(Array.length scoredPopulation))

      scoredPopulation
      |> f
      |> Seq.truncate k
      |> Seq.toArray

    let bestKPercent = applyAndTruncate sortByScoreDesc
    let worstKPercent = applyAndTruncate sortByScoreAsc

A: Yes. let private myfunc = will do it.

A: You can also use signature files to specify the public interface of a corresponding implementation file. Then the idea is that you don't worry about accessibility until the implementation has solidified. I've honestly not ever used them, but they are used in the F# compiler source code extensively (probably just because I'm comfortable with the implementation site style used in so many other languages, whereas folks with original ML experience will be at ease with signature files; also, you do get some extra features with signature files, though nothing super compelling).
So if your Scoring module were implemented in a file named Scoring.fs, you'd have a corresponding signature file named Scoring.fsi that would look something like:
namespace NS //replace with you actual namespace; I think you must use explicit namespaces
module Scoring =
    //replace int[] with the actual ScoredPopulation type; I don't think you can use aliases
    val bestKPercent : (float -> int[] -> int[])
    val worstKPercent : (float -> int[] -> int[])


text:
Q: How to change default color scheme of Nimbus L&F I want to change Nimbus L&F color scheme in my desktop application. What is the best way for doing this?
I tried the following approach, but it requires manual definition of a color for each component of the GUI. Is there any quick-way? For instance, let's say I want to change default color scheme of Nimbus to the Blue.
UIManager.put("nimbusBase", new Color(61,89,171));
UIManager.put("menu", new Color(61,89,171));
//...


text:
Q: Java.lang.NullPointerException error. Checking for a null object So what I'm trying to do here is to check if an object exists or not through if(x.next==null) and I'm getting an error for that which won't let me access a null object. I also get the same error when trying to modify an object for e.g. x.next=y
The code is simple, it's just to implement a linked list.
Thanks!
//import SingleLinkedList1.Node;

public class SingleLinkedList2 implements ISimpleList2 {

private class Node
{   int    value;
    Node   next; }

private Node first;
private Node last;

public void insertFront(int item) {
    // TODO Auto-generated method stub
    Node oldfirst = first;

    // Create the new node
    Node newfirst = new Node();
    newfirst.value = item;
    newfirst.next = oldfirst;

    // Set the new node as the first node
    first = newfirst;
    if(oldfirst.next==null){
        last=first;
    }
}

public int removeFront() {
    // TODO Auto-generated method stub
    // Save the previous first
    Node oldfirst = first;

    if(oldfirst.next==null){
        last=null;
    }

    // Follow the first's node (possibly empty)
    // and set the first to that pointer
    first = oldfirst.next;

    // Return the value of old first
    return oldfirst.value;

}

public void insertEnd(int item) {
    // TODO Auto-generated method stub

    Node newLast=new Node();
    newLast.value=item;
    last.next=newLast;

    last=newLast;

}

public int removeEnd() {
    // TODO Auto-generated method stub
    Node oldLast=last;
    Node check=new Node();
    check=first;
    while(check.next!=last ){
        check=check.next;
    }
    last=check;

    return oldLast.value;

}

public boolean isEmpty()
{
    if(first.next==null){
        return true;
    }
    else{
        return false;
    }
}

}

A: I think you should check x that can be null..
like in code f(x == null), because if x is null then you will get NullPointException.

A: This is quite common.
You have to ensure that the object itself isn't null.
In your check if(x.next==null) the evaluation of x.next throws a NullPointerException because x itself is Null.
E.g. In the isEmpty method you have to check if(first==null)


text:
Q: Enum Associated Value Lookup I have an enum with different associated value custom classes. Then trying to create a calculated value to determine if one particular type and return the value if so. The below works using a switch in the calculated value but seems a bit clumsy. Are there any cleaner approaches? Thanks.
private enum Situation: Equatable {
    case inLocation(LocationMO)
    case heldByBeing(BeingMO)
    case inContainer(PhysicalObjectMO)
}

private var isInSituation: Situation

var isInLocation: LocationMO? {
    switch isInSituation {
    case .inLocation(let validLocation): return validLocation
    default: return nil
    }
}


text:
Q: Adding another parameter to a join query I am using some MySQL tables.  Their structures are listed below.
"login":
loginid username password email actcode disabled activated created points website location age gender

Each user has a loginid
"submission":
submissionid loginid title slug url displayurl datesubmitted

In the submission table above, the "loginid" is the loginid of the user that submitted the submission.
"comment":
commentid loginid submissionid comment datecommented

In the comment table above, "loginid" is the loginid of the user who made the comment.  "submissionid" is the submission on which the comment was made.
The query below ranks the top 25 loginids by (days the loginid has been in existence) + (total submissions by the loginid) * 10 + (comments by the loginid).
I would like to include one more factor: (total comments made on submissionids that the loginid has submitted) * 10.
It would require the following:

*

*Getting all submissionids in the table "submission" for a given loginid

*Summing the total number of entries in the table "comment" that have those submissionids

How can I do this?
Thanks in advance,
John
$sqlStr2 = "SELECT
    l.loginid,
    l.username,
    l.created,
    DATEDIFF(NOW(), l.created) + COALESCE(s.total, 0) * 10 + COALESCE(c.total, 0) AS totalScore2
FROM login l
LEFT JOIN (
    SELECT loginid, COUNT(1) AS total
    FROM submission
    GROUP BY loginid
) s ON l.loginid = s.loginid
LEFT JOIN (
    SELECT loginid, COUNT(1) AS total
    FROM comment
    GROUP BY loginid
) c ON l.loginid = c.loginid
GROUP BY l.loginid
ORDER BY totalScore2 DESC
LIMIT 25";

A: Introduce the below into your query as an additional join and then include the total * 10 into your totalscore2 calculation.
LEFT JOIN (
    SELECT S2.loginid, COUNT(1) AS total
    FROM submission S2
    INNER JOIN comment C2
    ON C2.submissionid = S2.submissionid
    GROUP BY S2.loginid
) scs ON scs.loginid = l.loginid


text:
Q: Jersey with Appengine Standard and CloudEndpoints Our appengine application consists of several microservices deployed in a mix of standard and flex environments. Since we are using both flex and standard we chose jerse to implement our backend services as endpoint framework does not work with flex. We are not able to make this combination of Jersey + Appengine Standard + Endpoint work. When we deploy the swagger using gcloud cloud manager, it does not link with the backend services.
I could not find any  documentation regarding how to integrate App engine standard and endpoint without using endpoint framework annotations.
Has anybody implemented the rest service backends using the combination
Jersey + App engine Standard + Cloud Endpoints. Is it possible to integrate Cloud endpoints and appengine standard without using endpoint framework annotations.
Pls note : We have tested Jersey + Flex + Endpoints and it works.

A: This is not tested or documented, so you are playing in a new area. It should work, and I'm happy to try and help you debug it. To use Endpoints on Standard with Flex, you have to do this:

*

*Including this dependency:
<dependency>
    <groupId>com.google.endpoints</groupId>
    <artifactId>endpoints-management-control-appengine-all</artifactId>
    <version>${endpoints.management.version}</version>
</dependency>

*Add this configuration to your web.xml, then add a filter-mapping to go in front of jersey:
<filter>
    <filter-name>endpoints-api-controller</filter-name>
    <filter-class>com.google.api.control.extensions.appengine.GoogleAppEngineControlFilter</filter-class>
    <init-param>
        <param-name>endpoints.projectId</param-name>
        <param-value>${endpoints.project.id}</param-value>
    </init-param>
    <init-param>
        <param-name>endpoints.serviceName</param-name>
        <param-value>echo-api.endpoints.${endpoints.project.id}.cloud.goog</param-value>
    </init-param>
</filter>

*Upload your OpenAPI specification using gcloud service-management deploy.

*In appengine-web.xml, add an environment variable definition:
<env-variables>
    <env-var name="ENDPOINTS_SERVICE_NAME" value="echo-api.endpoints.${endpoints.project.id}.cloud.goog" />
</env-variables>


text:
Q: Build Python and Pip from source and "bad interpreter: No such file or directory" I am trying to build Python and Pip from source. Following is the Dockerfile for it:
FROM buildpack-deps:stretch
ARG PYTHON_VERSION="3.6.5"
ARG PIP_VERSION="20.2"
ARG INSTALLATION_PREFIX="/opt/python/${PYTHON_VERSION}"

WORKDIR /usr/src/python
RUN wget -q https://www.python.org/ftp/python/$PYTHON_VERSION/Python-${PYTHON_VERSION}.tgz \
    && apt-get update \
    && apt-get install -y \
        make \
        build-essential \
        libssl-dev \
        zlib1g-dev \
        libbz2-dev \
        libreadline-dev \
        libsqlite3-dev \
        wget \
        curl \
        llvm \
        libncurses5-dev \
        libncursesw5-dev \
        xz-utils \
        tk-dev

RUN tar xvf Python-${PYTHON_VERSION}.tgz \
    && rm -f Python-${PYTHON_VERSION}.tgz

RUN cd Python-$PYTHON_VERSION \
    && ./configure \
        --prefix=${INSTALLATION_PREFIX} \
        --build=$(dpkg-architecture --query DEB_BUILD_GNU_TYPE) \
        --enable-loadable-sqlite-extensions \
        --enable-shared \
        --with-system-expat \
        --with-system-ffi \
        --without-ensurepip \
    && make -j $(nproc) \
    && make altinstall

ENV LD_LIBRARY_PATH="${INSTALLATION_PREFIX}/lib:$LD_LIBRARY_PATH"
RUN wget -q https://bootstrap.pypa.io/get-pip.py -O /get-pip.py \
    && /usr/src/python/Python-3.6.5/python /get-pip.py \
    --prefix ${INSTALLATION_PREFIX} \
    --disable-pip-version-check \
    --no-cache-dir \
    --no-warn-script-location \
    pip==${PIP_VERSION}

WORKDIR /

RUN mv ${INSTALLATION_PREFIX} /tmp/test
ENV LD_LIBRARY_PATH="/tmp/test/lib:$LD_LIBRARY_PATH"
ENV PATH="/tmp/test/bin:$PATH"

When I build the above Dockerfile, it builds fine and I am able to do python3.6 --version and pip --version and I get the expected results.
Now because of a requirement that I have(Imagine building different Python versions from source in a docker image and store these built runtimes somewhere and install them on demand to a location before using it), I need to move this built Python and Pip to a different location, for example /tmp/test...I was hoping that Python and Pip executables would work just as before but when I do a pip --version I get the following error:
root@12c243458190:/# pip --version
bash: /tmp/test/bin/pip: /opt/python/3.6.5/bin/python3.6: bad interpreter: No such file or directory

pip seems to have hard-coded the location of Python to the installation prefix it was given when it was built.
Any ideas on how to fix this issue?


text:
Q: Ignoring unknown parameters: label.x.npc, label.y.npc while using stat_fit_glance() in ggpmisc I am plotting a time series data from a CSV file in R. The time series itself plots well without any error with this code:
data <- read.csv("SSSA_SSS.csv",
                 header = T,
                 sep = ",",
                 dec = ".")
head(data)
data$Year <- as.Date(data$ï..Date, format = "%m/%d/%Y")
class(data$Year)
time_plot <- ggplot(data, aes(x = Year, y = SSSA)) +
    geom_line(color = '#2b83e7', size = 1) + geom_point(color = "red", size =
                                                            1) +
    scale_x_date(date_labels = "%Y", date_breaks = "5 year") +
    theme_bw() + stat_smooth(
        method = "lm",
        formula = y ~ x,
        size = 0.75,
        se = T,
        color = '#1ac179'
    ) + stat_poly_eq(
        face = "bold",
        parse = T,
        aes(label = ..eq.label..),
        formula = y ~ x,
        label.x.npc = 0.5,
        label.y = 0.2,
        size = 6,
        coef.digits = 4
    ) + stat_fit_glance(
    method = 'lm',
    method.args = list(formula = y ~ x),
    geom = 'text',
    aes(label = paste(
        "P-value = ", signif(..p.value.., digits = 4), sep = ""
    )),
    size = 5.7,
    label.x.npc = 0.5,
    label.y.npc = 0.9,
) + theme(
    # LABLES APPEARANCE
    plot.title = element_text(
        size = 14,
        face = "bold",
        colour = "black"
    ),
    axis.title.x = element_text(
        size = 17,
        face = "bold",
        colour = "black"
    ),
    axis.title.y = element_text(
        size = 17,
        face = "bold",
        colour = "black"
    ),
    axis.text.x = element_text(
        size = 15,
        face = "bold",
        colour = "black"
    ),
    # axis.text.y = element_text(size=12,  colour = "black"), # unbold
    axis.text.y = element_text(
        size = 15,
        face = "bold",
        colour = "black"
    ),
    # bold
    strip.text.x = element_text(
        size = 13,
        face = "bold",
        colour = "black"
    ),
    strip.text.y = element_text(
        size = 13,
        face = "bold",
        colour = "black"
    ),
    axis.line.x = element_line(color = "black", size = 1),
    axis.line.y = element_line(color = "black", size = 1),
    axis.ticks = element_line(color = "black", size = 1.2),
    panel.border = element_rect(
        colour = "black",
        fill = NA,
        size = 1
    )
print(time_plot)

 As you can see, I am able to modify the position of the equation with stat_poly_eq(), however "the p value" texts is not responding to the command i used :
stat_fit_glance(
        method = 'lm',
        method.args = list(formula = y ~ x),
        geom = 'text',
        aes(label = paste(
            "P-value = ", signif(..p.value.., digits = 4), sep = ""
        )),
        size = 5.7,
        label.x.npc = 0.5,
        label.y.npc = 0.9,
    )

Therefore i am unable to move the caption, even though it is overlapping with the curve as it returns with the following error:
1: Ignoring unknown parameters: face
2: Ignoring unknown parameters: label.x.npc, label.y.npc

I understand that "face" error, but i want to manually change the position of the "p-value". I'd be grateful if someone point me out my mistake, thank you.


text:
Q: Running Spring Boot within IntelliJ results in Unable to load 'javax.el.ExpressionFactory' I am trying to run a simple Spring Boot application that has the following Maven pom.file:
<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <start-class>com.ptkonline.EwsdProxyApplication</start-class>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

If I package the file using Maven, and run the application through java -jar application.jar, the application starts up normally. However, if I run it from IntelliJ by executing the main class, the startup fails with the following error:
2014-12-25 22:18:55.831 ERROR 3388 --- [           main] o.s.boot.SpringApplication               : Application startup failed

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor': Invocation of init method failed; nested exception is javax.validation.ValidationException: Unable to instantiate Configuration.
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1566)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:198)
    at org.springframework.context.support.PostProcessorRegistrationDelegate.registerBeanPostProcessors(PostProcessorRegistrationDelegate.java:199)
    at org.springframework.context.support.AbstractApplicationContext.registerBeanPostProcessors(AbstractApplicationContext.java:615)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:465)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:691)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:321)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:961)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:950)
    at com.ptkonline.EwsdProxyApplication.main(EwsdProxyApplication.java:13)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
Caused by: javax.validation.ValidationException: Unable to instantiate Configuration.
    at javax.validation.Validation$GenericBootstrapImpl.configure(Validation.java:279)
    at org.springframework.validation.beanvalidation.LocalValidatorFactoryBean.afterPropertiesSet(LocalValidatorFactoryBean.java:223)
    at org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor$Jsr303ValidatorFactory.run(ConfigurationPropertiesBindingPostProcessor.java:361)
    at org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor.afterPropertiesSet(ConfigurationPropertiesBindingPostProcessor.java:174)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1625)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1562)
    ... 19 common frames omitted
Caused by: javax.validation.ValidationException: HV000183: Unable to load 'javax.el.ExpressionFactory'. Check that you have the EL dependencies on the classpath
    at org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator.<init>(ResourceBundleMessageInterpolator.java:172)
    at org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator.<init>(ResourceBundleMessageInterpolator.java:118)
    at org.hibernate.validator.internal.engine.ConfigurationImpl.<init>(ConfigurationImpl.java:110)
    at org.hibernate.validator.internal.engine.ConfigurationImpl.<init>(ConfigurationImpl.java:86)
    at org.hibernate.validator.HibernateValidator.createGenericConfiguration(HibernateValidator.java:41)
    at javax.validation.Validation$GenericBootstrapImpl.configure(Validation.java:276)
    ... 24 common frames omitted

Has anyone been able to run a Spring Boot application directly from IntelliJ?

A: I had a similar problem when creating a WAR file using the Spring Initializr with Intellij, and by adding the following dependency the application executed without any errors, thank you:
    <dependency>
        <groupId>javax.el</groupId>
        <artifactId>javax.el-api</artifactId>
        <version>2.2.4</version>
    </dependency>

A: The problem is probably that the EL implementation is in the Tomcat starter that you marked as "provided". If it isn't provided (which it won't be for a JAR file) maybe you should just leave it out?

A: I've reproduced the same issue:
Error creating bean with name 'org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor': Invocation of init method failed; nested exception is javax.validation.ValidationException: Unable to instantiate Configuration.

Using in POM versions of Java 11 and Spring Boot 1.3.0.RELEASE instead of:
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.3.0.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

to:
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.9.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

And working POM file was:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>springmvc</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>springmvc</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
        <!--<version>1.3.0.RELEASE</version>-->
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <java.version>11</java.version>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator-annotation-processor</artifactId>
            <version>4.1.0.Final</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

So I could even skip any additional dependencies in other answers, which were mentioned above:
<dependency>
    <groupId>javax.el</groupId>
    <artifactId>javax.el-api</artifactId>
    <version>2.2.4</version>
</dependency>

<dependency>
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-el</artifactId>
    <scope>test</scope>
</dependency>


text:
Q: Flutter and Firebase: Dynamic push notifications like Whatsapp Most tutorials I've seen on the topic of notifications either broadcast notifications through the Firebase Console, or create in-app notifications that don't work if the app is in the background or is closed completely.
Is there a way to make notifications pop up dynamically using Flutter and Firebase even when the app is closed? Something like Whatsapp or Instagram notifications.
Reference image for what I mean by notifications like Whatsapp: https://www.techidence.com/wp-content/uploads/2020/10/WhatsApp-Nootifications.jpg

A: You won't be able to generate dynamic notifications directly from Flutter. Since to do this, the App has to be active. Usually you would send these kind of notifications from some kind of backend. Google Cloud Messaging exposes an API for this, which allows you to send POST requests to an Endpoint, and Google handles the sending of the actual notification.
Check this article under the point "1. Send Notification"
https://medium.com/@selvaganesh93/firebase-cloud-messaging-important-rest-apis-be79260022b5


text:
Q: Duplicate in ec2 instance list with pythonboto3 i made a tool that need to reboot a aws ec2 instances , the reboot works fine but when im listing the servers i have duplicates in the instance id , how i can list the instances without duplications?
https://gist.github.com/jacobamar8/7aa4367ed44c2d7235bc6e0c86ac0056
Thanks

A: Here:
for instance in instances:
    instancename = ''
    for tag in instance.tags:
        if tag["Key"] == 'Name':
            instancename = tag["Value"]
            break;
    t.add_rows([['InstanceID', 'InstanceName', 'IP'], [instance.id,
     instancename, instance.private_ip_address]])

For sorting by instance name, I had to add the instances to a list and sort that. after that added that to TextTable.
import boto3
from texttable import Texttable
t = Texttable()
client = boto3.client('ec2')
ec2 = boto3.resource('ec2')
describe_instance = []
instance = ec2.Instance('id')
instances = ec2.instances.filter(
    Filters=[{'Name': 'instance-state-name', 'Values': ['running', 'stopped']}])

instanceList = []
for instance in instances:
    instancename = ''
    for tag in instance.tags:
        if tag["Key"] == 'Name':
            instancename = tag["Value"]
            row = [['InstanceID', 'InstanceName', 'IP'], [
                        instance.id, instancename, instance.private_ip_address]]
            instanceList.append(row)

instanceList.sort(key=lambda x: x[1][1])

for instanceListItem in instanceList:
  t.add_rows(instanceListItem)

print(t.draw())


text:
Q: About a sequence with a simple property. I want to use 1-n to generate a sequence S whose length is 2*n. Each number from 1-n will appear exactly twice. The sequence should satisfy the following property: if S[i] = S[j] = k, i < j, j-i should be k. For example: when n=4, a target sequence is 11423243.
Question 1: Prove: only when n=4m or 4m+1, m >= 1, this kind of sequence exists.
Question 2: Given n, how to generate thus a sequence quickly?


text:
Q: ¿Cómo encender un LED a través de raspberry python y un PC en red local? La idea de esta pregunta es saber cómo, a través de un script de python en ubuntu, enviar una señal a una raspberry conectada en red local y que ésta, a su vez, encienda un LED.
¿Alguien tiene alguna idea de como hacerlo?

A: Una posible forma de hacerlo es con sockets.
Yo usaría sockets UDP si se trata de una red local, pues hay muy baja probabilidad de que los paquetes se pierdan en este tipo de red y es más sencillo implementar la lógica del servidor porque no tienes que preocuparte de mantener la conexión abierta o cerrarla, simplificando así la aplicación.
Éste sería un ejemplo:
import socket

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)  # Crear el socket udp
s.bind(("", 55555))                                   # Ponerle un número de puerto

while True:  # Bucle infinito, se repite por siempre
    mensaje, _ = s.recvfrom(1000)  # 1000 es el tamaño máximo esperado, no importa mucho el número
    print("Recibido: {}".format(mensaje))
    if b"ENCENDER" in mensaje:
        encender_led()
    # No hay más, repetimos el bucle para esperar otro mensaje

En la raspberry ejecutas el script anterior con python 3. Se quedará a la espera de mensajes en el puerto 55555. Cuando reciba uno, lo imprimirá por pantalla (en bytes) y si contiene el texto "ENCENDER", llamará a la función encender_led(), que ya tendrías que programar tú.
Para enviarle un mensaje desde el PC puedes programar otro script en python que de forma similar cree un socket (no necesitas hacer bind() en este caso) y le envíe el comando con una línea como:
s.sendto(b"ENCENDER", ("192.168.1.103", 55555))

Donde "192.168.1.103" sería la IP de la raspberry y 55555 el puerto en que está escuchando el script anterior.
Pero ni siquiera necesitas escribir este script en el lado Ubuntu. Puedes usar la herramienta nc que permite enviar mensajes por TCP o UDP a cualquier máquina, por ejemplo escribiendo lo siguiente en una terminal:
$ echo "ENCENDER" | nc -u 192.168.1.103 55555

La opción -u es para que use UDP, y el resto serían la IP y puerto en que está esperando el mensaje la raspberry.


text:
Q: Java Play Framework using Find and JPQL to create an object list with duplicates from string list So I am new to Java and Play still get confused from time to time about quasi object oriented programming...
I need to convert a delimited string with duplicate values into an Object list, also with those duplicate values, in the same order as the string.
Example:
I have a form where a user submits of space delimited string. For example:
http://www.feedme.com?food=apple+orange+banana+apple+grape+apple
that goes to
public static List<Food> getFoodList(String foodString) {
    foodString = foodString.trim();
    List<String> foods = Arrays.asList(foodString.split("\\s+"));
    List<Food> foodList = Food.find("name IN (:foods)").bind("foods", foods).fetch();
    return foodList;
}

I print the loop of the String list to the screen and get the expected:
apple
orange
banana
apple
grape
apple
I print the Food.name value for each in the loop of the foodList and get:
Grape
Apple
Banana
Orange
This is clearly an issue with IN in the WHERE clause, as that's the expected behavior.
So, my current solution is to manually populate the List by looping through List and running the following on each String in the List foods
List<Food> foodList = new ArrayList<Food>(foods.size());
    for ( String name: foods ){
        Food food = Food.find("byName", name).first();
        foodList.add(food);
    }

This works how I want it but just doesn't seem very elegant or efficient. The duplicates ARE required, so I think that rules out IN. Does anyone have any better ideas? If the answer is no, would appreciate that too!
Many thanks.

A: There is no (at least not reasonable) way to construct such a JPQL query. If executing too many queries in loop bothers, you can fetch Food entities in one query and map them afterwards with something like (not compiled/tested, but just as an idea):
List<Food> matchFoodNamesToFoods(List<String> foodNames , List<Food> foodList ) {
    final ArrayList<Food> result = new ArrayList<Food>();
    for (String foodName: foodNames) {
        for (Food food: foodList) {
            if (food.getName().equals(foodName)) {
                result.add(food);
            }
            //maybe you want to add null here when no match
        }
    }
    return result;
}

Depending about size of of foodList and expected amount of duplicates (and maybe you find it more clear as well) you can also first create map with foodName/Food entries and query it in inner loop:
List<Food> matchFoodNamesToFoods(List<String> foodNames , List<Food> foodList ) {
    final ArrayList<Food> result = new ArrayList<Food>();
    final Map<String, Food> foodNameToFood = new HashMap<String, Food>();
    for (Food food: foodList) {
        for (String foodName: foodNames) {
            if (food.getName().equals(foodName)) {
                foodNameToFood.put(foodName, food);
            }
        }
    }
    for (String foodName: foodNames) {
        result.add(foodNameToFood.get(foodName));
    }
    return result;
}

Additionally you have to decide does missing Food for some name produce null entry to the result or is such a anomaly that you rather through exception in such a case.


text:
Q: Why is $(N,N' G)$ reaction not listed? If I go here,
http://www.nndc.bnl.gov/ensdf/#
go to the by Nuclide tab, check the "Reaction" box, and search for $\rm^{24}Mg$ in the Nuclide box; various reactions which produce $\rm^{24}Mg$ appear. Included is the $\rm^{24}Mg(N,N'G)$ reaction (Neutron is incident on $\rm^{24}Mg$ Nucleus, Neutron and Gamma are emitted).
If I do the same search but with $\rm^{26}Mg$ instead of $\rm^{24}Mg$, the $\rm^{26}Mg(N,N'G)$ reaction is not listed.
Basically for some Nuclides this reaction is listed and for others it is not. I'm assuming that the reason for this is that this reaction is not allowed/doesn't occur.

*

*My question is why this reaction is permitted for some isotopes but not others?

A: It's not (necessarily) a question of what's permitted so much as what's been measured, and published, and entered into the ENDF database.  The reference for the 24Mg paper is

*

*1984EL12,
Nucl.Instrum.Methods 228, 62 (1984),
D.Elenkov, D.Lefterov, G.Toumbev,
"Two-Target DSAM following the (n, n'γ) Reaction with Fast Reactor Neutrons"

and the abstract specifically mentions 24Mg; you'd have to find the paper to see whether they used an isotopically purified sample or whether they just selected against data from the 20% of magnesium with extra neutrons.
At the top of the search results is a link steering you to the XUNDL (experimental, un-evaluated data), which contains this reference for data on both (n,$\gamma$) and (n,n) on all stable magnesiums:

*

*2012MA14,
Phys.Rev. C 85, 044615 (2012),
C.Massimi, for the n_TOF Collaboration,
"Resonance neutron-capture cross sections of stable magnesium isotopes and their astrophysical implications"
NUCLEAR REACTIONS 24,25,26Mg(n, γ), E=1 eV-1 MeV; measured Eγ, E(n), time-of-flight, capture yields, σ(E), resonance parameters using n_TOF facility at CERN. 25,26,27Mg; deduced resonances, levels, J, π, neutron and gamma widths, Maxwellian averaged cross sections. R-matrix analysis. Comparison with KADoNiS database. Discussed impact on s-process abundances and neutron resonance contribution to 22Ne(α, n)25Mg reaction.
Happy hunting!


text:
Q: directshow what is the best component to use hi every one there please i need some info
i have created app using directshow &c++ for image processing
so the thing is that i need to create a sophisticated GUI  i have used win32 components which don't  fulfill my needs and my expectations plus difficult to tweak specailly with events
so i got to find a solution i thought about using jni and merge c++'s functionality with java's the swing components .
the other choice is to use the window form(.net) but if i'm right i need to use directshow.net (i don't know how to use it )

A: "but if i'm right i need to use directshow.net".
No, not really. You can create an activex control in C++ that wraps your current code and use that instead in .Net with Windows.Forms.

A: Qt is most often called the best C++ framework for building GUIs.
Windows Forms is quite nice. Don't be afraid of using DirectShow.Net, it looks very similar to C++ but easier. You can take a look at GraphEditPlus, it can generate DirectShow graph building code in both C++ and C# (for DirectShow.Net), so you can see how semantically the same code looks in two languages. Also, GraphEditPlus itself is an example of Windows Forms application working with DirectShow.


text:
Q: how to upload files with angular using CORS I'm using restangular 1.51 with angular 1.6. My html looks like this
<input type="file" name="file" />

and the angular code (based on the discussion here):
let directive = {
  ..
  link: (scope, element, attrs) => {
        let inputElement = angular.element(element[0].querySelector('input'));
        inputElement.bind('change', function () {
        var formData = new FormData();
        formData.append('file', inputElement[0].files[0]);

        API.all('stores/csv').withHttpConfig({transformRequest: angular.identity})             .customPOST(formData,'' , undefined,
          { 'Content-Type': undefined }).then((response) => {console.log(response);
          });
    });

laravel code:
public function upload(Request $request)
{

    $this->validate($request, [
        'file' => 'required',
        'type'  => 'in:csv,xls,xlsx',
        ]);

    $file = $request->file('file');
    var_dump($file);
    return response()->success(['file' => $file]);
}

thing is the $file here is appearing as an empty array in the laravel dump. The documentation is pretty bad on this. Ideas?
update
It works just fine using postman. this is the curl generated by postman:
postman curl:
curl -X POST \
  http://127.0.0.1:8000/api/stores/csv \
  -H 'Accept: application/x.toters.v1+json' \
  -H 'Authorization: Bearer ***' \
  -H 'Cache-Control: no-cache' \
  -H 'Content-Type: application/x-www-form-urlencoded' \
  -H 'Postman-Token: 4f9d2f3b-551b-aa47-4f65-98c7582f2919' \
  -H 'content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' \
  -F file=@/Users/Shared/Download/bac-383-store-update.csv

postman server logs
[2018-03-03 06:35:18] local.INFO: ----------------------------- [] []
[2018-03-03 06:35:18] local.INFO: POST api/stores/csv [] []
[2018-03-03 06:35:18] local.INFO: array (   'file' =>    Illuminate\Http\UploadedFile::__set_state(array(      'test' => false,      'originalName' => 'bac-383-store-update.csv',      'mimeType' => 'text/csv',      'size' => 62,      'error' => 0,   )), ) [] []
[2018-03-03 06:35:18] local.INFO: Status code: 200 [] []
[2018-03-03 06:35:18] local.INFO: User id: 104 [] []

this is the curl generated by restangular
restangular (two requests - using chrome) curl:
curl 'http://127.0.0.1:8000/api/stores/csv'
-X OPTIONS
-H 'Access-Control-Request-Method: POST'
-H 'Origin: http://localhost:3000'
-H 'Accept-Encoding: gzip, deflate, br'
-H 'Accept-Language: en-US,en;q=0.9'
-H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36'
-H 'Accept: */*'
-H 'Connection: keep-alive'
-H 'Access-Control-Request-Headers: authorization,content-type'
--compressed

curl 'http://127.0.0.1:8000/api/stores/csv'
-H 'Origin: http://localhost:3000'
-H 'Accept-Encoding: gzip, deflate, br'
-H 'Accept-Language: en-US,en;q=0.9'
-H 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjEwNCwiaXNzIjoiaHR0cDpcL1wvMTkyLjE2OC4wLjIzMjo4MDAwXC9hcGlcL3VzZXJzXC9sb2dpbiIsImlhdCI6MTUxOTk2OTAzNiwiZXhwIjoxNjE0NTc3MDM2LCJuYmYiOjE1MTk5NjkwMzYsImp0aSI6IndHV0UzRjhYQ3hRdDBGOWMifQ.XqySEIprbxtAU-RfhOgtFkScN1nUuuXEwMxCltfjqu8'
-H 'Content-Type: application/json'
-H 'Accept: application/x.toters.v1+json'
-H 'Referer: http://localhost:3000/?local/'
-H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36'
-H 'Connection: keep-alive'
--data-binary $'------WebKitFormBoundary9ApCHw2ykmLYK2IY\r\nContent-Disposition: form-data; name="file"; filename="bac-383-store-update.csv"\r\nContent-Type: text/csv\r\n\r\n\r\n------WebKitFormBoundary9ApCHw2ykmLYK2IY--\r\n' --compressed

restangular/chrome server logs
[2018-03-03 06:34:52] local.INFO: ----------------------------- [] []
[2018-03-03 06:34:52] local.INFO: OPTIONS api/stores/csv [] []
[2018-03-03 06:34:52] local.INFO: array ( ) [] []
[2018-03-03 06:34:52] local.INFO: Status code: 200 [] []
[2018-03-03 06:34:52] local.INFO: ----------------------------- [] []
[2018-03-03 06:34:52] local.INFO: POST api/stores/csv [] []
[2018-03-03 06:34:52] local.INFO: array ( ) [] []
[2018-03-03 06:34:52] local.INFO: Status code: 200 [] []
[2018-03-03 06:34:52] local.INFO: User id: 104 [] []

update 2:
after comparing the headers between both curls, i noticed that the content type was different:
postman curl snippet
-H 'Content-Type: application/x-www-form-urlencoded' \

restangular curl snippet
-H 'Content-Type: application/json'

this was shocking, considering that the rectangular people PROMISED that by using the above syntax, the content type should be application/x-www-form-urlencoded:

Restangular.all('users')
            .withHttpConfig({transformRequest: angular.identity})
            .customPOST(formData, undefined, undefined,
              { 'Content-Type': undefined }); This basically tells the request to use the Content-Type: multipart/form-data as the header.

so I wrote this:
    API.all('stores/csv').withHttpConfig({transformRequest: angular.identity})
    .customPOST(formData, undefined, undefined,
      { 'Content-Type': 'application/x-www-form-urlencoded' }).then((response) => {console.log(response);

this improved things a bit.. compare the two curls now:
postman
curl -X POST \
  http://127.0.0.1:8000/api/stores/csv \
  -H 'Accept: application/x.toters.v1+json' \
  -H 'Authorization: Bearer ***' \
  -H 'Cache-Control: no-cache' \
  -H 'Content-Type: application/x-www-form-urlencoded' \
  -H 'Postman-Token: 4f9d2f3b-551b-aa47-4f65-98c7582f2919' \
  -H 'content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' \
  -F file=@/Users/Shared/Download/bac-383-store-update.csv

angular
  curl 'http://127.0.0.1:8000/api/stores/csv'
  -H 'Origin: http://localhost:3000'
  -H 'Accept-Encoding: gzip, deflate, br'
  -H 'Accept-Language: en-US,en;q=0.9'
  -H 'Authorization: Bearer ***
  -H 'Content-Type: application/x-www-form-urlencoded'
  -H 'Accept: application/x.toters.v1+json'
  -H 'Referer: http://localhost:3000/?local/'
  -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36'
  -H 'Connection: keep-alive'
  --data $'------WebKitFormBoundaryd405EnTxpFJv2GDN\r\nContent-Disposition: form-data; name="file"; filename="bac-383-store-update.csv"\r\nContent-Type: text/csv\r\n\r\n\r\n------WebKitFormBoundaryd405EnTxpFJv2GDN\r\nContent-Disposition: form-data; name="name"\r\n\r\nfile\r\n------WebKitFormBoundaryd405EnTxpFJv2GDN--\r\n'
  --compressed

so i'm still not sending the -F option

A: I've not touched on restangular before, however in Laravel, when you want to get a file from the request you need to use the file method on the request object:
$file = $request->file('file');

That should give you an instance of Illuminate\Http\UploadedFile

A: I haven't delved into restangular a lot but on an HTTP level, I believe you want your Content-Type header to be multipart/form-data, not application/x-www-form-urlencoded.
If you're curious about the difference, check this answer out.
Since you're sending a file, multipart/form-data is what you want.

I know you see Postman do:
-H 'Content-Type: application/x-www-form-urlencoded'

But just a few lines under that, it does:
-H 'content-type: multipart/form-data; boundary...


text:
Q: What is "graph-directed iterated function"? Im translating an article about Rauzy fractal and I ran into this sentence:
The Rauzy fractal has remarkable properties. Firstly, it is selfsimilar,
more exactly, it is divided into three pieces,
corresponding to the three letters, which are the
solutions of a graph-directed iterated function system.

I do not know what is a graph-directed iterated function system. Can any one help me?
Iv searched the net but I didn't find anything useful.

A: From the wikipedia article, you have the substition rules $1\to12$, $2\to13$, $3\to1$.
We can write this in matrix form
$$
\begin{pmatrix}
1 & 1 & 1 \\
1 & 0 & 0 \\
0 & 1 & 0
\end{pmatrix}
$$
where the first column indicate what $1$ is mapped to, the second what $2$ is mapped to, and so on.
This makes a bit sense, the characteristic polynomial of this matrix is $t^3-t^2-t-1$,
which is also mentioned in the article.
Now, this matrix can also be seen as the incidence matrix of a directed graph, with edges $1\to 1, 1\to 2, 2\to 1, 2\to 3$ and so on, so perhaps this is what is meant by directed-graph iterated function system.


text:
Q: C# to mysql - inserting new row to table with foreign key I need to insert a new row in a mysql table using C#.
The table looks like this, and contains one foreign key column.
i use the follwing code to cinnect to the database and insert data.
    public virtual void addToDB()
    {
        try
        {
            //prepare for query
            var cmd = MySQL.readyQuery();

            //insert testdata to Vo2test
            cmd.CommandText = "INSERT INTO vo2test_tb(ClientID, Weight, Methods, TimeOfDay, Date, StartResistance, Endresistance, TheoreticalMaxPulse, FatPercent3point, FatPercent7point, VO2_max, FitnessRating, HRmax, RERmax, TestTime, Raw_test_data) VALUES((SELECT UserID from user_tb WHERE UserID = '@UserID'), '@Weight', '@Method', '@Timeofday', '@Date', '@Startresistance', '@Endresistance', '@Theoreticalmaxpulse', '@Fatprocent3p', '@Fatprocent7p', '@vo2max', '@fitnessrating', '@hrmax', '@rermax', '@testtime', '@rawtestdata')";

            cmd.Prepare();
            //insert parameters som skal ændres:
            cmd.Parameters.AddWithValue("@UserID", UserID);
            cmd.Parameters.AddWithValue("@Weight", Weight);
            cmd.Parameters.AddWithValue("@Method", Method);
            //coverts date to 0000-00-00
            string DateString = Convert.ToString(TestDate.Date.Date.Year) + "-" + Convert.ToString(TestDate.Date.Month) + "-" + Convert.ToString(TestDate.Date.Day);
            cmd.Parameters.AddWithValue("@Date", DateString);
            //converts time to 00:00:00.
            string TimeString = Convert.ToString(TimeOfDay.Hour) + ":" + Convert.ToString(TimeOfDay.Minute) + ":00";
            cmd.Parameters.AddWithValue("@Timeofday", TimeString);
            cmd.Parameters.AddWithValue("@Startresisstance", StartResistance);
            cmd.Parameters.AddWithValue("@Endressistance", EndResistance);
            cmd.Parameters.AddWithValue("@TheoreticalMaxPulse", TheoreticMaxPulse);
            cmd.Parameters.AddWithValue("@FatPercent3point", FatPercent3Point);
            cmd.Parameters.AddWithValue("@FatPercent7point", FatPercent7Point);
            cmd.Parameters.AddWithValue("@VO2_max", Vo2Max);
            cmd.Parameters.AddWithValue("@FitnessRating", FitnessRating);
            cmd.Parameters.AddWithValue("@HRmax", HRmax);
            cmd.Parameters.AddWithValue("@RERmax", RERmax);
            cmd.Parameters.AddWithValue("@TestTime", TimeOfDay);
            cmd.Parameters.AddWithValue("@Raw_test_data", RawTestData);

            cmd.ExecuteNonQuery();

            //close connection
            cmd.Connection.Close();
        }
        catch (MySqlException ex)
        {
            Console.WriteLine(ex.Message);
        }
    }

when i run it, i am told that ClientID can't be null but if i just run the sql query in Adminer it works fine.

A: The sub select in your insert query doesnt make sense. Why are you doing a sub select to insert a value you already have.
SELECT UserID from user_tb WHERE UserID = '@UserID'

Just insert @UserID directly.
Also you have wrapped all your @ parameters in single quotes in the query string. You do not need this. Parameterization deals with the quotes for you in the background. Remove all single quotes so that it just reads:
cmd.CommandText = "INSERT INTO vo2test_tb(ClientID, Weight, Methods, TimeOfDay, Date,
StartResistance, Endresistance, TheoreticalMaxPulse, FatPercent3point, FatPercent7point,
VO2_max, FitnessRating, HRmax, RERmax, TestTime, Raw_test_data)

VALUES((SELECT ClientID from user_tb WHERE UserID = @UserID), @Weight, @Method, @Timeofday,
@Date, @Startresistance, @Endresistance, @Theoreticalmaxpulse, @Fatprocent3p, @Fatprocent7p,
@vo2max, @fitnessrating, @hrmax, @rermax, @testtime, @rawtestdata)";


text:
Q: How to receive UDP Multicast and Unicast with Network Framework of iOS I've been developing Smart House apps that require UDP communication of both Unicast and Multicast on iOS with Swift using CocoaAsyncSocket.
I'd like to use Network Framework instead of CocoaAsyncSocket.
I made a following trial program of receiving UDP at 3610 port with both Unicast and Multicast at "224.0.23.0".
With this program, I'm having a problem to receive both Multicast and Unicast.
This program can handle receiving Multicast, but not Unicast.
When I comment out "receiveMulticast()" in the init(), this program can handle receiving Unicast.
I need to handle receving both Multicast and Unicast at 3610 port.
Is there any advice?
=======================================
import Foundation
import Network

class Controller: ObservableObject {
  @Published var rxContents = String()
  @Published var rxFrom = String()

  init() {
    receiveMulticast()
    receiveUnicast()
  }

  func receiveUnicast() {
    guard let listener = try? NWListener(using: .udp, on: 3610)
    else { fatalError() }
    listener.newConnectionHandler = { (newConnection) in
      print("connection OK")
      newConnection.start(queue: .main)
      self.receive(on: newConnection)
    }
    listener.stateUpdateHandler = { (newState) in
      print("listener entered state \(String(describing: newState))")
    }
    listener.start(queue: .main)
  }

  func receiveMulticast() {
    guard let multicast = try? NWMulticastGroup(for: [ .hostPort(host: "224.0.23.0", port: 3610) ], disableUnicast: false)
    else { fatalError() }
    let group = NWConnectionGroup(with: multicast, using: .udp)
    group.setReceiveHandler(maximumMessageSize: 16384, rejectOversizedMessages: true) { (message, content, isComplete) in
      print("Received message from \(String(describing: message.remoteEndpoint))")
      if let content = content, let message = String(data: content, encoding: .utf8) {
        print("Received Message: \(message)")
      }
    }
    group.stateUpdateHandler = { (newState) in
      print("Group entered state \(String(describing: newState))")
    }
    group.start(queue: .main)
  }

  private func receive(on connection: NWConnection) {
    connection.receiveMessage { (data: Data?, contentContext: NWConnection.ContentContext?, aBool: Bool, error: NWError?) in
      self.rxFrom = String(describing: connection.endpoint)
      print("Received message from \(self.rxFrom))")
      print(data ?? "data is null")
      if let data = data{
        self.rxContents = String(format: "%@", data as CVarArg)
        print("Received Message(unicast): \(self.rxContents)")
      }
      if let error = error {
        print(error)
      } else {
        self.receive(on: connection)
      }
    }
  }
}


text:
Q: how to make array or arrays that is result from db to be indexed by ID from the table without looping? example:
Array
(
 [0] => Array
    (
        ['user_id'] => 4567
        ['user_name'] => 'John Doe'
        ['city'] => 'NY'
        // and so on
    )

 [1] => Array
    (
        ['user_id'] => 3732
        ['user_name'] => 'Janet Smith'
        ['city'] => 'LA'
        // and so on
    )
 // and here many more rows

but I need this:
Array
(
 [4567] => Array
    (
        ['user_id'] => 4567
        ['user_name'] => 'John Doe'
        ['city'] => 'NY'
        // and so on
    )

 [3732] => Array
    (
        ['user_id'] => 3732
        ['user_name'] => 'Janet Smith'
        ['city'] => 'LA'
        // and so on
    )
 // and here many more rows

So I can acces given row by it's id.
The only one way I know is to loop this whole array that can be huge:
 foreach($array_from_db as $row) {
   $idexed_array_from_db[$row['user_id']] = $row;
 }

Are there other ways to achieve this result ?

A: I don't think PDO can do this directly. There are other wrappers which can, such as ADODb with GetAssoc
  $array=$db->GetAssoc("select user_id,user_name,city from user");

However, any wrapper is simply retrieving the result and building the array just as you describe in your question. The only difference is that your suggestion fetches the entire resultset into an array first, then generates your associative array from that.
If you're using PDO, your then a more memory efficient approach would be to read the results row-by-row and build the array that way.


text:
Q: How to get value from function with typescript (ionic2) I´m trying to get a value from a function. This is what I´m trying to do:
In file favorite.ts

getUserFavsCount(userId: string){
    let count = 0;
    let favs = this.af.list(`/favorites/${userId}`).subscribe(data =>{
      count = data.length;
    });
    console.log(count) // getting the value. here it shows correct
    return count;

  }

Now, in my profile.ts I´m trying to get this value:

countUserFav() {
    this.userProvider.currentUser.first().subscribe((currentUser: User) => {
      console.log("---->",this.favoriteProvider.getUserFavsCount(currentUser.$key)); // here I get 0 value always :(
      this.myFavs = this.favoriteProvider.getUserFavsCount(currentUser.$key)

    });
  }

What Am I doing wrong?

A: As TheFallen has commented you'll need to return a promise. Always use promises or you'll have concurrence problems. Try this
getUserFavsCount = (userId: string): Promise<number> => {
  // SINCE YOU RETURN A LENGTH, THEN THE PROMISE SHOULD RETURN A NUMBER
  // THERE'S NO NEED TO DECLARE A COUNT VARIABLE SINCE YOU'LL NOT USE IT
  return new Promise<number>(resolve =>{
    let favs = this.af.list(`/favorites/${userId}`).subscribe(data =>{
      resolve(data.length);
    });
  });
}

And then get your data
countUserFav() {
  this.userProvider.currentUser.first().subscribe((currentUser: User) => {
    this.favoriteProvider.getUserFavsCount(currentUser.$key).then(res =>{
      this.myFavs = res;
    });
  });
}

Hope this helps :D


text:
Q: Laravel PHP: Creating default object from empty value error I'm using a controller to call up a form defined in one of my views.  Within the controller, I have a simple 'create()' method that I just want to use to call up a form while using the 'Video' model I've defined.  The problem is when I try to call this function, I keep getting a 'Creating default object from empty value' error.
Controller(app\VideosController.php):
 <?php

use Acme\repositories\VideoRepository;

use Models\Video;

use Models\Validators as Validators;

class VideosController extends BaseController {

/**
 * The video model
 *
 * @var \Models\Video
 **/
protected $video;

/*  The value defined from my repository
*/

protected $videoRepo;

/**
 * Instantiate the controller
 *
 * @param Models\Video $video
 * @return void
 **/

   public function __construct(VideoRepository $videoRepo)
   {
     $this->videoRepo = $videoRepo;
     /* Old code below
     $this->video = \App::make('Repositories\VideoRepository');
     */
   }

/* Create a new video by passing in a sub view
Of the form for creating a new video */

   public function create()
   {
    $data = array('type' => 'video');
    $this->layout->content = \View::make('forms.new-video', $data);
   }

}

Model(app/models/video.php):
<?php

class Video extends Eloquent {

    /**
     * The table used by this model
     *
     * @var string
     **/
    protected $table = 'videos';

    /**
     * The primary key
     *
     * @var string
     **/
    protected $primaryKey = 'video_id';

    /**
     * The fields that are guarded cannot be mass assigned
     *
     * @var array
     **/
    protected $guarded = array();

    /**
    *  Enabling soft deleting
    *
    *  @var boolean
    **/
     protected $softDelete = true;

    }

The view for my form is located at 'app\views\forms\new-video.blade.php'.
Am I not defining my 'create()' method properly or is a matter of not placing files in their correct location?

A: I believe you are missing the declaration of the $layout property in your controller, so it has no idea what view to use as the template:
/**
 * The layout that should be used for responses.
 */
protected $layout = 'layouts.master';

See http://laravel.com/docs/4.2/templates#controller-layouts.