text:
Q: Core Data Crash that redirects to the app delegate persistentStoreCoordinator mathod Hi everyone I am trying to implement core data to a table view from my app, to avoid unwanted internet traffic the problem is that I am new to core data and also at the beginning of the implementation.
So here you have my core data Entity and how it looks:

I am using only one Entity, with the model that you can see in the photo and also with NSmanagedObjectSubclass.
What I am doing is:
1. I download an XML from the internet and I save in NSUserDefaults for better persistence, so that if the app is launched for the first time I check if the the NSUserDefaults exists than I download it again in the viewDiaAppear, and if it is for the first time I download the data in viewDidLoad.
2. So creating the data for the first Time and retrieving it in the table view works fine
3. But when the app launches for the second, It does a series of conditions at witch point it crushes during one of them witch I don't know for sure, so I added CrashLitiscs and these is what I am getting:

but at the line specified I have no array, not only at that line but nothing near that line above or beneath.
These is the code at the line from Crashlytics
//check ID
if ([NSString stringWithFormat:@"%d", count] != suggestedEntityForGroup.groupName) {
    //replace with new data
    suggestedEntityForGroup.groupID = [NSString stringWithFormat:@"%d",count];
    NSError *managedObjError = nil;
    if (![[self appDelegate].managedObjectContext save:&managedObjError]) {
        NSLog(@"Next error ocured:%@ while updating group id at position:%d", managedObjError, count);
    }
}

And here is the entire code that handles core data DB after the XML is retrieved:
and here is the console log after the crash:
CoreData: error: -addPersistentStoreWithType:SQLite configuration:(null) URL:file:///Users/laurentiu/Library/Developer/CoreSimulator/Devices/1F02B530-AB90-4B1B-BBAA-08B3B9C14ECA/data/Containers/Data/Application/668593BE-16B2-419E-ACB9-95FB38A8A90B/Documents/ChannerApp.sqlite options:{
        NSInferMappingModelAutomaticallyOption = 1;
        NSMigratePersistentStoresAutomaticallyOption = 1;
    } ... returned error Error Domain=NSCocoaErrorDomain Code=134130 "The operation couldn't be completed. (Cocoa error 134130.)" UserInfo=0x7fa4d600ce70 {URL=file:///Users/laurentiu/Library/Developer/CoreSimulator/Devices/1F02B530-AB90-4B1B-BBAA-08B3B9C14ECA/data/Containers/Data/Application/668593BE-16B2-419E-ACB9-95FB38A8A90B/Documents/ChannerApp.sqlite, metadata={
        NSPersistenceFrameworkVersion = 519;
        NSStoreModelVersionHashes =     {
            Asd = <6acf157c fdf3a06b 00e10f78 074562df 987e2334 be30294e ae73e5c1 cdc1f9b1>;
            SuggestedChannelsEntity = ;
        };
        NSStoreModelVersionHashesVersion = 3;
        NSStoreModelVersionIdentifiers =     (
            ""
        );
        NSStoreType = SQLite;
        NSStoreUUID = "D73CCCB1-F3AE-4153-83AE-2D1B6D91E3D9";
        "_NSAutoVacuumLevel" = 2;
    }, reason=Can't find model for source store} with userInfo dictionary {
        URL = "file:///Users/laurentiu/Library/Developer/CoreSimulator/Devices/1F02B530-AB90-4B1B-BBAA-08B3B9C14ECA/data/Containers/Data/Application/668593BE-16B2-419E-ACB9-95FB38A8A90B/Documents/ChannerApp.sqlite";
        metadata =     {
            NSPersistenceFrameworkVersion = 519;
            NSStoreModelVersionHashes =         {
                Asd = <6acf157c fdf3a06b 00e10f78 074562df 987e2334 be30294e ae73e5c1 cdc1f9b1>;
                SuggestedChannelsEntity = ;
            };
            NSStoreModelVersionHashesVersion = 3;
            NSStoreModelVersionIdentifiers =         (
                ""
            );
            NSStoreType = SQLite;
            NSStoreUUID = "D73CCCB1-F3AE-4153-83AE-2D1B6D91E3D9";
            "_NSAutoVacuumLevel" = 2;
        };
        reason = "Can't find model for source store";
    }
    2015-04-24 17:45:34.467 ChannerApp[11021:412450] CoreData: annotation: NSPersistentStoreCoordinator's current model hashes are {
        SuggestedChannelsEntity = ;
    }
    2015-04-24 17:45:34.468 ChannerApp[11021:412450] Unresolved error Error Domain=YOUR_ERROR_DOMAIN Code=9999 "Failed to initialize the application's saved data" UserInfo=0x7fa4d3c9e0c0 {NSLocalizedFailureReason=There was an error creating or loading the application's saved data., NSLocalizedDescription=Failed to initialize the application's saved data, NSUnderlyingError=0x7fa4d600e2c0 "The operation couldn't be completed. (Cocoa error 134130.)"}, {
        NSLocalizedDescription = "Failed to initialize the application's saved data";
        NSLocalizedFailureReason = "There was an error creating or loading the application's saved data.";
        NSUnderlyingError = "Error Domain=NSCocoaErrorDomain Code=134130 \"The operation couldn\U2019t be completed. (Cocoa error 134130.)\" UserInfo=0x7fa4d600ce70 {URL=file:///Users/laurentiu/Library/Developer/CoreSimulator/Devices/1F02B530-AB90-4B1B-BBAA-08B3B9C14ECA/data/Containers/Data/Application/668593BE-16B2-419E-ACB9-95FB38A8A90B/Documents/ChannerApp.sqlite, metadata={\n    NSPersistenceFrameworkVersion = 519;\n    NSStoreModelVersionHashes =     {\n        Asd = <6acf157c fdf3a06b 00e10f78 074562df 987e2334 be30294e ae73e5c1 cdc1f9b1>;\n        SuggestedChannelsEntity = ;\n    };\n    NSStoreModelVersionHashesVersion = 3;\n    NSStoreModelVersionIdentifiers =     (\n        \"\"\n    );\n    NSStoreType = SQLite;\n    NSStoreUUID = \"D73CCCB1-F3AE-4153-83AE-2D1B6D91E3D9\";\n    \"_NSAutoVacuumLevel\" = 2;\n}, reason=Can't find model for source store}";
    }


text:
Q: PHP: fopen - Permission denied - chmod 777 already done I am setting up a new CentOS 6.6 machine running PHP 5.5 and migrating our site to the server but am getting the error in my httpd error log:
PHP Warning:  fopen(/ssd-media/www/app/storage/logs/laravel.log): failed to open stream: Permission denied in /ssd-media/www/index.php on line

I have already checked and the httpd process is being run as the user/group "apache" and have done the chmod -R 775 storage and verified that the file has the right user / group configured and permissions and then ran the following code:
<?php
$myfile = fopen("/ssd-media/www/app/storage/logs/laravel.log", "w") or die("Unable to open file!");
$txt = "test\n";
fwrite($myfile, $txt);
fclose($myfile);
?>

I have moved the DocumentRoot to /ssd-media/www which is not where CentOS is installed, it is an SSD RAID that is only for the apache / mysql files. Other than that it is a fairly simple configuration for which I followed this guide:
https://webtatic.com/packages/php55/
What other reasons would I get a permissions denied on that file? I tried 777 permissions as well to no avail.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Change the order of columns I am working on a large dataframe with >40 columns.  I want to be able to move a column, without having to specify all the column names.  For example:
a<-c(1:5)
b<-c(4,3,2,1,1)
Percent<-c(40,30,20,10,10)
Labels<-c("Cat","Dog","Rabbit","Rat","Mouse")
df1<-data.frame(a,b,Percent,Labels)

How would I move the column 'Lables' to before column 'a' WITHOUT having to write all the other column names (i.e. can I just specify a column to come before/after another column?).
Thanks.

A: Something quick and dirty would be (i.e. no sanity checking etc. and assuming only a single colname is supplied):
moveToFirstCol <- function(df, colname) {
    cnams <- colnames(df)
    want <- which(colname == cnams)
    df[, c(cnams[want], cnams[-want])]
}

which gives:
> moveToFirstCol(df1, "Labels")
  Labels a b Percent
1    Cat 1 4      40
2    Dog 2 3      30
3 Rabbit 3 2      20
4    Rat 4 1      10
5  Mouse 5 1      10

That should suggest a way to handle this sort of thing if you need additional flexibility.

A: Solution with additional flexibility:
move_variable <- function(x,where,data,after=FALSE){
 vnames <- names(data)
 x_idx <- match(x, vnames)
 where_idx <- match(where, vnames)
 idx <- seq(length(vnames))
 idx[x_idx] <- where_idx
 idx1 <- rep(0L, length(vnames))
 if(after) idx1[x_idx] <- 1 else idx1[where_idx] <- 1
 return(data[order(idx, idx1)])
}


text:
Q: ImageResizer generate wrong width for the image I let users upload a banner with a minimum width of 400px. This image will then get a wide of 1110px.
I try to upload images with the following sizes: 960x390, 410x410, 784x250.
When i upload 784x250, the image get the same size 784x250 not the width, 1110px.
I use this:
        int Height;
        using (var Bmp = new Bitmap(str))
        {
            if (Bmp.Width < 400)
            {
                throw;
            }
            if (Bmp.Height < 150)
            {
                throw;
            }
            Height = Bmp.Height;
        }

        if (Height > 300)
        {
            Height = 300;
        }

        str.Position = 0;
        var ImageData = str.StreamToByteArray();

        var Settings = "width=1110;height="+ Height + ";format=jpg;mode=crop;"

        var Setting = new ResizeSettings(Settings);
        using (var Out = new MemoryStream())
        {
            using (var In = new MemoryStream(ImageData))
            {
                In.Seek(0, SeekOrigin.Begin);

                var I = new ImageJob(In, Out, Setting)
                {
                    CreateParentDirectory = false
                };
                I.Build();
            }

            Out.Position = 0;

            // Upload to blob
        }

(str contains a stream with the image)
I want the image to be 1110px wide and max 300px high.
Whats wrong?

A: ImageResizer does not upscale images unless you specifically ask for it via scale=both or scale=canvas. Upscaling is typically undesired.
Also, you can pass the stream directly to ImageJob and simplify your code significantly.
str.Seek(0, SeekOrigin.Begin);
var Out = new MemoryStream(8096);
new ImageJob(str, Out, new Instructions("width=1110;height="+ Height + ";format=jpg;mode=crop;scale=both")).Build();
Out.Seek(0, SeekOrigin.Begin);

A: The other sizes you tested each have a Bmp.Height > 300 which means the image requires to be cropped.
However when using an image size 784x250, the image doesn't require to be cropped. So you'll never re-size the image.
Assuming you wish to keep the image proportionally correct, you should first re-size the image to match the wanted width and afterwards crop the exceeding height if necessary.
var image = new Bitmap(str);

var ratio = (double)1110 / image.Width;

var newWidth = (int)(image.Width * ratio);
var newHeight = (int)(image.Height * ratio);

var newImage = new Bitmap(newWidth, newHeight);

Graphics.FromImage(newImage).DrawImage(image, 0, 0, newWidth, newHeight);
var bmp = new Bitmap(newImage);

if(bmp.Height > 300){
//Resize again using crop, like you did in your original code.
}


text:
Q: C# Task Independent Main Thread I Have A REST API and inside its POST action , I need to call method and don't wait for it and return result.
I need a methodology to guarantee that this method will be called and fully executed in background.
I Tried executing this method in Task but it failed sometimes and sometimes succeeded.
public string Post([FromBody]Accounts accounts)
{
    Task.Run(() =>
    {
         ExecuteApi(); //I don't want to wait this method execution
    });
    return "Success";
}
public void ExecuteApi(string request)
{
       string formattedResponse = "";
       string apiURL = ConfigurationManager.AppSettings["URL"];
       using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri(apiURL);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new
            MediaTypeWithQualityHeaderValue("application/xml"));
            string url = apiURL;
             StringContent contentA = new StringContent(request,
            Encoding.UTF8, "application/xml");

                var apiResponse = client.PostAsync(url, contentA).Result;
        }
}

A: Task.Run(..) creates new Task instance which is doing some job. But you should be aware, that when your API send to your user 200 OK (when you return "Success" and exit you Post(..) action) - your controller is disposed and this Task become "garbadge-collectable". So, sometimes your GC is fast enough to kill your Task before it executes, sometimes not.
You may think that storing your Task in a private field might be a good solution for this issue (spoiler: it's not)
private Task _aTask;

public string Post([FromBody]Accounts accounts)
{
    _aTask = Task.Run(() => ExecuteApi()); // this will not help
    return "Success";
}

This will not work as your controller instance is GC after your API call.

So now for the solutions:
1. The best solution: if you need it - await it.
public async Task<string> Post([FromBody]Accounts accounts)
{
    await ExecuteApiAsync();
    return "Success";
}

public async Task ExecuteApiAsync(string mobileNumber)
{
    // ...
    // WARNING! Bad use of HttpClient class here.
    // You should NOT create too many HttpClient instances eventhough you dispose them right.
    // Read this: https://softwareengineering.stackexchange.com/questions/330364/should-we-create-a-new-single-instance-of-httpclient-for-all-requests
    // and this: https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/
    using (var client = new HttpClient())
    {
        // ...
        await client.GetAsync(url);
    }
}

2. Good solution: use QueueBackgroundWorkItem or any other 3rd party task schedulers. For example Hangfire or any other.
3. Sort-of-good solution: write your own task scheduler.


text:
Q: Failed to locate the code coverage command line tool , MSBuild with SonarQube Getting the following error's once build is triggered from the build definition.
3:46:16 AM  Failed to locate the code coverage command line tool Post-processing failed. Exit code: 1
Exception Message: TF270015: 'MSBuild.SonarQube.Runner.exe' returned an unexpected exit code. Expected '0'; actual '1'. See the build logs for more details. (type UnexpectedExitCodeException)
Exception Stack Trace:
   at System.Activities.Statements.Throw.Execute(CodeActivityContext context)
   at System.Activities.CodeActivity.InternalExecute(ActivityInstance instance, ActivityExecutor executor, BookmarkManager bookmarkManager)
   at System.Activities.Runtime.ActivityExecutor.ExecuteActivityWorkItem.ExecuteBody(ActivityExecutor executor, BookmarkManager bookmarkManager, Location resultLocation)

I am using SonarQube 5.3, installed in the build server. I have .net framework installed in build server not the visual studio .
BuildDefinition where I am referencing SonarQube.
Please help me here !!!!

A: The code coverage tools are installed with Visual Studio not the .Net Framework, so if you want code coverage you'll need to install VS on the build agent.
Depending on the version of Visual Studio you are using, you may not need an additional license for build agent. See the discussion Is a separate Visual Studio license required for a build machine? get more detail.


text:
Q: Are there any pure client-side AJAX/javascript Spellchecker plugins? Spellify works like a charm, but it entails 2 hops - once to your own server, which then creates a web request and calls out the google API. Expensive - considering it occurs every time any user types a space in one of one's forms.
I am yet to find a pure client-side version that manges to create the 3rd-party request client side (presumably because it is a post and you have x-origin issues) - are there any JSONP / GET solutions out there?

A: It's worth noting I've since stumbled upon the new HTML5 spellcheck attribute.
Our call is that for us the spellcheck is a nice to have - since the latest browsers are all supporting this attribute, overtime more and more of our users will get this feature.
I'd still like to hear about a JSONP solution, as suggested replacements a la spellify would be even better.


text:
Q: mvc JQuery JSON.parse() to fill dropdown I want to fill dropdown from the Javascript object returned from JSON.parse(). Tried but not successfull. Please help

A: You can do this by using following code,
HTML is,
<input type="button" id="btnclick" value="add" />

<select id="drpTemp">
</select>

JQuery Code is,

It will Fill Dropdownlist on Button Click.


text:
Q: about C++ pointer I have just started to practice c++ and I am stuck at one point.
I have a Node class and the class has a constructor like this:
class Node
{
    public:
          Node(std::string,Node *,int,int,int,int);
    private:
          std::string state;
          Node* parent_node;
          int total_cost;
          int path_cost;
          int heuristic_cost;
          int depth;
}

Node::Node(std::string state,Node *parent_node,int path_cost,int heuristic_cost,int total_cost,int depth)
{
    this->state=state;
    this->parent_node=parent_node;
    this->path_cost=path_cost;
    this->heuristic_cost=heuristic_cost;
    this->total_cost=total_cost;
    this->depth=depth;
}

Everything works ok so far, but I can not create a Node object with a NULL parent_node.
I have tried this:
Node *n = new Node("state name",NULL,0,15,20,1);

I have also tried creating a new object and assigning it as parent_node, but no success either.
Node *temp = new Node();
Node *n = new Node("state name",temp,0,15,20,1);

I am doing something wrong with the pointer but I don't know what I am missing. I get a compile error which says no matching function call.
Thanks in advance

A: Is your constructor public?
class Node
{
public:
    Node(std::string,Node *,int,int,int,int);
private:
    std::string state;
    Node* parent_node;
    int total_cost;
    int path_cost;
    int heuristic_cost;
    int depth;
};

Also, don't forget the semicolon after Node declaration, this is not Java ;)

A: I think it's normal to specify 0 for a null pointer value, instead of NULL (NULL is a macro used for C which, depending on how the macro is defined, might not work well with C++).
Also, I don't like to see std::string as a parameter type. I'd prefer to see either const char*, or const std::string&.
Also Node* node = new Node(); will produce that compiler error, because when you declare a non-default constructor then you hide the default constructor (where by 'default constructor' I mean the constructor which takes no parameters). If you want to support new Node(); then you need to explicitly declare the default constructor (and, define how it's implemented.)

A: This works fine for me on GCC-4 on Mac OS X, after correcting the typos and implementing a Node::Node() constructor. It'd probably be helpful if you edited your question to include all the code to your test program, as well as the actual error messages you're getting when you compile.

A: The following compiles fine for me:
// Added this.
#include <string>

class Node
{    public:
          Node(std::string,Node *,int,int,int,int);
    private:
          std::string state;
          Node* parent_node;
          int total_cost;
          int path_cost;
          int heuristic_cost;
          int depth;
}; // Added semicolon here

Node::Node(std::string state,Node *parent_node,
           int path_cost,int heuristic_cost,int total_cost,int depth)
{
        this->state=state;
        this->parent_node=parent_node;
        this->path_cost=path_cost;
        this->heuristic_cost=heuristic_cost;
        this->total_cost=total_cost;
        this->depth=depth;
}

// Put code inside main.
int main()
{
    Node *n = new Node("state name",NULL,0,15,20,1);
}


text:
Q: SpagoBI 5.2 doen't shows the saved datasets. What should I do? I have an error in SpagoBI 5.2 in which I unfortunately could not find a solution on the Internet.
I use my own Tomcat version 8.0.37 in which I want to deploy the WebApps (All-in-Oneis not an alternative for me). I proceeded as follows:

*

*declared environment variables.

*created the schema on the Oracle database. (ORA-create.sql and-create-quartz-schema.sql)

*deployed the WebApp "SpagoBI", so the folder is created with the necessary configuration files.

*edited the server.xml to connect to Oracle. (added environment variables and the metadata source)

*edited the hibernate.cfg.xml and jbpm.hibernate.cfg.xml to address the correct driver.

*added more resources in the lib-folder

*

*casclient.jar

*commons-logging-1.1.1.jar

*commons-logging-api-1.1.jar

*concurrent.jar

*foo-commonj.jar

*geronimo-commonj_1.1_spec-1.0.jar

*iijdbc.jar

*ojdbc7.jar

SpagoBI I could reach without problems.
Now the problem: When I create a dataset that is saved successfully. but I want it to edit or delete, the dataset does not appear in the environment. But in the database it is available. Can somebody help me?
saved Dataset
reloaded

A: There can be 2 cases.
CASE 1:
You try to save it twice and check whether the username & save time comes on bottom right corner window of the same screen whose image you have posted.
CASE 2:
You need to create 1 datasource where meta-data of SpagoBI is stored.
You should make it write-default true.
After that it will be visible.
But you need to re-install the spago as on the current set-up it wont work.


text:
Q: Getting a program only to run with certain dlls in the directory When, for instance, I create a program and compile it with MinGW if I delete the environment variable I need to put the dll in the directory for it to work
ie. libgcc_s_dw2-1.dll
without it the program will not even start.
When developing with QT I noticed I needed another dll in the directory, it was QtCored4.dll, I was wondering how the program knows that the dll is missing?
Also is there anyway to add something like this to a program,
like a define statement or something?
I need an answer that can work with C++ :)

A: That is taken care by the operating system -- since your program uses functions from the DLL, it is automatically loaded when your program starts, and if the DLL is missing, you will get an error. You can read more about this process on MSDN: Load-Time Dynamic Linking.

A:
when developing with QT I noticed I needed another dll in the directory, it was QtCored4.dll, I was wondering how the program knows that the dll is missing

You can also try to load the DLL yourself at runtime, and handle failure gracefully. See LoadLibrary and GetProcAddress.


text:
Q: A general "inclusion-exclusion principle" / Formulas like $\inf(a,b)\sup(a,b)=ab$ Let me list a few formulas which should be well-known:

*

*(GCD-LCM product formula) For positive integers $n,m$,
$$\operatorname{gcd}(n,m)\operatorname{lcm}(n,m)=nm.$$

*(Inclusion-exclusion principle) For sets $A,B$,
$$\#(A\cap B)+\#(A\cup B)=\#A+\#B$$

*("Linear inclusion-exclusion principle") For subspaces $W_1,W_2$ of a vector space $V$,
$$\dim(W_1\cap W_2)+\dim(W_1+W_2)=\dim(W_1)+\dim(W_2)$$
All of these formulas have the same form: We have:

*

*A lattice $L$,

*A commutative ordered monoid $(M,\star,\leq)$,

*an order-preserving "size" function $S\colon L\to M$ such that
$$S(a\land b)\star S(a\lor b)=S(a)\star S(b)\qquad\text{for all }a,b\in L.\tag{$\star$}$$
In the first example, $L=\mathbb{Z}_{>0}$ with the divisibility ordering ($n\leq m$ iff $n$  divides $m$); $M=\mathbb{Z}_{>0}$ with product and the usual order (or the divisibility ordering, doesn't matter); $S$ is the identity function of $\mathbb{Z}_{>0}$.
In the second example, $L$ is the power set of some universe, ordered by inclusion; $M$ is $\mathbb{Z}_{>0}$ with sum and the usual ordering; $S$ is the function which outputs the cardinality of a set.
In the third example, $L$ is the lattice of subspaces of $V$; $M$ is as in the second example; $S$ is the function mapping each subspace to its dimension.
Here are a few other examples of the same nature, which are more-or-less trivial but interesting nevertheless:

*If $B_1$, $B_2$ are Boolean algebras is a Boolean Algebra and $S\colon B_1\to B_2$ is a homomorphism, then for all $a,b\in B_1$,
$$S(a\land b)\lor S(a\lor b)=S(a)\lor S(b).$$

*For bounded subsets $A,B$ of a complete lattice $L$,
$$\sup(A\cap B)\lor\sup(A\cup B)=\sup(A)\lor\sup(B)$$

*For real functions $f,g$ on $[0,1]$,
$$\int_0^1\min(f,g)+\int_0^1\max(f,g)=\int_0^1f+\int_0^1g.$$

*For subsets $A,B$ of a vector space $V$,
$$\operatorname{span}(A\cap B)+\operatorname{span}(A\cup B)=\operatorname{span}(A)+\operatorname{span}(B).$$
(Examples 4, 5 and 7 are more trivial, as the commutative ordered monoid under consideration is simply a lattice with the join operation and the "size" function preserves joins)

Question: Is there a name for the kind of structure described as in $(\star)$? These seem to be reocurring in different areas concerning all kinds of interesting structures.

A: Would you be looking for the names valuation and/or modular function? Some references:
Garret Birkhoff, Lattice Theory, revised edition (1948), p. 74:

In general, by a valuation on a lattice $L$ is meant a real-valued
function $v(x)$ defined on $L$ which satisfies
$v(x)+v(y) = v(x \wedge y) + v(x \vee y)$.
A valuation is called isotone if and only if
$x \ge y$ implies $v(x) \ge v(y)$;
positive if and only if $x>y$ implies $v(x)>v(y)$.

Geissinger, Ladnor, Valuations on distributive lattices. I, II, III, Arch. Math. 24, 230-239 (1973); 24, 337-345 (1973); 24, 475-481 (1973). ZBL0268.06008.

A function $f$ from a lattice $L$ into an abelian group is modular
if $f(a \vee b)+f(a \wedge b)=f(a)+f(b)$ for all $a,b \in L$.
Following Rota [19], we call any such modular function a valuation.
(Birkhoff [2] reserves the term valuation for real-valued modular functions.)


text:
Q: (Python) Capture any interactions with an object I'm looking for a way to find out when a str object has been accessed. I want to know when its value has been used by other variables or functions in my code, such as when it was used by int, float, len, print or when it was used for additions result = my_var + 'something'.
My initial approach was to create a Decorator class, extending str and use decorator function to tell me when any of its methods have been accessed. While this approach works fine for print and my_var + 'something', it doesn't notify me when I use my object in  int builtin function for example.
My approach:
def delegate_all():
    def decorate(cls):
        for attr in str.__dict__:
            if callable(getattr(str, attr)) and attr not in ['__init__', '__new__']:
                setattr(cls, attr,
                    lambda self, *args, **kwargs:
                        do_action(self, cls, attr, '_string_value', attr, *args, **kwargs))

        return cls
    return decorate

The do_action function is where I dynamically set an accessed field in my object and then forward the method call to my actual string instance in my object.
And then create a class AccessWrapper:
@delegate_all()
class AccessWrapper(str):
    def __init__(self, value):
        self._string_value = value
        self.__accessed = False

Is there a better way to capture any kind of interactions with my object? Or am I missing something for this approach ?
Thanks.


text:
Q: How to deal with very unstable operating systems? I'm trying to do some changes on a portable computer, running Windows 7. It fills the entire partition.
However, I'm pretty much unable to run Windows, because it suddenly freezes in a matter of minutes. How can I work with it?
I'm trying to create a new partition and install a new OS on it, while preserving previous data. I have a wireless network and another stable computer.

A: *

*Boot a different OS from a CD/DVD or USB memory stick (for example, some utility distro)

*Move the data to a safe place

*Format everything and install a new OS

*If the system is still unstable, locate the cause.

A: You can use Ubuntu (or another Linux distro) to extract the data. If this doesn't work out (if it stills reboots/freezes), you can try upload the data to a cloud storage (Dropbox, OneDrive, Box, Google Drive, etc) and download later.
However, if a upload can't be done, you will have to remove the HDD and extract the data directly through your other computer.


text:
Q: JQuery UI droppable accept condition not working After searching google and stackoverflow for nearly two hours, I just can't get to the bottom of this. I can't find the problem in my code:
HTML:

uuu

aaa

Javascript:
$("li").draggable({
    helper: function () {
       return $("
test
");
    }
});

$("#canvas").droppable({
    accept: ".helper",
    drop: function (ev, ui) {
        var h = ui.helper.clone(false) //$(ui.helper).clone(false) shows the same behaviour
               .removeClass('ui-draggable-dragging')
               .css({position:'relative', left:0, top:0});
        $(this).append(h);
    }
});

$("body").disableSelection();

Whatever I do, whenever I specify the "accept" option of .droppable, $("#canvas") won't receive any elements anymore.
Here's the fiddle: http://jsfiddle.net/98tdy/
Can anyone please tell me the problem?

A: Your code is not working becuase you've specified <div id="#canvas"
so $("#canvas") won't work. simply change the id to canvas
check this fiddle


text:
Q: Nginx Wild Card Domains I have an A Name domain setup on Nginx, I also have wildcard DNS setup on Digital Ocean.
I would like my main domain to point to where it is: /usr/share/nginx/html/mission13.io
I would then like all the wildcard domains to point to their respective folders:

*

*/usr/share/nginx/html/sub1.mission13.io

*/usr/share/nginx/html/sub2.mission13.io

*/usr/share/nginx/html/sub3.mission13.io
Here is what I have, but I am not sure what to do to get them to point to the proper location. What can I change to do that?
server{
    listen 80;
    root /usr/share/nginx/html/mission13.io;
    index index.php index.html index.htm;

    server_name mission13.io www.mission13.io *.mission13.io;

    location / {
            try_files $uri $uri/ /index.html;
    }
    include /usr/share/nginx/conf/mission13.io.conf;
    location ~ \.php$ {
            fastcgi_pass unix:/var/run/php5-fpm.sock;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include fastcgi_params;
    }
}

A: Got it!
I need to use $http_host like so:
root /usr/share/nginx/html/$http_host;

A: Another way please change server name to _ then it will search folder with the host name inside root /usr/share/nginx/html/ directory.so,your directory looks clean
server{
 listen 80;
 root /usr/share/nginx/html;
 index index.php index.html index.htm;

 server_name _;

 location / {
        try_files $uri $uri/ /index.html;
 }
 include /usr/share/nginx/conf/mission13.io.conf;
 location ~ \.php$ {
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
 }
}


text:
Q: Python - None value is being returned from a count I'm trying to count the max number of spaces there are in a sentence with the following code:
def spaces(sentences):
  textList = sentences.split('. ')
  whiteList = [whitespaces.count(' ') for whitespaces in textList]
  x = max(whiteList)
  print(x)

However, while it is returning the number of whitespaces there are, this is also returning a None on a second line. How come this is the case?

A: You print the result, but you don't return it. You need to add return x at the end of your code.
You can check this page, which explains the difference between print and return in Python.

A: You must return a value from your function and then print the result of it
def spaces(sentences):
  textList = sentences.split('. ')
  whiteList = [whitespaces.count(' ') for whitespaces in textList]

  return max(whiteList)

print(spaces(sentences))


text:
Q: Django Is it efficient for DB to store uploaded files in model? I have a form and if I store the file using form.save(), is the entire file content stored in DB or just the file path?
Suppose I have hundreds of thousands or millions of files. Is it efficient to store all of them in DB because size of the table must be huge?
If I don't want to store them in database and simple upload and keep them in local file system, is there any way I could get the list of all file names? By storing them in database, I simply get that by:
AllDocument.objects.all()

Thanks!

A: Actually, by default django stores only paths to files in db, not the files themselves, so there is no problem to store even millions of file entries.
I do not think it is a good idea to store file paths somewhere else. At least, it will be more complex than using Django Manager.

A: I think Djanga stores files in media or static root files, and the paths in the db.

A: Doc.

A local filesystem path that will be appended to your MEDIA_ROOT
  setting to determine the value of the url attribute.

I think this can help you, to clarify the question.
A file-upload field . FileField

The file is saved as part of saving the model in the database, so the
  actual file name used on disk cannot be relied on until after the
  model has been saved.

FileField and FieldFile


text:
Q: Neural Network is not predicting the correct digit I am new to ML and for my project, I am trying to make a digit classifier using neural networks.
I have made a GUI where you can draw the digit and it will pass the NumPy Array to the neural network.
I have trained my neural network with mnist digit data set with a model accuracy of 97.70% yet it cannot predict the digits entered.
#CODE FOR NEURAL NETWORK
    class mltest():
       def __init__(self):
          self.model = keras.Sequential([  keras.layers.Dense(120,input_shape = (784,),activation = 'relu'),
                                           keras.layers.Dense(10,activation = 'softmax')])
       def train(self):
          (x_train,y_train),(x_test,y_test) = keras.datasets.mnist.load_data()
          x_train = x_train/255
          x_test = x_test/255
          x_train = x_train.reshape(len(x_train),28*28)
          x_test = x_test.reshape(len(x_test),28*28)

          self.model.compile(optimizer='adam',loss='SparseCategoricalCrossentropy',metrics=['accuracy'])
          self.model.fit(x_train,y_train,epochs=12,batch_size=200)
          self.model.evaluate(x_test,y_test)

       def test(self,value):
           y_predicted = self.model.predict(value)
           print(np.argmax(y_predicted))

       if __name__ =='__main__':
           obj = mltest()
           obj.train()

Epoch 12/12
300/300 [==============================] - 1s 2ms/step - loss: 0.0338 - accuracy: 0.9908
313/313 [==============================] - 0s 776us/step - loss: 0.0763 - accuracy: 0.9770

CODE FOR GUI
class Window(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("Ai")

        self.setGeometry(300,300,300,300)

        self.image = QImage(self.size(), QImage.Format_RGB32)

        self.image.fill(Qt.white)

        self.drawing = False

        self.brushSize = 25

        self.brushColor = Qt.black

        self.lastPoint = QPoint()

        self.object = mltest()

#To send the picture data to neural network when enter key is pressed
    def keyPressEvent(self, event):
        if event.key() ==  16777220:
            screen = QtWidgets.QApplication.primaryScreen()
            screenshot = screen.grabWindow(QtWidgets.QWidget.winId(self))
            bufffer = QBuffer()
            bufffer.open(bufffer.ReadWrite)
            screenshot = screenshot.save(bufffer,'PNG')
            image = Image.open(io.BytesIO(bufffer.data()))
            image = image.convert('P')
            image = np.array(image)

            image =cv2.resize(image,dsize = (28,28))

            image = cv2.blur(image,(2,2))
            image = cv2.bitwise_not(image)
            image[image<=30] = 0
            print(image)

            plt.matshow(image)
            plt.show()
            image = image.reshape(1,28*28)
            image = image/255

            self.object.test(image)
 #To draw
    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:

            self.drawing = True
            self.lastPoint = event.pos()

    def mouseMoveEvent(self, event):

        if (event.buttons() & Qt.LeftButton) & self.drawing:

            painter = QPainter(self.image)
            painter.setPen(QPen(self.brushColor, self.brushSize,
                            Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin))

            painter.drawLine(self.lastPoint, event.pos())

            self.lastPoint = event.pos()

            self.update()

    def mouseReleaseEvent(self, event):

        if event.button() == Qt.LeftButton:
            self.drawing = False

    def paintEvent(self, event):
        canvasPainter = QPainter(self)
        canvasPainter.drawImage(self.rect(), self.image, self.image.rect())

    if __name__ == '__main__':
        App = QApplication(sys.argv)
        window = Window()
        window.show()
        sys.exit(App.exec())

predicted value is 5

A: You apparently use  if __name__ =='__main__': in two files, and you train the network only when you call the network's file, while when you launch your GUI application your network is created untrained there self.object = mltest(). Unless you call self.object.train(), it'll probably remain untrained and thus incapable of good predictions


text:
Q: tool for pdf creation from .net? We are looking for a sdk to create complex pdf document from a .NET application
So far we used "aspose for pdf" that was Ok appart from the HTML to pdf features
because while generating it crashes depending from the
complexity/css styles of our html block we add to the pdf (requirement 4)
That why aspose isn't a option for us.
Our mandatory requirements are
1 automatic generation of a table of content (toc) with page information
(not pdf bookmark!)
2 automatic page numbering at the bottom of each page (page x of y)
3 add textual chapter or headings that are
  references in the toc,
  important: the chapter numbering 1, 1.1, 1.1.1, 1.1.1.2 etc. has to be generated automatically !
4 adding html -> pdf elements, the document contains then a mix of a
    chapter structure,
    formatted not html text elements,
    images,
    html sections
the content and structure of the generated pdf should be like this
document title

<any text> etc.

-- endofpage --

table of content

1 mainchapter  .............. page 1

1.1 subchapter .............. page 1

2 mainchapter ............... page 3

2.1 subchapter .............. page 3

2.1.1 subchapter ............ page 3

etc.

-- endofpage --

1 mainchapter <<< chapter number have to be generated automatically depending on the document   structure and actualize if the content or structure changes!

1.1 subchapter

<any text> etc.

<html formated text> <<< any valid html block should be rendered,
           css styles that can't be interpreted should be ignored

-- endofpage --

<image>
<any text> etc.

 etc.

-- endofpage --

2 main chapter

<any text> etc.
<image>
<image>
<any text> etc.

We didn't find any sdk that offer a automatic chapter numbering  so far
whereas pdfcreator and pdftron offers a stable html rendering, we are missing
any TOC feature from the document heading/chapters.
After 3 days of googling and sample evaluation we didn't find any tool so far.
Does somebody have a hint?
Thank for any idea.
Kagel

A: I've always recommended the following PDF creation libs:
https://www.nuget.org/packages/iTextSharp-LGPL/
https://www.nuget.org/packages/PdfSharp/
Those are two very tested and proven libraries, I believe PdfSharp has the functionality you're looking for


text:
Q: Wordpress loop not looping over posts I am working on a Wordpress theme and for some reason even though I have posts it is showing that I do not have any posts.
<?php if(have_posts()){ ?>

        <?php if ( is_home() && ! is_front_page() ) { ?>

<?php single_post_title(); ?>

        <?php while ( have_posts() ){ the_post();  ?>

            <?php
            /*
             * Include the Post-Format-specific template for the content.
             * If you want to override this in a child theme, then include a file
             * called content-___.php (where ___ is the Post Format name) and that will be used instead.
             */
            get_template_part('template-parts/content', get_post_format()); ?>

        <?php } ?>

        <?php the_posts_navigation(); ?>

    <?php }else{ ?>
        <?php get_template_part( 'template-parts/content', 'none' ); ?>
   <?php } ?>

I'm having issues with debugging it since it shows their are posts.

A: I checked your code and it seems like you made a mistake in templates paths, they should be "template-parts/post/content" - you lost "post/" directory.


text:
Q: Use of Airbus WorldDem altimetric values (EGM2008) In France, the altimetric values are issued from a mesure of heights above the sea level based on the Marseille's tide gauge. If i didn't mess it up, the system is named NGF - IGN69 for mainland (See https://en.wikipedia.org/wiki/General_levelling_of_France).
In the dataset named WorldDEM from Airbus, I see the vertical reference is EGM2008 (Ref : http://www.engesat.com.br/wp-content/uploads/663-2015_04_worlddem_technicalspecs_version2.pdf)
Are those two compatible ? Can I compare/mix both and/or does one needs to do a transformation to be in the same altimetric system ? Said differently : can I use WorldDem in France without doing any transformation/shift ?


text:
Q: explain this haskell funtion "list of tuples to list" I'm a beginner and basically I need an explanation of this
He answer with this code:
tupleToList :: [(a,a)] -> [a]
tupleToList ((a,b):xs) = a : b : tupleToList xs
tupleToList _          = []

But I don't underdand why he don't use:
tupleToList [] = []
tupleToList ((a,b):xs) = a : b : tupleToList xs

Like I usually see in the first exercises of the guides.
I know that '_' is whatever, but, isn't better to use '[]' that mean, when the list is empty?

A:
Like I usually see in the first exercises of the guides. I know that _ is whatever, but, isn't better to use [] that mean, when the list is empty?

Semantically the two are the same since a 2-tuple has only one constructor (a,b), and a list has two constructors [] and (h:t).
Since the only pattern left that is not matched by the first clause is the empty list, the wildcard _ is equivalent to [].
Since [] and ((a,b):xs) are disjunctive patterns (i.e. there are no values that can match both patterns), the order of the two patterns is of no importance, when [] is used explicitly. We can write it in any order we like, then.
Some Haskell programmers prefer to use explicit patterns (so with [] instead of _), since that means that we know which values we actually handle with that clause. If later the Haskell community would decide to introduce an additional list constructor (yes, for lists that is very unlikely, but for other data types this might be more reasonable), the Haskell compiler can (with -Wincomplete-patterns) give warnings that some patterns are not covered. A wildcard of course covers all patterns, but perhaps the expression at the right is not the one we intended for the additional constructor.
Therefore I would advice to use a wildcard only in case you want to match multiple patterns by the same clause. In case it is clear what the other pattern is, it is better to be explicit. Like the Zen of Python says (yes, it is Python, but most concepts are to some extent universal): "explicit is better than implicit".

A: There is no difference: their semantics is exactly the same.
tupleToList [] = []
tupleToList ((a,b):xs) = a : b : tupleToList xs

is equivalent to
tupleToList ((a,b):xs) = a : b : tupleToList xs
tupleToList [] = []

which is equivalent to
tupleToList ((a,b):xs) = a : b : tupleToList xs
tupleToList _ = []

Usually, the wildcard _ is used when we need to pattern match multiple cases. E.g.
myAnd :: Bool -> Bool -> Bool
myAnd True  y = y
myAnd False _ = False

Above, we could enumerate the False False and False True cases individually, and use three equations, but using a wildcard is more convenient (and makes our function slightly lazier, e.g. myAnd False undefined evaluates to False).
Concluding, it's mostly a matter of style. Usually, when the wildcard _ can only stand for one case, it is better to spell it out, to be explicit about it. In this way, the code is often more readable. E.g.
not :: Bool -> Bool
not False = True
not _     = False

is equivalent but worse than
not :: Bool -> Bool
not False = True
not True  = False

The same holds for case expression, of course.
case x of
  Just y  -> 1 + y
  Nothing -> 0

is arguably more readable than
case x of
  Just y -> 1 + y
  _      -> 0


text:
Q: Adding CNAME to domain apex for Hubspot and AWS SES DKIM etc Both Hubspot and AWS SES require that we add CNAME records to make emails sent through them work.
To this end, I've been asked to add various CNAMES to our domain apex e.g. example.com, so we can send emails from e.g. info@example.com (as opposed to a subdomain e.g. info@mail.example.com)
See for e.g.
https://knowledge.hubspot.com/articles/kcs_article/cos-general/how-can-i-resolve-the-missing-records-associated-with-my-email-sending-domain?utm_source=hs_email&utm_medium=email&utm_content=63942509
However, technically, the specs for DNS specify that you can't add a CNAME record to the domain apex.
So, how does this work? Let's say Hubspot want me to add a CNAME with the Hostname: hs2._domainkey.example.com
Should I create a subdomain hs2._domainkey? Or add the CNAME record in the domain apex in Amazon Route 53 and risk causing problems with subdomains?

A: The premise of this question is a bit strange, as it seems centered around doing something else than what the referenced documentation says that you should do.
In the Hubspot example they mention adding a CNAME record at eg hs2._domainkey.example.com, which is clearly not the zone apex if your zone is example.com (which seems like the reasonable assumption).
The AWS SES instructions are (as you indicated) similar in this regard.
This is unsurprising, as these are both cases of DKIM records, which always reside at names that have a selectorusedinyourmailserverconfig._domainkey prefix.

As for your questions regarding the zone apex, you are correct that you cannot have a CNAME record there. Luckily, neither service provider is asking you to add such a record.
The general rule for CNAME records is not specifically about the zone apex, rather that CNAME records cannot coexist with other records.
The zone apex just so happens to be a case that always has other records (it must have at least SOA and NS records).


text:
Q: SQL Query displaying duplicate results suddenly I am stumped after a day of troubleshooting. This MySQL query has been running successfully for a month and all of the sudden I am receiving duplicate results which is fouling up the entire management program it is relevant to.
My troubleshooting included searching the database for duplicate entries and none existed. For example, I used the search command in phpMyAdmin to display the entries where entry_id = 45 and field_id = 65. The result of the search displayed only one result which is correct. As of yesterday the below query displays the same result twice.
Query:

    SELECT f.id, f.title, f.type, f.name, v.id AS f_id, v.field_value
    FROM jos_directory_enf AS v
    LEFT JOIN jos_directory_field AS f ON f.id = v.field_id
    WHERE v.entry_id = 45 AND v.field_id = 65

A: You may want to see if your joining tables have any duplicates in them that will result in more results to your main query.

A: It is difficult to answer your question without knowing details about your schema and the duplicated result. I guess your data was updated since the time where no duplicated were presented.
Look if v.id and v.field_value contain NULL values more than once for the same v.field_id or there rows with the same values for the columns, which you project in one of the two tables. Look if f.id or v.field_id have the same values in different rows.


text:
Q: Convergence in Probability of functions defined in metric spaces Let $(\Omega,\mathcal{F},\mathbb{P})$ be a probability space, $(S,d)$ a metric space, $\xi$ and the sequence $\{\xi_n\}$ be $\mathcal{F}/\mathcal{B}(S)$-measurable maps.
According to Wikipedia we require that $(S,d)$ be separable to define convergence of $\xi_n\rightarrow\xi$ in probability but other texts (such as Kallenberg) don't mention separability, so is it needed to ensure that $\forall\epsilon>0,\lim\limits_{n\rightarrow\infty}\mathbb{P}[d(\xi,\xi_n)\geq\epsilon]=0$ is well-defined?
Secondly it is claimed that convergence in probability is equivalent to $\lim\limits_{n\rightarrow\infty}\mathbb{E}[d(\xi,\xi_n)\wedge1]=0$ and $\rho_1(X,Y):=\mathbb{E}[d(X,Y)\wedge1]$ defines a metric on the set $\mathcal{M}$, of all $\mathcal{F}/\mathcal{B}(S)$-measurable maps. I am a bit stuck here and not sure how to show that the two definitions of convergence are equivalent, I tried using the Markov equality but don't get anywhere.
It is also claimed the $\rho_2(X,Y):=\inf\{\epsilon>0:\mathbb{P}[d(X,Y)>\epsilon]\leq\epsilon\}$ defines a metric on $\mathcal{M}$ and so do to me it seems quite obvious that $\rho_2(\xi,\xi_n)\rightarrow 0$ is equivalent to convergence in probability as the only difference is the $\geq$ sign, so am I right are is there a more detailed argument?
And so $\rho_1$ and $\rho_2$ must be equivalent metrics as the have the same convergent sequences?
So any help with any of my questions is really needed and appreciated. Thanks

A: For the first question, why wouldn't it be well defined?
For the secon question, note that $\mathbb{E}[min(d(\chi,\chi_{n}),1)] \leq \mathbb{P}(d(\chi_{n},\chi)\geq \epsilon) + \epsilon $


text:
Q: Toggle button to switch between desktop/mobile view like chrome desktop site For my mobile menu, I would like to add a toggle button to the desktop view, and the user can click the button again to go back to mobile view.
So far, I manage to make the button go to desktop view, but :-
1) How can I toggle it back to mobile view?
2) While in desktop view, if I go to other page, it just goes back to mobile view. So, how can I force it based on my current preferred view?
Basically, what I'm trying to achieve is exactly as chrome desktop site option.
Here's my code so far:
HTML
<button onclick="requestDesktopSite()">Request Desktop Site</button>

Javascript
function requestDesktopSite() {
document.getElementsByTagName('meta')['viewport'].content='width= 1440px;';
}

A: Maybe try this:
function requestDesktopSite(){
 if(document.getElementsByTagName('meta')['viewport'].content=='width= 1440px;'){
  document.getElementsByTagName('meta')['viewport'].content='width= 400px;';
 }else{
  document.getElementsByTagName('meta')['viewport'].content='width= 1440px;';
 }
}


text:
Q: Is it possible to sum all integers in a list? (C# console) I have a list containing user entered values. I would like all integers entered to sum together at the end and the total to be displayed. Is this possible?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BubbleSort1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.ForegroundColor = ConsoleColor.Green;
            List<int> price= new List<int>();
        enterprice:
            Console.WriteLine("Please enter price");
            Console.WriteLine("When Finished please press '/'");
            string pricex = Console.ReadLine();

            if (pricex == "/")
            {
                goto receipt;
            }
            else
            {
                int pricey = Convert.ToInt16(pricex);
                price.Add(pricey);
                Console.Clear();
                goto enterprice;
            }

        receipt:
            Console.Clear();
            Console.WriteLine("Your Outflows:");
            Console.WriteLine(string.Join("\n", price));
            Console.ReadKey();
        }
    }
}

Before anyone mentions I understand there are better methods than goto and I could probably save user entered data straight as integers and I will learn how but have just started so want to take my time with it. Many thanks ;)

A: There is a sum function on the List object.
var total = price.Sum();

It is an extension method on System.Linq.  So, you will also need.
using System.Linq;

A: The other answer recommends LINQ, and that is definitely the less verbose way to do it. But I have a feeling that you're just learning, so may want to have an idea of how this actually works. Below is the an abridged version of the Linq.Sum source code so you can see what is happening.
public static int Sum(this IEnumerable<int> source)
{
    int sum = 0;
    foreach (int v in source)
    {
        sum += v;
    }
    return sum;
}

It loops through each item in the IEnumerable, adds them to another variable, and then returns that result.


text:
Q: Fullscreen on Nexus devices using libgdx Does anyone know how to go fullscreen using libgdx, where the virtual home key buttons on devices such as Nexus are also not visible?

A: In case anyone finds this like I did while looking for a simple fix you can use
config.useImmersiveMode = true;

on the AndroidApplicationConfiguration object on 4.4 and up to hide the soft keys in addition to the statusbar (which is hidden by default).
UPDATE: The line belongs in android/src/YOUR/PACKAGE/PATH/android/AndroidLauncher.java

A: libgdx does this for you by default via AndroidApplicationConfiguration#hideStatusBar. However, you can still set to fullscreen.
In the android game project's main activity class:
public class MainActivity extends AndroidApplication {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
         requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
        AndroidApplicationConfiguration cfg = new AndroidApplicationConfiguration();
        //cfg.hideStatusBar = true; //set to true by default

if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
getWindow().getDecorView().setSystemUiVisibility(View.STATUS_BAR_VISIBLE);
getWindow().getDecorView().setSystemUiVisibility(View.STATUS_BAR_HIDDEN);
}
            initialize(new MainClass(), cfg);
        }
    }

I realized there's a bug where the buttons on the status bar becomes visible after resuming from a locked screen. The workaround is to  either use handler to listen(setOnSystemUiVisibilityChangeListener) for system UI visibility changes and then re-hide the UI if it becomes visible or show the status bar before hiding it as I've done above.
Also View.STATUS_BAR_HIDDEN (API v11) was renamed to View.SYSTEM_UI_FLAG_LOW_PROFILE (API v14) which turns the virtual nav buttons into dots. However, both map to the same constant 0x1. Also, as soon as the screen is touched again the buttons will become visible .
If you want to remove the status bar entirely, use View.SYSTEM_UI_FLAG_HIDE_NAVIGATION (API v14) and Build.VERSION_CODES.ICE_CREAM_SANDWICH

A: What you should do is set System Ui Visibility in onResume()
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);

A: Tried many things and only this code succeeded for me:
...

      AndroidApplicationConfiguration cfg = new AndroidApplicationConfiguration();
        cfg.useGL20 = false;
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        View decorView = getWindow().getDecorView();

     decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                                   | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                                   | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                                   | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                                   | View.SYSTEM_UI_FLAG_FULLSCREEN
                                   | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);

     initialize(new Soldiers(), cfg);

This is part of MainActivity.java and probably should be executed also on onResume().


text:
Q: Calculation of an error of a non-linear FSR produced by the connection of the voltmeter Background: I'm studying my master at Computer Science and took a course that requires some understanding in electrical engineering. Unfortunately I have a very basic understanding of electrical engineering concepts.
Having said that, I've encountered the following question on electrical impedance with a pretty straightforward solution:

I was basically asked to solve this question once again, but now the dependence between the sensor resistance and the force is not linear but quadratic. Meaning: $$F=R^2$$
Should also be noted that question emphasizes that ranges stay the same, meaning for 1g we have 1 MegaOhm and for 1000g we have 1 KiloOhm.
So I've tried to figure out what changes in terms of calculation when force sensor resistance changes but couldn't come up with anything.
Any hints? Thanks!

A: If the resistance changes quadratically, isn't the equation:
R = k.F^2. ?
However this is inconsistent with the 2 end points given (1g == 1 MΩ; 1000 g = 1 kΩ), and in fact inconsistent with resistance increasing with force.
However, once you clarify that, you can calculate the sensor's resistance for any applied force. The error is then the fractional difference between that value and the value with 10 MΩ in parallel.


text:
Q: Representing multiple values within one class member I've been working on some electrical network simulation software (ElecNetKit). In electrical networks, sometimes it's convenient to work with single-phase models, sometimes in three-phase models.
As such, I would like to be able to represent one of the electrical network elements as:
class Bus
{
    public Complex Voltage {set; get;} //single phase property
}

but simultaneously in a fashion so that the user can call Bus.Voltage.Phases[x], and expect a Complex for any valid integer x.
The Bus.Voltage property should map to Bus.Voltage.Phases[1] when treated as a Complex.
I've got two questions here:

*

*Is this in violation of any OOP principles? I've got a feeling that it might be.

*Is there a convenient way to represent this in C#?
In terms of representation, I've tried:

*

*a class Phased<T> : T, but this is incompatible with the typing system, and

*a class Phased<T> with a generic converter to type T, but the converter still needs to be invoked.

I'm aware that I can simply use something like:
public Dictionary<int,Complex> VoltagePhases {private set; get;}
public Complex Voltage {
    set {VoltagePhases[1] = value;}
    get {return VoltagePhases[1];}
}

but there's a lot of repetition once you start to do this for multiple properties, across multiple classes.

A: Can you do something like this? This will work similar to your solution at the bottom but because of the generic class you are not repeating the code for each property.
class Program
{
    static void Main(string[] args)
    {
        Collection<Complex> complex = new Collection<Complex>();
        //TODO: Populate the collection with data

        Complex first = complex.First;
        Complex another = complex.Items[2];
    }
}

public class Complex
{
    // implementation
}

public class Collection<T> where T : class
{
    public List<T> Items { get; set; }

    public T First
    {
        get
        {
            return (Items.Count > 0) ? Items[1] : null;
        }
        set
        {
            if(Items.Count > 0)
                Items[1] = value;
        }
    }
}

A: I would propose something like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Diagnostics;
using System.Numerics;

namespace Test
{
    class PhaseList
    {
        private Dictionary<int, Complex> mPhases = new Dictionary<int, Complex>();

        public Complex this[int pIndex]
        {
            get
            {
                Complex lRet;
                mPhases.TryGetValue(pIndex, out lRet);
                return lRet;
            }
            set
            {
                mPhases.Remove(pIndex);
                mPhases.Add(pIndex, value);
            }
        }
    }

    class PhasedType
    {
        private PhaseList mPhases = new PhaseList();
        public PhaseList Phases { get { return mPhases; } }
        public static implicit operator Complex(PhasedType pSelf)
        {
            return pSelf.Phases[1];
        }

        public static implicit operator PhasedType(Complex pValue)
        {
            PhasedType lRet = new PhasedType();
            lRet.Phases[1] = pValue;
            return lRet;
        }
    }

    class Bus
    {
        public PhasedType Voltage { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Bus lBus = new Bus();

            lBus.Voltage = new Complex(1.0, 1.0);
            Complex c = lBus.Voltage;
            lBus.Voltage.Phases[1] = c;
            c = lBus.Voltage.Phases[1];
        }
    }
}


text:
Q: How to make a connection with local host database through visual studio 2008 using c#? I have created a sample database in MySql workbench. I am working on a smart device windows application and i am trying to connect my local host where i have my sample database to the login button i have created on the login form. My coding
private void Login_Click(object sender, EventArgs e)
{

    MySqlConnection conn = new MySqlConnection("server=localhost;User Id= ;database= ");
    MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM login where Username = '" + textBox1.Text+ "' and Password = '" + textBox2.Text + "'", conn);

    DataTable dt = new DataTable();
    da.Fill(dt);
    if (dt.Rows[0][0].ToString()== "1")
    {
        MainMenuform ps = new MainMenuform();
        ps.Show();
        this.Hide();
   }
    else
    {
        MessageBox.Show("Please check Username and Password");
    }
}

So, when i try the above coding, its giving me an error "Cannot connect to the specified MySql host you specified". My code seems alright but i am still getting this error. Please help.


text:
Q: Access windows user folder from ubuntu live How can i access windows users directory from ubuntu live to backup some files before format.
It is showing me empty folder but i know that it is not empty?
Folder /media/somepart/Users/Myuser is empty but i know it is not.
If i where under windows i could perform take over ownership of that directory but i do not know how to do that under linux.
Can you help me to transfer files ?

A: You are looking in the wrong place. On the left bar, there should be something like OSDISK or XXX GB Filesystem. You want to pick the one where Windows is installed(try a few). Your documents will be stored in Documents and Settings/[Your username]/My Documents or Users/[Your username]/My Documents. You can copy them to a flash drive. You can also do this after installing as long as you don't pick the option to remove Windows while installing.

A: try with sudo: sudo cd /media/somepart/Users/Myuser
I do not recommend to use chmod, since this can ruin Windows-Permissions (wrong order for windows), that computer behaves unpredictable (not reproducible) and might won't start any more (at least can't log in with this user). I ruined Win7 this way, with cygwin. (I applied chmod on the whole disk including C:\Windows, I reinstalled Windows)


text:
Q: Jupyter lab is only opened on private ip, not public ip OS : ubuntu 18.04.1 LTS on aws ec2
I'm setting up jupyter lab on my aws ec2 server, and want to connect my server from other pc.
However I can't access jupyter
Maybe that's why it is connected to private ip
Firstly, I installed jupyter and config
$ pip3 install jupyter

$ pip3 install jupyterlab

$ jupyter notebook --generate-config

changed config on

"~/.jupyter/jupyter_notebook_config.py"

c.NotebookApp.allow_origin = '*'

c.NotebookApp.ip = '0.0.0.0'

c.NotebookApp.open_browser = False

c.NotebookApp.password = <my_password>

c.NotebookApp.port = 8888

and then, I try to run jupyter lab

$ jupyter lab

Finally,
[I 06:25:39.565 LabApp] JupyterLab extension loaded from /usr/local/lib/python3.6/dist-packages/jupyterlab

[I 06:25:39.565 LabApp] JupyterLab application directory is /usr/local/share/jupyter/lab

[W 06:25:39.567 LabApp] JupyterLab server extension not enabled, manually loading...

[I 06:25:39.569 LabApp] JupyterLab extension loaded from /usr/local/lib/python3.6/dist-packages/jupyterlab

[I 06:25:39.569 LabApp] JupyterLab application directory is /usr/local/share/jupyter/lab

[I 06:25:39.570 LabApp] Serving notebooks from local directory: /home/ubuntu/.certs

[I 06:25:39.570 LabApp] The Jupyter Notebook is running at:

[I 06:25:39.570 LabApp] http://(ip-XXX-XX-XX-XXX or 127.0.0.1):8888/

[I 06:25:39.570 LabApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).

is printed
I expect ec2-XX-XXX-XXX-XX.ap-northeast-2.compute.amazonaws.com shows on cmd
How can I run jupyter on public ip?


text:
Q: Convert repository to older version (without sparse revlog) Our team is using Mercurial for version control, with the central repository located on a shared network drive (i.e. we are not using a server). Our company restricts what we can install on our computers, and everyone had Hg version 4.6. One of the team members used admin rights he has to install the latest TortoiseHg (4.9). It seemingly resulted in the central repository to be converted to the newest version. Now another team member, with the old Mercurial, cannot pull from the central repository. It says

repository requires features unknown to this Mercurial: sparserevlog

I read a bit about it, and it seems that this feature is not critical for us. Would it be possible to revert the central repository to the version without sparse revlog?

A: Normally it should be possible to instruct hg during a clone operation NOT to use a specific, newer repo format.
There are specific configuration options for this, as shown in the docs:

Config option: format
usegeneraldelta

Enable or disable the "generaldelta" repository format ...  Enabled by
default.
dotencode

Enable or disable the "dotencode" repository format ...  Enabled by
default.
usefncache

Enable or disable the "fncache" repository format ... Enabled by
default.
usestore

Enable or disable the "store" repository format ... Enabled by
default.

However for some reason there is no option listed corresponding to the newest repo format which as noted in the question is "sparse-revlog" (documented here).
But that seems to be just a documentation oversight, so similar to the answer to another question, you should be able to re-clone using a command similar to this:
hg clone --config format.sparse-revlog=no  <source> <dest>

This will require hg to NOT utilize that format, which means the older prior format should be what you get and will be compatible with your local hg clients.
Added info/explanation from a comment by Juan: this will work if (a) your clone source & destination are not on the same filesystem or (b) you add --pull.
(By default Mercurial will try to create hard links for speed & space savings. Avoiding hard links by cloning to different filesystems or different hosts altogether or by forcing the clone to not use hard links on the same filesystem by using --pull will allow the new repo to be created without sparse-revlog.)
I guess you would have to do this to replace every existing clone that has been pulled since the central repo was accidentally upgraded. I would plan that work carefully, to make sure no local changes are lost. You could to a local pull using the same config option to transfer commits from the old to new repos.

A: With 4.9, new repositories will be created using sparse-revlog by default. However existing repositories are untouched. They stay in the same format they have been created with.
Avoiding the issue at repository creation
To prevent the users who upgraded to create sparse-revlog repositories he needs to set the following in his user configuration (hg config -e)
[format]
sparse-revlog = no

Do you have global control of your users configuration?
Downgrading existing repositories
If you want to downgrade such newly created repository you do the following:

*

*add the following to the repository configuration (hg config -l)

[format]
sparse-revlog = no

*run hg debugupgraderepo --run (with 4.7 or newer)

Upgrading existing repositories
If you want to upgrade existing created repository, the process is similar:

*

*add the following to the repository configuration (hg config -l)

[format]
sparse-revlog = yes

*run hg debugupgraderepo --run (with 4.7 or newer)

Note: the page https://www.selenic.com/mercurial/hgrc.5.html#format is outdated. The website for mercurial have been https://www.mercurial-scm.org/ for a couple of years.

A: Here's one approach which is kind of ugly (understatement) but might work as a fix, since you only have to do it once...
This approach takes advantage of the fact that an HTTP-served HG instance can apparently interoperate between any internal repo versions.
According to docs Missing Requirement section Downgrade your repository over the network:

Because all versions of Mercurial can interoperate over the network,
  an old client can simply pull from a repository served by a new
  client:
# run this on the new client
$ hg serve
listening at http://hostname:8000/ (bound to *:8000)

# run this on the old client
$ hg clone http://hostname:8000/ downgraded-repo

Since you are not using hg serve already this obviously won't work for you automatically. But you might be able to use it temporarily. Something like this:

*

*Setup a temporary hg serve running on some PC. (Ideally, IT restrictions won't prevent this.) It should serve your central repo.

*Identify all clones of the repo which need to be fixed. (Maybe cull any which aren't needed to save work here.) These should only need to be ones modified (pushed/pulled) by a THG 4.9 client.

*Backup work. Ideally, commit and push everything possible first to reduce the later step which restores any backed-up files.

*Following the example above, re-clone from the temporary hg serve PC to new local clones in all instances where they are needed.

*Restore any backed-up work to the new clones (this is the worst part and could be really painful). I think this has to be done manually; maybe there is a clever diff/patch approach which would be easier.

*Shut down the temp hg serve instance
Be cautious that the problem could eventually re-propagate outwards. i.e., if even one repo is overlooked and later is used to push to the central repo, the problem will repeat itself.
Alternative / variation - you could run hg serve on each & every developer's PC that had used THG 4.9, and have them each independently re-clone from localhost. This might get around any IT limitations, if absolutely necessary. (But if you don't have IT limitations, it doesn't really matter where hg serve itself is running).

If you have a very large # of affected devs / clones, I am not sure this approach is best. For one thing, if you were able to involve your IT people to upgrade everyone to the newest hg version, it could be a much easier fix overall.


text:
Q: Get Visual Studio 2015 to recognize Doxygen comments I have a function documented like this:
/**
 * Does something useful
 */
int foo(Bar bar)
{
    // my function
}

But Intellisense doesn't display it when i hover the function in other places. When i hover it at the definition, i see * Does something useful, which isn't right either (the star should not be in there). Doxygen runs fine and eclipse CDT displays the doc comments as you would expect.

A: As of version 2016.2, JetBrains ReSharper provides support for Doxygen documents in C++ files. From this blog post I quote:

Doxygen is arguably the most popular format and tool for code
  documentation in the C++ world. ReSharper C++ now understands Doxygen
  syntax, and provides several key features to facilitate editing of
  documentation blocks.

*

*Typing assist helps with creating new comment blocks and maintaining the
  structure of existing ones.

*Code completion suggests Doxygen commands with accompanying short descriptions.

*Function parameter references introduced with \param commands will be reported by Find Usages and will get updated when Rename is used to change a function parameter's name.

*Warnings are issued when function parameter references do not resolve to an existing function parameter.

*Documentation generation: You can now generate documentation for C++ declarators, classes and macro definitions.

*Quick Documentation: Documentation now works in C++. The documentation pop-up (bound to Ctrl+Shift+F1 in the Visual Studio scheme or Ctrl+Q in the IntelliJ IDEA scheme) will display documentation from Doxygen comment blocks, or the symbol's signature if no documentation is found.

It should be noted that this product is not free and to use it, you need to procure a license.


text:
Q: ¿Como remover comillas de un query POSTGRESQL? Intento realizar una consulta que por me dio de un SELECT dentro de un IN me muestre la información que en cuyo requerimiento necesito; se que el problema que puedo tener es porque el campo dinámico para los IN es un VARCHAR (24,34), y en la tabla principal los id son INTEGER, entonces ¿como podría remover esas comillas para simular que es una especie de "arreglo" con números enteros?
SQL
SELECT public.tb_encuesta.enc_nombre
FROM public.tb_encuesta
WHERE public.tb_encuesta.enc_id IN (
                                     SELECT CAST (per_enc_id AS integer)// Este es el campo que contiene los valores
                                     FROM public.tb_periodo
                                     WHERE per_estado = true
                                     ORDER BY per_id DESC
                                     LIMIT 1
      )

ERROR:  invalid input syntax for integer: "24,34"

Agradecería el interés

A: Tendrías que hacer el uso de split_part para que te pueda dar los valores separados, pero deberías de estar seguro que solo tienes dos valores ademas de tenerlos en el orden correcto.
La función split_part de PostgreSQL se usa para dividir una cadena dada(1er parametro) en base a un delimitador(2do parametro) y seleccionar el campo deseado de la cadena(3er parametro), comienza desde la izquierda de la cadena.
Por ejemplo teniendo per_enc_id="24,34":
SELECT CAST (split_part(per_enc_id,',',1) AS integer)
FROM public.tb_periodo
WHERE per_estado = true
ORDER BY per_id DESC
LIMIT 1;

Suponiendo que toda la consulta va bien este deberia de resultar: 24.
En caso de querer el segundo elemento del split cambiamos split_part(per_enc_id,',',2).
En caso de necesitar todos los elementos de la cadena, necesariamente deberias de saber cuantos existen, en tu caso quizás siempre serán dos separados por una sola coma entonces:
SELECT CAST (split_part(per_enc_id,',',1) AS integer) as per_id, CAST (split_part(per_enc_id,',',2) AS integer) as enc_id
FROM public.tb_periodo
WHERE per_estado = true
ORDER BY per_id DESC
LIMIT 1;

Los as per_id y as enc_id depende de ti si los deseas o no.

A: prueba esto:
SELECT public.tb_encuesta.enc_nombre
FROM public.tb_encuesta
WHERE public.tb_encuesta.enc_id IN (
                                     SELECT CONVERT(per_enc_id,INT) // Este es el campo que contiene los valores
                                     FROM public.tb_periodo
                                     WHERE per_estado = true
                                     ORDER BY per_id DESC
                                     LIMIT 1
      )

A: Puedes usar: string_to_array. Es una función que:

Divide la cadena en elementos de matriz utilizando el delimitador
  suministrado y la cadena nula opcional.

Por ejemplo:
string_to_array(valor,separador
SELECT public.tb_encuesta.enc_nombre
FROM public.tb_encuesta
WHERE public.tb_encuesta.enc_id IN (
                                     SELECT string_to_array(per_enc_id,',')::int[]
                                     FROM public.tb_periodo
                                     WHERE per_estado = true
                                     ORDER BY per_id DESC
                                     LIMIT 1
      )


text:
Q: Как в asp.net сделать кнопку недоступной до тех пор, пока форма не пройдёт валидацию? Есть кнопка с текстовыми полями, к каждому из которых привязаны разные валидаторы. В результате, когда пользователь нажимает кнопку "отправить", то если текстовые поля заполнены в форме неверно, но валидаторы выдают ошибку.
А можно ли так сделать, чтобы кнопка "отправить" была бы неактивна до тех пор, пока пользователь не заполнит форму верно? (Использую обычные формы asp.net.)
Желательно, если это возможно, сделать это не с помощью JavaScript, а с помощью механизма валидаторов asp.net.
A: Примерно так:
    protected void Wizard1_NextButtonClick(object sender, WizardNavigationEventArgs e)
    {
        if (e.CurrentStepIndex == 0)
        {
            bool IsValidPassword = false;
            ///
            /// Validate user
            ///
            if (!IsValidPassword) e.Cancel = true;
        }
    }
    public bool IsValidPassword
    {
        get
        {
            return Valid.password(password.Text) &&
                   Valid.password(repassword.Text);
        }
    }
public class Valid
    {
        public static bool email(string email)
        {
            string pattern = "[.\\-_a-z0-9]+@([a-z0-9][\\-a-z0-9]+\\.)+[a-z]{2,6}";
            Match isMatch = Regex.Match(email, pattern, RegexOptions.IgnoreCase);
            return isMatch.Success;
        }
        public static bool username(string username)
        {
            string pattern = "[a-zA-Zа-яА-Я0-9]{5,50}";
            Match isMatch = Regex.Match(username, pattern, RegexOptions.IgnoreCase);
            return isMatch.Success;
        }
        public static bool password(string password)
        {
            string pattern = "(^[a-zA-Zа-яА-Я0-9-~!@#$%^&?*]{6,20})$";
            Match isMatch = Regex.Match(password, pattern, RegexOptions.IgnoreCase);
            return isMatch.Success;
        }
        public static bool lfName(string LastFirstName)
        {
            string pattern = "[a-zA-Zа-яА-Я]{2,50}";
            Match isMatch = Regex.Match(LastFirstName, pattern, RegexOptions.IgnoreCase);
            return isMatch.Success;
        }
        public static bool probel(string LastFirstName)
        {
            string pattern = "([\\s])";
            Match isMatch = Regex.Match(LastFirstName.Trim(), pattern, RegexOptions.IgnoreCase);
            return isMatch.Success;
        }
        public static bool phone(string phone)
        {
            string _phone = phone;
            _phone = Regex.Replace(_phone, @"[^\d]", "", RegexOptions.Compiled);
            string pattern = "([0-9]{10})$";
            Match isMatch = Regex.Match(_phone, pattern, RegexOptions.IgnoreCase);
            return isMatch.Success;
        }
        public static bool address(string address)
        {
            string pattern = "^[a-zA-Zа-яА-Я0-9-.,\\s]{5,300}$";
            Match isMatch = Regex.Match(address.Trim(), pattern, RegexOptions.IgnoreCase);
            return isMatch.Success;
        }
        public static bool sity(string sity)
        {
            string pattern = "^[a-zA-Zа-яА-Я-]{2,40}$";
            Match isMatch = Regex.Match(sity.Trim(), pattern, RegexOptions.IgnoreCase);
            return isMatch.Success;
        }
        public static bool index(string index)
        {
            string pattern = "^[0-9\\s]{3,10}$";
            Match isMatch = Regex.Match(index.Trim(), pattern, RegexOptions.IgnoreCase);
            return isMatch.Success;
        }
    }


text:
Q: On $\gcd(a-b, (a^n-b^n)/(a-b))$ Let $a,b$ be two coprime integers. Show that the gcd of the numbers $a-b, (a^n-b^n)/(a-b)$ divides $n$ for all $n\in\mathbb{N}$.

A: $$\frac{a^n-b^n}{a-b}\equiv a^{n-1}+a^{n-2}b+\cdots+b^{n-1}\equiv na^{n-1}\equiv nb^{n-1}\pmod{a-b}$$
Now apply Euclidean algorithm:
$$\gcd\left(\frac{a^n-b^n}{a-b},a-b\right)=\gcd\left(na^{n-1},a-b\right)=\gcd\left(nb^{n-1},a-b\right)$$
$$=\gcd\left(\gcd\left(na^{n-1},nb^{n-1}\right),a-b\right)=\gcd\left(n\gcd(a,b)^{n-1},a-b\right)$$
If $\gcd(a,b)=1$, then this is a divisor of $n$ by the definition of $\gcd$.
Your claim is not necessarily true if $a,b$ aren't coprime: e.g., let $(a,b,n)=(6,2,2)$.
I used some $\gcd$ properties that aren't difficult to prove.


text:
Q: Remove all Columns Based on Error in Column Header? I use index match or hlookup a lot to make sure I get only the columns I want for a certain file. Whatever I cannot match, I need to delete. What is the most efficient VBA script to remove all column headers of "#N/A"?

A: Use the Range.SpecialCells method with an xlCellType of xlCellTypeFormulas and specify xlErrors for the XlSpecialCellsValue  constant.
Sub del_err_cols()
    With Worksheets("Sheet1")
        On Error Resume Next
        With .Rows(1).SpecialCells(xlCellTypeFormulas, xlErrors)
            .Cells.EntireColumn.Delete
        End With
        On Error GoTo 0
    End With
End Sub

A: I think @Jeeped solution is better, but since you posted code here's my suggestion:
Sub del_err_colsG()

    Dim lastCol As Long, i As Integer

    lastCol = Cells(1, Columns.Count).End(xlToLeft).Column

    For i = lastCol To 1 Step -1
        If IsError(Cells(1, i).Value) Then Columns(i).Delete
    Next

End Sub


text:
Q: Devise i18n resource I'm trying to use locale to translate devise default language (english) to portuguese. I've found a pretty good resource for that, it's working for the most part, but whenever I have a pointer to the resource variable inside the locale it gives me the name in English. For example, I have a model called User, so when something goes wrong while updating this user I would like to show a flash message containing the right translation of "User", in this case "Usuário".

A: model names translations should be put to config/locales/pt.yml
pt:
  activerecord:
    models:
      user: Usuário

A: Devise doesn't use ActiveRecord translations, probably not to couple with any ORM.
I've just ended up overriding devise view adding translation with ActiveRecord keys:
h2 =t('.sign_up')
= simple_form_for(resource, :as => resource_name, :url => registration_path(resource_name), :html => {:class => 'form-vertical' }) do |f|
  = f.error_notification
  = display_base_errors resource
  = f.input :name, label: t('activerecord.attributes.user.name'), :autofocus => true
  = f.input :email, label: t('activerecord.attributes.user.email'), :required => true
  = f.input :password, label: t('activerecord.attributes.user.password'),:required => true
  = f.input :password_confirmation, label: t('activerecord.attributes.user.password_confirmation'), :required => true
  = f.button :submit, t('.sign_up'), :class => 'btn-primary'
= render "devise/shared/links"

For translating other messages (not field labels) you should try https://github.com/mcasimir/devise-i18n-views


text:
Q: C# Loose coupling to access to a property value I want to create loosely coupled classes (PlayerProfile and PlayersManager) and be able to access the value of the PlayerScore property (that's implemented in PlayerProfile) from PlayersManager(without knowing about PlayerProfile)
public class PlayerProfile : IPlayer
{
    int myScore = 520;

    public int PlayerScore
    {
        get
        {
            return myScore;
        }
    }
}

public interface IPlayer
{
    int PlayerScore { get; }
}

public class PlayersManager
{
    //There is any way to access here to the value of "PlayerScore" without creating an instance
    //of PlayerProfile and without depending in any way of the PlayerProfile (like IClass myClass = new PlayerProfile())?
}

PS: I don't know if using interfaces is the right way to do it or if there is another way.
Any idea how I can achieve this?
Thanks

A: To detail my comment:
public interface IClass
{
     int PlayerScore { get; }
}

public class ClassA : IClass
{
    public int PlayerScore { get; } = 250;
}

public class ClassB
{
    public ClassB(IClass aClass)
    {
        _aClass = aClass;
        // Now you can use _aClass.PlayerScore in the other methods
    }
    private readonly IClass _aClass;
}

Now after reading your updated code:
public interface IPlayerProfile
{
     int PlayerScore { get; }
}

public class Player : IPlayerProfile
{
    public int PlayerScore { get; } = 250;
}

public class PlayersManager
{
    public Add(IPlayerProfile profile)
    {
        // Use profile.PlayerScore
    }
}

A: You can use constructor injection. This is a Dependency Injection Design Pattern. See also: Dependency injection.
public class PlayersManager
{
    private readonly IPlayer _player;

    PlayersManager(IPlayer player)
    {
        _player = player;
    }

    public void Manage() // Example
    {
        int score = _player.PlayerScore;
        ...
    }
}

Dependency injection frameworks can create and inject the dependency automatically. They work like this (of course the details vary among the different dependency injection frameworks):
Create a dependency injection container in a static class
public static class DI
{
    public static SomeContainer Container { get; } = new SomeContainer();
}

At program startup register your services
DI.Container.Register<IPlayer, PlayerProfile>();
DI.Container.Register<PlayersManager>();

Then create a PlayersManager with:
// This automatically creates a `PlayerProfile` object and a `PlayersManager` object by
// injecting the player profile into the constructor of the manager.
var pm = DI.Container.Resolve<PlayersManager>();

It does the same as
IPlayer temp = new PlayerProfile();
var pm = new PlayersManager(temp);


text:
Q: Get first element of Series without knowing the index Is there any way to access the first element of a Series without knowing its index?
Let's say I have the following Series:
import pandas as pd

key='MCS096'
SUBJECTS = pd.DataFrame(
    {
        "ID": pd.Series([146], index=[145]),
        "study": pd.Series(["MCS"], index=[145]),
        "center": pd.Series(["Mag"], index=[145]),
        "initials": pd.Series(["MCS096"], index=[145]),
    }
)

Print out SUBJECTS:
print(SUBJECTS[SUBJECTS.initials==key]['ID'])
>>> 145    146
>>> Name: ID, dtype: int64

How can I get the value 146 here without using index 145?

A: Use iloc to access by position (rather than label):
In [11]: df = pd.DataFrame([[1, 2], [3, 4]], ['a', 'b'], ['A', 'B'])

In [12]: df
Out[12]:
   A  B
a  1  2
b  3  4

In [13]: df.iloc[0]  # first row in a DataFrame
Out[13]:
A    1
B    2
Name: a, dtype: int64

In [14]: df['A'].iloc[0]  # first item in a Series (Column)
Out[14]: 1


text:
Q: Google sign-in API without basic profile info I am trying to simply get the Google sign-in button working on my website, but I am stuck at the following step:
Getting profile information
As you can see, Google has taken an extremely straightforward task and made it impossible with contextless code snippets, and I am absolutely stuck. Right now, all I have done is put the following in the head of my HTML file:
<script src="https://apis.google.com/js/platform.js" async defer></script>
<meta name="google-signin-client_id" content="(I PUT MY CLIENT ID HERE ALREADY).apps.googleusercontent.com">

All I want to do is sign the user in WITHOUT requesting email address. My problem is the following:

*

*WHERE do I put the gapi.load('auth2', function()... code snippet? At the top level of my webpage's JavaScript file? In the body's onload function? In the onSignIn function? NONE of the above are working. I get an exception, or it says "gapi is not defined" or it says "auth2 is not defined" etc... And once that code snippet is in place, where do I put the if (auth2.isSignedIn.get()) code snippet? You'd think the geniuses at google would think to include this incredibly simple, vital information in their tutorial. Incredibly frustrating.

A: You can pass the url a callback function to be run when the javascript gets loaded.
<script src="https://apis.google.com/js/platform.js?onload=googleLoaded" async defer></script>

So in your code you can do
function googleLoaded(){
  // The script is ready to use.
  // gapi.load('auth2', function()...
}

found here https://developers.google.com/identity/sign-in/web/build-button


text:
Q: My  will not stay at the bottom of the page My <footer> tag will not seem to stay at the bottom of my page. I have tried several different techniques to fix it and none have worked.
I have included the link to my working site below.
http://stage.bmdigitalgroup.com/recipes.html

A: Based on your screenshot, it looks like your monitor's height is larger than your website's content or you have zoomed out a lot, so what you're seeing is totally normal. In a smaller monitor it would look just fine. You could add a min-height: rule to your sites container so it pushes the footer down to the specified value, but you need to figure out a min-height that makes sense to you and your users.
If you really want to make the footer always stick to the bottom regardless of the monitor's height or zoom level, then you could add the following rules - just keep in mind that in a page where there isn't much content, you will end up forcing users to scroll down for no reason if they need to get to the footer:
/*
 This rule is already in your stylesheet.
 I added it here just for reference.
*/
html, body {
  height: 100%;
}

/*
  This is the container that holds your whole site.
  You should use an id like "#container" or "#site" so this rule
  applies only to your site's main container.
*/
.container_12 {
  min-height: 100%;
}

A: i think you want to put your footer at bottom of the page i any resolution, if am i right than here is answer.
.footer {
position:absolute;
border:0px;
}

for more tips, tricks and tutorial visit - blog.klassicweb.com


text:
Q: Why does datetime('now') return 2 hours before real time in SQLite? I need that every time I make a change to a certain record from a table in SQLite, in the column lastChangedDate to set the time from France. Here is the structure of my table :
CREATE TABLE name(
    id VARCHAR(36) PRIMARY KEY
    , pos_report_id VARCHAR(36)
    , path_name VARCHAR(64)
    , photo_name VARCHAR(64)
    , from_scratch INTEGER DEFAULT 0
    , lastChangedDate DATETIME DEFAULT (DATETIME('now', 'utc', '1 hours'))
)

I see that DATETIME('now') returns 2 hours before my real time and DATETIME('now', 'utc', '1 hours') returns with 3 hours before my time. Why is happening this? I need the application to work in more countries, so I cannot use localtime.
Any idea how to solve this?

A: I have the same problem (using sqlite on Raspbarry Pi). 'utc' obviously only calcultes the difference according to location and timezone. I got it running like this:
select datetime(datetime('now', 'localtime'), 'utc');

Also check out the other variation of my VIEW [NOW] for sensor logging purpose.
CREATE VIEW [NOW] AS
SELECT datetime('now', 'localtime') as LOCAL,
datetime(datetime('now', 'localtime'),'utc') as UTC,
substr(datetime('now', 'localtime'),1,17)||'00' as TimeSlot_1min,
substr(datetime('now', 'localtime'),1,15)||'0:00' as TimeSlot_10min,
substr(datetime('now', 'localtime'),1,14)||'00:00' as TimeSlot_1h;

A: try datetime('now','localtime')  instead of DATETIME('now', 'utc', '1 hours')
Ok dont use default time for lastChangedDate
CREATE TABLE name(
    id VARCHAR(36) PRIMARY KEY
    , pos_report_id VARCHAR(36)
    , path_name VARCHAR(64)
    , photo_name VARCHAR(64)
    , from_scratch INTEGER DEFAULT 0
    , lastChangedDate DATETIME)
)

then when you want to add record to table, you can calculate the time in France and add this value to your database
//Calendar cal = Calendar.getInstance();
//Log.v("hata",String.valueOf(cal.get(Calendar.HOUR)));

Calendar c = Calendar.getInstance();

// It is local time
Log.v("time",String.valueOf(c.getTime()));

TimeZone z = c.getTimeZone();
int offset = z.getRawOffset();

if(z.inDaylightTime(new Date())){
    offset = offset + z.getDSTSavings();
}

// france is GMT2
int offsetHrs = offset / 1000 / 60 / 60;
int offsetMins = offset / 1000 / 60 % 60;

// Offsets
Log.v("time",String.valueOf(offsetHrs));
Log.v("time",String.valueOf(offsetMins));

c.add(Calendar.HOUR_OF_DAY, (-offsetHrs));
c.add(Calendar.MINUTE, (-offsetMins));

// FRANCE time
Log.v("time",String.valueOf(c.getTime()));


text:
Q: Difference between bind(Foo.class).to(Bar.class) vs bind(Foo.class).toInstance(new Bar()) What's the difference between bind(Foo.class).to(Bar.class) and bind(Foo.class).toInstance(new Bar());
Also, would fields be injected properly with the latter method of calling the constructor new Bar()?

A: bind(Foo.class).to(Bar.class) is a linked binding: you're telling Guice "whenever someone asks for a Foo, give them a Bar instead". You're not telling Guice how to create a Bar; this implies that there's an @Inject-annotated or public zero arg constructor and that you're allowing Guice to do everything it normally does including field injection. You're also not telling Guice whether to memoize the Bar instance and keep it around, meaning it will create a new Bar every time. (Note that this doesn't preclude you from bind(Bar.class).to(Baz.class) or bind(Bar.class).toInstance(new Baz()) if you wanted to; without one of those you're technically letting Bar be an implicit or JIT binding.)
bind(Foo.class).toInstance(new Bar()) is an instance binding. You're telling Guice "whenever someone asks for a Foo, give them this Bar instead". Guice doesn't ever try to create a Bar, so it doesn't try to inject constructor parameters, and it also doesn't ever try to create a different Bar: you always get the same one. UPDATE: Thanks Tavian, I'd forgotten that automatic injections do allow field injection on toInstance bindings. Note that none of this affects injection requests for Bar, just Foo.
So, the former allows injection and creates a new instance every time, and the latter lets you create instances manually and returns the same instance every time. Those can also be two separate decisions:

*

*To always return the same instance, you can mark the class with @Singleton, or make your binding .in(Singleton.class). See Scopes for more details and options. Guice creates the instance, so you have access to field injections.

*To let you create instances manually without field injection (but allowing for calls to static factory methods or custom initializer methods), bind to a Provider or create a @Provides method. Guice won't inject fields, because you've taken the creation on yourself.
Those provider/@Provides bindings can also be made Singleton, which is similar to toInstance above, but doesn't require you to create your instance at injector creation time.


text:
Q: Fober et al Lock-Free FIFO Queue: multiple consumers and producers? I was wondering if the fifo queue presented in Fober et al's paper http://nedko.arnaudov.name/soft/L17_Fober.pdf was a multiple consumer and produce fifo queue. If not, which is the best documented multiple consumer and producer FIFO queue?
Thanks

A: I haven't read the paper but I am making a big assumption here:  The paper uses the CAS (compare and swap) technique to achieve the concurrency.
Lock free does not mean block free.  The use of CAS will stall other threads, but at least one thread will be moving 'forwards' at all times.
Multiple producers all write to the same queue - that isn't a problem. The trickiness is the multiple consumers. If every consumer must access the data then I would implement that by multiple queues and the data would fall through to the next queue after being processed in one.  If you mean multiple consumers via threads then that would work on the above method

A: yes. read section '3.1 Linearizability'
the pop operation assumes that concurrent dequeue might happen. This means that multiple threads will be able to consume the queue.

A: I don't know the "Fober queue" but have already written lock-free FIFOs as ring buffers.
What is possible relatively easily is a "inter-lock free" queue which means that readers do not block writers and vice versa but multiple readers must be serialized and multple writers must be too.
So it is not exactly lock-free but still there is no locking/blocking between the readers and writers.
Maybe there are even better approaches that allow even less locking but maybe this will already help you.


text:
Q: fetching data from xmlhttprequest as an array in php Is there a way to fetch data from xmlhttprequest Object as an array (not using json & jquery) in php?
I have encountered a text saying that in order to handle ajax requests in php it will be first checked whether the input data is an array or not.
here's the code regarding the text:
  <?php
    $data = $_REQUEST['fld'];
    if ( is_array($data) )
        echo file_put_contents('db.csv', implode(",", $data) . "\n", FILE_APPEND) ? 1 : 2;
    else
        echo 3;//Error
  ?>

A: You must create the QUERY_STRING with encoded field-names and -values(let's assume you would send these fields via a form by using GET, the QUERY_STRING you would see in the address-bar of the browser you must create via JS ).
Example:
  var  name   = 'fld[]',//name of the fields
       enc    = encodeURIComponent(name),//encoded name
       query  = [],//array to store the data
       flds   = document.querySelectorAll('input[name="'+name+'"]');//the inputs

  for(var f = 0; f < flds.length; ++f){//iterate over the inputs
    //collect the data
    query.push([enc,encodeURIComponent(flds[f].value)].join('='));
  }
  //prepare the data
  query=query.join('&');

  //query now is ready for transmission:

  //either via GET:
  XMLHttpRequestInstance.open('GET', 'some.php?'+query, true);

  //or via POST:
  XMLHttpRequestInstance.send(query);

$_REQUEST['fld'] will be an array.
Note: when you send the data via POST you must also send appropriate headers, see:
Send POST data using XMLHttpRequest


text:
Q: Divide into view - C# MVC For example I want divide the result(this is number INT) of this in view:
@Model.Visits.Sum(i => i.TotalVisit)

for the number 60 for example.
Can it be divided in some way in the view? and how is the syntax?

A: You can do simple calculation on the razor view.

Division is is @(@Model.Visits.Sum(i => i.TotalVisit) / b)

Source

A: Yes, it's possible to use operators in Razor views. Just like Iman showed.
@(Model.Visits.Sum(i => i)/60)
It's important to keep track of your parentheses. Here's a useful link regarding Razor views. https://learn.microsoft.com/en-us/aspnet/web-pages/overview/getting-started/introducing-razor-syntax-c