text:
Q: return what when error in void * fun() /*
//i comment this block, please see the updates
void* fun_one(char *buffer, long length)
{
    if(NULL == buffer)
        return  xxx; //return what value here
    ...
}

fun_two()
{
    ...
    fun_one(image->buffer, image->length);
    ...
}
*/

If the error happened, I do not hope to exit the program but return to fun_two(). What should I do?
I know that return (void *)0; or return NULL;when succeed, but return what value when error?
links related:
void *

update:
but what if ti's a thread function ,such as
int main()
{
    ...
    pthread_create(&id1, NULL, (void*)myThread1, &param_struct);
    ...
}

void* myThread1(void* param)
{
    struct len_str* img = (struct len_str*)param;
    if(NULL == img->buf)
        return xxx;    //return what value here
    if(0 == img->len)
        return xxx;
    ...
}

links related:
pthread_create
the return value of myThread1() is void *
what value should return if the error occur

A: Instead of returning a pointer, return a value of int type.
A return of 0 means all ok.
A return of 1 means NULL pointer passed in.
A return of 2 means invalid length.
...
int fun_one(char *buffer, long length) {
    if (buffer == NULL) return 1;
    if (length == 0) return 2;
    if (length < 0) return 3;
    /* ... */
    return 0;
}

For extra clarity (???), you can use enums
enum fun_one_errors {FO_OK, FO_NULL, FO_ZERO, FO_NEG};
return FO_ZERO;

A: You are struggling with the "design" of your interface. What do you need to pass to the function, what does it need to return and how do you signal an error.
Normally if you return a pointer, the pointer value zero (NULL) means an error. If you want to pass more information, you can use an auxiliary variable that you set to one of your error codes. This will be a global variable or a (pointer to) a variable:
int my_errcode;
...
if ((p=fun_one(buf, len))==NULL) printf("error %d\n",my_errcode);

As an alternative, you return the void * pointer as a parameter (you must use a double indirection now) and let the function return signal success, or failure and the type of failure:
if ((my_errcode=fun_one(buf, len, &p))!=0) printf("error %d\n",my_errcode);

So it is up to you...

A: In your thread function, you would dynamically allocate a variable to store the return value.  You would set that value and return the pointer.
Then when you call pthread_join, you'll receive the pointer to that variable, which you would then cast and dereference to read the value, and free it when you're done.
void* myThread1(void* param)
{
    int *rval = malloc(sizeof(int));
    if (rval == NULL) {
        perror("malloc failed");
        exit(1);
    }
    struct len_str* img = (struct len_str*)param;
    if(NULL == img->buf) {
        *rval = 0;
        return rval;
    }
    if(0 == img->len) {
        *rval = 1;
        return rval;
    }
    ...
}

int main()
{
    ...
    pthread_create(&id1, NULL, (void*)myThread1, &param_struct);
    ...
    void *rval;
    pthread_join(id1, &rval);
    printf("rval = %d\n", *(int *)rval);
    free(rval);
}

A: Well, when returning a pointer you have normally the problem of what to do if the function execution resulted in an error?
The classical approach is to reserve a special value (NULL, or 0 in C++) to represent this kind of error, and use a global to represent the different error values you can have.
But, what if you want a reentrant module to be able of multithreading? Well, the pointers have the problem that everywhere they point to is a possible source of trouble if that place happens to be occupied by a non-useless variable.
But we have a different approach.  Just create dumb variables (not used for anything else) to hold the addresses of nothing.  This way you can reserve several pointer values (the addresses of those variables) to represent the proper error codes.  As the places they have been located by the compiler cannot be used for anything else, they can be used to hold (not to store) the address of something special to you.
int error_001_placeholder;
int error_002_placeholder;
int error_003_placeholder;

...

if (condition_1) return &error_001_placeholder;
if (condition_2) return &error_002_placeholder;
if (condition_3) return &error_003_placeholder;

Then, you'll be able to check for different invalid return pointers, just by checking if they belong to this set of pointers.
Even more, if you want to do generic error check, you can reserve a global array, and return individual cells for different errors, finally to generic check if the returned value is an error, you can just check if
returned_value >= errors_array && returned_value < errors_array + erros_array_size.


text:
Q: How to verify installed application in runtime to prevent phishing attack? I have a payment application in my device, my application connect to that application's service to get a pending-intent for launch payment activity and then listen to result in onActivityResult() method.(similar to In-App-Purchase scenario)
I set package name for payment intent. but you know, it's not guarantee payment application is trusted. if some one install fake application through unknown source with same package name and same aidl-service implementation then it can give me pending-intent and phishing my user info.
I verify payment result with some mechanism and that only safe my application from fake payment result but my application user enter their data in phisher application. (this paragraph say my problem is not trusting response of payment application, my problem is trusting payment application before launch their activity)
I know some approach that i can check other application signature and public key. if Android OS guarantee that public key and signature is read-only and matched for installed application, i can rely on that and check public key of payment application before sending intent to that.but i guess those is not ready-only and check match only in installing.
any suggestion (similar or different approach) for prevent phishing attack ?
Updated:
about 50% of application's user install application from my corporation website directly (Unknown-Source).

A: Android offers a native method to verify if an app has been installed from Play Store, even Amazon App Store. But does it work on other apps?
Take a look at the method:
PackageManager.getInstallerPackageName(String packageName) (Documentation)
Fortunately for you, getInstallerPackageName accepts a String package name, which means you can feed it your neighbor-app's package id, and have it return the package name that installed it!
This example will tell you if your neighbor-app was installed by Play Store, aka com.android.vending:
if(context.getPackageManager().getInstallerPackageName("com.untrusted.app") ==
  "com.android.vending") {                          //   ^^^ CHANGE ^^^

  //Verified; app installed directly from Play Store
}

Amazon app store has an odd package name:
if(context.getPackageManager().getInstallerPackageName("com.untrusted.app") ==
  "com.amazon.venezia") {

  //Verified; app installed directly from Amazon App Store
}

This should be everything you need, hope it helps!

A: What you are looking for is a combination of app signatures and permissions. To clarify, this will only work if you own both applications and can sign them with the same key.
According to the docs:

"signature": A permission that the system grants only if the requesting application
  is signed with the same certificate as the application that declared
  the permission. If the certificates match, the system automatically
  grants the permission without notifying the user or asking for the
  user's explicit approval.

This means that the Android OS itself enforces that the signatures of the two applications must match in order for the permission to be granted. This is what you want, since the permission will not be granted if someone tries to spoof your app. Since they cannot possibly sign their app with your private key, there is no way they can forge your signature.
To create a permission, in your Manifest for the application providing the payment service, you should declare it like this:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapp.paymentservice" >

    <permission android:name="com.example.myapp.paymentservice.permission.PAYMENT"
        android:label="@string/permission_payment_label"
        android:description="@string/permission_payment_description"
        android:protectionLevel="signature" />
    ...

Then, when you declare your service, protect it with the android:permission that you declared:
    ...
    <service android:name=".BillingService"
        android:permission="com.example.myapp.paymentservice.permission.PAYMENT" />
</manifest>

Finally, you declare in your client application(s) that you use that permission:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapp.clientapp" >

    <uses-permission android:name="com.example.myapp.paymentservice.permission.PAYMENT" />
    ...
</manifest>

As long as the two applications are signed with the same signing key, the OS will grant the permission. For more information, check out http://developer.android.com/guide/topics/security/permissions.html#defining and http://developer.android.com/guide/topics/manifest/permission-element.html

A: What if main app get signature of payment app via package manager api and validate it (by whitlist of signatures, for example)? The validation process can also happened in main app server.
EDIT:
somthing like that
        List<byte[]> whitelist = ... ; // load from config or something...

        PackageManager pm = this.getPackageManager();
        String packageName = "payment.app.package.name";

        PackageInfo packageInfo = pm.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
        Signature[] signatures = packageInfo.signatures;

        for (Signature sig : signatures) {
            InputStream input = new ByteArrayInputStream(sig.toByteArray());
            CertificateFactory cf = CertificateFactory.getInstance("X509");
            X509Certificate cert = (X509Certificate) cf.generateCertificate(input);

            PublicKey pb = cert.getPublicKey();
            if (! whitelist.contains(pb.getEncoded())) {
                throw new Exception("public key is not valid");
            }
        }

redpajama_set_name: RedPajamaStackExchange


text:
Q: $(R,\mathcal m)$ be a Noetherian local ring and let $P$ be a prime ideal of $R$. If $P^2$ is a prime ideal of $R$, then $P=0$
Let $(R,\mathcal m)$ be a Noetherian local ring and let $P$ be a prime ideal of $R$. If $P^2$ is a prime ideal of $R$, then $P=0$.

I was thinking to use Nakayama lemma as:
$R_P$ is local with $PR_P$ as its maximal ideal. Also as $P^2$ is prime so $P^2R_P$ will also be the same maximal ideal. Then $PR_P=P^2R_P= P.PR_P$. Using Nakayama lemma  here, we get $PR_p=0$. This implies $P=0$, as $PR_P$ is finitely generated.
Is it correct? Otherwise please provide some hints.
Thanks in advance.

A: You do not need to further localize, since your ring is already local.
We have $P^2 \supset P \cdot P$, by the prime property we get $P^2 \supset P$. In particular $P \supset mP \supset P^2  \supset P$, hence $mP=P$. Nakayama finishes the proof.

A: Let $x\in p.$ Then $x^2\in p^2$ and since $p^2$ is prime we have $x\in p^2.$ So $p= p^2,$ and by Nakayama $p=0.$


text:
Q: I want to use JSON in Python to save users and password This is diary writer with users login requirement. Now I need to save the users and passwords and be able to read them every time I rerun the program because not every time the user will create their account.
name=[]
password=[]
diary=""
x =""
namee=""
passwordd=""

file = open("user.txt","a")
print("welcome to world!")
while x != "q":
    print("1) Enter :1 sign in!")
    print("2) Enter :2 create new soul?")
    print("3) Enter :q exit!")
    x = input("what do you want?\n")
    if x == "1":
        namee=input("Enter your name!")
        passwordd=input("Enter your password!")
        if namee in name:
            if passwordd not in password or name.index(namee) != password.index(passwordd) :
                print("wrong password")
            else:
                file.write("\n\n\n\n")
                file.write(namee)
                file.write("\n\n")
                diary = input("write your diary\n")
                file.write(diary)

        else :
            print("can't find your name here.\n please create new soul!.")
    elif x =="2":
        namee = input("enter you name!")
        if namee in name:
            print("user name taken")
        else:
            passwordd = input("enter your password")
            name.append(namee)
            password.append(passwordd)

        elif x=="q":
        print("thank you for your time")
    else :
        print("please enter valid value!")
print("thanks.!")
print(name,password)
file.close()

A: To get from a json file the information that you are looking to store (two lists), you can simply import json and load the file, and query it like a dictionary.
Imagine having a json like this:
{
    "users": ["Bacon", "Eggs", "Toast"],
    "passwords": ["Please don't do it this way though!", "runny", "buttered"]
}

One can simply:
import json

path_to_json = "./stackoverflowexample.json"

with open(path_to_json, "r") as handler:
    info = json.load(handler)

users = info["users"]
passwords = info["passwords"]

print("User 0 '{}', has password '{}'".format(users[0], passwords[0]))

This is a very insecure method of storing passwords, it is very inefficient, and you'll likely run into consistency issues at some point.
A much better method of storing passwords would be in a database, that would allow you to query for the information you wanted more efficiently, and to salt and hash the passwords when you get them so they aren't stored as human readable strings.
Example:
import sqlite3
import hashlib
import uuid

user_table_definition = """
CREATE TABLE users (
    username TEXT,
    salt TEXT,
    hpassword TEXT
)"""
add_user_sql = "INSERT INTO users VALUES ('{}','{}','{}')"

connection = sqlite3.connect("./stackoverflowdb.db")
cursor = connection.cursor()

cursor.execute(user_table_definition)

# Add incoming user
username = "Bacon"
password = "This is a little better, but this is just an outline..."

salt = uuid.uuid4().hex
hashedpassword = hashlib.sha512((salt + password).encode("UTF-8")).hexdigest()

cursor.execute(add_user_sql.format(username, salt, hashedpassword))

# Check incoming user

username = "Bacon"
password = "This is a little better, but this is just an outline..."

row = cursor.execute("SELECT salt, hpassword FROM users WHERE username = '{}'".format(username)).fetchone()

salt, hpassword = row  # Unpacking the row information - btw this would fail if the username didn't exist

hashedIncomingPwd = hashlib.sha512((salt + password).encode("UTF-8")).hexdigest()

if hashedIncomingPwd == hpassword:
    print("Winner winner chicken dinner we have a live one!")
else:
    print("No access for you")

This is only showing you the lines that do the core of what you want, you should move some of these lines into functions, you couldn't call this code twice because the table shall already be created and other issues. For one, you don't have to use sqlite!
SQL is a really powerful thing to learn and considering that your question looks kind of like a hobby, I would recommend looking into as you go along. Best of luck.


text:
Q: How to create partial copy of DB Objects (tables, functions, stored procedures, etc) in SQL Server? For a join project with a 3rd party I need to build a new database in SQL Server (2014SP2), which will include only main objects from our current one and without any data, apart from some basic settings I will INSERT INTO later.
I maintain our DDL scripts on GitHub, so on a daily basis every new script will be saved there as well as on our local SQL Server with .sql extension and then will be picked up and processed by my stored procedure mySP across our test DB's. Once everyone is happy and things have been tested, I will send the script to our DBA's to apply in live.
In order to address this new request I was thinking to implement same approach:

*

*To have all the relevant scripts saved on the new SQL Server.

*Run stored procedure mySP, which will pick them up
and process one by one: will execute the scripts, record the
errors (I already know there will be some, e.g. foreign keys on
tables, which may not exist yet), send me an email with the list of
errors and then I will have to manually fix them (e.g. re-build
those foreign keys).

My question if there is any better approach, please?
Example of my current process :
Step 1 - save a script with .sql extension on SQL Server. example for such a script is below
/*********************************************************************/
--   Date   |Developer's Name    | Version | Description
--27/04/2018| Mr Smith           |    12   | Added new column myColumn
-----------------------------------------------------------------------
ALTER TABLE myTable
ADD myColumn BIT DEFAULT 0 NOT NULL;

Step 2 - my stored procedure is scheduled to run every hour and will pick up all the .sql files from the predefined location and process them, sending me the email. The script is here: http://www.sqlfiddle.com/#!18/e3309/1
Any advice will be much appreciated.


text:
Q: SVG create elements on path phenomenon I have a problem with creating "points" on path, if I'm creating more than 2 "points" they begin to "merge" and on a simple straight path everything is OK.
<path id="path" stroke="black" d="M436.3,583.7C561.4,788.6,726.6,968.7,921,1109.7c99.8,72.4,208.5,134.7,326.5,172.1c127.2,40.3,261.7,48.9,394.4,48
c127.8-0.9,256.5-9.7,381.3-38.6c122.6-28.4,234.3-79.4,340.5-146.2c100.8-63.5,196.8-135.2,303.6-188.6
c107.3-53.6,225.3-84.3,345.6-84.6c214.7-0.5,425.8,102.5,541.2,286.8c13.8,22.1,26,45.1,36.6,68.9c0.8,1.7-1.8,3.3-2.6,1.5
c-92.9-208.4-306.1-339.5-530.6-353c-126-7.6-252.6,18.9-366.7,72.3c-109,51-206.3,122.8-307.2,187.5
c-102.1,65.5-208.5,119-326.3,150c-120.3,31.7-245,43.3-369,46.2c-128,3-257.8-0.9-382.8-31.1c-118.9-28.8-229.5-83.4-331.2-150.7
c-194.1-128.7-362.2-298-492.7-490.7c-16.5-24.4-32.4-49.2-47.7-74.3C432.7,583.6,435.3,582.1,436.3,583.7L436.3,583.7z"/>

<script type="text/javascript"><![CDATA[

var el        = document.getElementById("path");
var len       = parseInt(el.getTotalLength());
var userValue = parseInt(prompt('Enter Integer from 2 to 100:'));
var modulo    = parseInt(len / userValue);

for (i = 0; i < len; i++) {

if (i % modulo ) { continue; }

var dot = document.createElementNS("http://www.w3.org/2000/svg", "circle");
dot.setAttributeNS(null, "cx", el.getPointAtLength(i).x );
dot.setAttributeNS(null, "cy", el.getPointAtLength(i).y );
dot.setAttributeNS(null, "r", '25');
dot.setAttributeNS(null, "fill", "red");
document.getElementById("container").appendChild(dot);
}]]></script>

Screenshot 1
Screenshot 2

A: In the HTML: The path follows some curves out and then follows the same curves back to the starting point which creates a closed path. The first and last circle will be at the same point. The second and next to last circle will be at the same place. And so on. Did you intend to create an open path that does not loop back on itself? For example...
<path id="path" fill="none" stroke="black" d="M436.3,583.7C561.4,788.6,726.6,968.7,921,1109.7c99.8,72.4,208.5,134.7,326.5,172.1c127.2,40.3,261.7,48.9,394.4,48
    c127.8-0.9,256.5-9.7,381.3-38.6c122.6-28.4,234.3-79.4,340.5-146.2c100.8-63.5,196.8-135.2,303.6-188.6
    c107.3-53.6,225.3-84.3,345.6-84.6c214.7-0.5,425.8,102.5,541.2,286.8c13.8,22.1,26,45.1,36.6,68.9c0.8,1.7-1.8,3.3-2.6,1.5"/>

In the JavaScript: The total distance of the path (i.e. getTotalLength()) is a float. The distance between circles (i.e. getTotaleLength()/(uservalue-1)) is a float. The code was converting both of these values to integers which loses the decimal part of the values which messes up the later calculations. One solution is to step i from 0 to userValue - 1 and then calculate distance along path of the ith circle. For example...
var el = document.getElementById("path");
var totalLength = el.getTotalLength();
var userValue = parseInt(prompt('Enter Integer from 2 to 100:'), 10);
for (i = 0; i < userValue; i++) {
    var distance = (i / (userValue - 1)) * totalLength;
    var dot = document.createElementNS("http://www.w3.org/2000/svg", "circle");
    dot.setAttributeNS(null, "cx", el.getPointAtLength(distance).x );
    dot.setAttributeNS(null, "cy", el.getPointAtLength(distance).y );
    dot.setAttributeNS(null, "r", '25');
    dot.setAttributeNS(null, "fill", "red");
    document.getElementById("container").appendChild(dot);
}

Note: When calling parseInt() function, it is a good practice to specify radix.


text:
Q: mysqldump: MySql backup user is not able to connect using password I have created a mysql user using following command:
CREATE USER 'backupuser'@'localhost' IDENTIFIED BY 'password';

I have given him permissions using following command:
GRANT EVENT, LOCK TABLES, SELECT, SHOW DATABASES, RELOAD, REPLICATION CLIENT ON *.* TO 'backupuser'@'localhost' IDENTIFIED BY 'password';

But when I try to do database dump using following command it does not work:
sudo mysqldump -ubackupuser -ppassword --all-databases > all_db_backup.sql

It says: mysqldump: Got error: 1045: Access denied for user 'backupuser'@'localhost' (using password: YES) when trying to connect
But if I try to connect without using password then it asks for password and then it works.
I am creating  a backup script so I have to pass the password in command. Can you please help how to make my backupuser to connect using mysql dump?

A: Does your password contain any characters that are special to the shell? Like ; & ! or space, quotes, etc.? You might have to quote the password.
But regardless, I recommend you do NOT put your passwords on the command-line. Anyone who can run ps on your server can therefore see your password in plain text.
Instead, put the user and password in an options file. That is, save a small file with the following content:
[mysqldump]
user = backupuser
password = ...

Of course write your own password where I put "...".
Change the permissions on the file so no one can read it except the user who runs your backups.
Then reference the options file when you run mysqldump:
mysqldump --defaults-file=myopts.cnf --all-databases ...

That way the password is not visible in the server's process list. Also there is no worry about special characters in your password.
P.S.: I'm not sure why you use sudo to run your backup. That should not be necessary.


text:
Q: Winedt PDFLaTeXify not working I moved to a new machine and can't get texify to work. Everything else works - I can use PDFLaTeX to run the .tex document, run biber, then PDFLaTeX repeatedly to get the desired PDF. But PDFLaTeXify gives me the error "object 'errorstopmode' not found."
Options: Execution modes: Diagnosis says my Miktex installation appears to be fine.
Any suggestions?
I'm running Winedt v 10.3, build 20180507. LaTeXify is installed and up to date.
Thanks!
Gordon
Here are the settings for PDFTeXify. Are any others needed?

This setup allows me to use knitr directly in WinEdt, to edit/compile .Rnw documents (combination R code and output + LaTeX). One source for this instruction is https://yihui.org/knitr/demo/editors/.
But perhaps that's outmoded. I see that the RManager plugin has no such instructions. Maybe I should experiment resetting this to the default settings. Do you know what they are?
Well, that was a silly request. I see how to reset to default - and it's now more or less working. Doesn't seem to actually run Biber but I'll fool around a bit - at least I'm on the road to getting it fixed!

A: For anyone else that runs into this problem (PDFLaTeXify not running due to setup w/ RManager), it's actually a simple fix: forget the ancient settings. Things will now run close to out of the box. Settings that are now working for me are below.
And these for Biber to run automatically as part of the process.
Many thanks to Ulrike Fischer for setting me on the road towards the solution.


text:
Q: Reloading UITableView Container from method I am trying to reload my tableview with the parameters received from changing a UIDatepicker. Currently I have the following method that captures the data and sends it to the UIButton (which works). I am trying to reset the container view that houses the UITableViewController which is called DisplayTableViewController but it is not reloading the NSFetchController. Any suggestions about how to debug or fix this issue?
-(void)changeDate:(UIDatePicker *)sender {

    //NSDate Formatter
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"ddMMyyyy"];

    //Convert to string
    NSString *stringFromDate = [dateFormatter stringFromDate:sender.date];

    //Send to UIButton
    [dateLabel setTitle:stringFromDate forState:UIControlStateNormal];

    DisplayTableViewController *tbc = (DisplayTableViewController *)self.childViewControllers[0];
    [tbc.tableView reloadData];

}

EDIT
 if ([[segue identifier] isEqualToString:@"ShowDisplayResults"])
    {
        //Format Date for Seague
        NSDateFormatter *todaysdate = [[NSDateFormatter alloc] init];
        [todaysdate setDateFormat:@"ddMMyyyy"];
        //Convert to string for Seague
        NSString *stringFromDate = [todaysdate stringFromDate:[NSDate date]];
        // Store the text we entered to dateSeague
        dateSeague =stringFromDate;
        // Get reference to the destination view controller
        DisplayTableViewController *targetVC = [segue destinationViewController];
        // Pass any objects to the view controller here, like...
        targetVC.dateSeague = dateSeague;
        targetVC.Ex = self.Ex;

    }

NSFETCHCONTROLLER IN CONTAINER
- (NSFetchedResultsController *)fetchedResultsController {
    NSLog(@"Test Date for second seague = %@", dateSeague);
    if (_fetchedResultsController != nil) {
        return _fetchedResultsController;
    }
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    //Query Entity
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"WorkoutDetails"inManagedObjectContext:managedObjectContext];
    //Fetch Entity
    [fetchRequest setEntity:entity];

    //Sort Returned Values
    NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"weight" ascending:NO];
    //Fetch Sorted Array
    [fetchRequest setSortDescriptors:[NSArray arrayWithObject:sort]];
    //Set Return Size
    [fetchRequest setFetchBatchSize:20];

    //Predicate Results Based on ID
    NSPredicate *sortName = [NSPredicate predicateWithFormat:@"exid == %@", Ex.name];
    //Get NSDate format from String
    NSString *stringFromDate = dateSeague;
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    //Convert Back to NSDate
    [df setDateFormat:@"ddMMyyyy"];
    NSDate *inputedDate = [df dateFromString: stringFromDate];
    //Set Predicate
    NSPredicate *sortDate = [NSPredicate predicateWithFormat:@"date == %@", inputedDate];
    //Compound Predicate Array
    NSPredicate *placesPredicate = [NSCompoundPredicate andPredicateWithSubpredicates:[NSArray arrayWithObjects:sortName, sortDate, nil]];
    //Fetch Predicate Compound Array
    [fetchRequest setPredicate:placesPredicate];
    //Continue Fetching!
    NSFetchedResultsController *theFetchedResultsController =
    [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
                                        managedObjectContext:managedObjectContext sectionNameKeyPath:nil
                                                   cacheName: nil];
    self.fetchedResultsController = theFetchedResultsController;
    _fetchedResultsController.delegate = self;

    return _fetchedResultsController;

}

A: First of all self.childViewControllers[0] will get you the first view controller on the view controller hierarchy and you want this only if you have one view controller that contains another view controller.
Second it's not a good practice to use this approach since you don't really know the state of the view controller when you call this and it's possible that the view controller at that index won't be the same class as you expected.
So I suggest that you implement a delegate for your view controller or view that holds the date picker and when the date is changed and you do all the things that you want to do with the date, call the delegate. If you don't want to do anything with the date, you just want to pass it to the view controller, then you can set the date picker delegate to be your DisplayTableViewController
As a side note, I don't know the hierarchy that you have right now and if you don't find my answer helpful please add more details to your question (the hierarchy and the flow that you want to get)

A: Are query params for the NSFetchRequest of the NSFetchController changing?   If so, make sure that you use deleteCacheWithName if it is using a cache, and then reconfigure the NSFetchController.


text:
Q: Newest Chrome 85 removing 3rd party cookie with SameSite=None and secure The latest version of Chrome (85.0.4183.83) is removing my 3rd party cookies, although they are set as SameSite=None; secure; - how can this be, and am I the only one experiencing this?
They are also HttpOnly, if that matters, and it happens when setting the cookie through a Chrome Extension.

A: Chrome 85 seems to be removing 3rd party cookies set by Chrome Extensions, regardless of SameSite attribute. It doesn't seem to be documented, so it may be unintended.


text:
Q: Error " MemoryError" while using MultiProcessPool to get count of files inside a folder i have a code which counts the number of file inside a folder using MultiProcessPool , but now it is throwing me Memory Error , am new to the concept of multiprocessing and multithreading . I wrote code for MultiProcessing and MultiThreading for doing the same function . Both are throwing me error :
Code for Multiprocessing:
def findfiles(taggedrootdir,files):
    taggedrootdir = pathlib.Path(taggedrootdir)

    if ((len(files)) > 0):
        oldest_file = (
            min([f for f in taggedrootdir.resolve().glob('**/*') if f.is_file()], key=os.path.getmtime))
        newest_file = (
            max([f for f in taggedrootdir.resolve().glob('**/*') if f.is_file()], key=os.path.getmtime))
        c_time_of_oldest = os.path.getctime(oldest_file)
        local_time_of_oldest = time.ctime(c_time_of_oldest)

        c_time_of_newest = os.path.getctime(newest_file)
        local_time_of_newest = time.ctime(c_time_of_newest)

    elif ((len(files)) == 0):
        local_time_of_oldest = "No File in Path"
        local_time_of_newest = "No File in Path"

    # print("{} --> {} --> {} --> {}".format(len(files), root,local_time_of_oldest,local_time_of_newest))
    fileStatsObj = os.stat(taggedrootdir)
    modificationTime = time.ctime(fileStatsObj[stat.ST_MTIME])

    folderstat = {}
    folderstat['FolderPath'] = taggedrootdir
    folderstat['count'] = len(files)
    folderstat['OldestTimeStamp'] = local_time_of_oldest
    folderstat['NewestTimeStamp'] = local_time_of_newest
    folderstat['FolderModificationTime'] = modificationTime

    return folderstat

if __name__ == '__main__':

    roots = r'Path'

    start_time = time.time()

    args = ((root, files) for root, dirs, files in os.walk(roots))

    for result in Pool().starmap(findfiles, args):

        with open('MultiProcessPool.csv', 'a') as f:
            for key in result.keys():
                f.write("%s,%s\n" % (key, result[key]))

    print('--- %s seconds ---' % (time.time() - start_time))

Error:
multiprocessing.pool.RemoteTraceback:
"""
Traceback (most recent call last):
  File "C:\Local\Programs\Python\Python38-32\lib\pathlib.py", line 713, in __str__
    return self._str
AttributeError: _str

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Local\Programs\Python\Python38-32\lib\pathlib.py", line 715, in __str__
    self._str = self._format_parsed_parts(self._drv, self._root,
  File "C:\Local\Programs\Python\Python38-32\lib\pathlib.py", line 695, in _format_parsed_parts
    return drv + root + cls._flavour.join(parts[1:])

Code for MultiThreading :
root = roots = r'Path'
count_of_file = 0

import pathlib
noOfFiles = local_time_of_oldest = local_time_of_newest= 0
subdir=""
N = 0
def Count_files_in_subd():
    for root, dirs, files in os.walk(roots):
        taggedrootdir = pathlib.Path(root)

        thread = threading.Thread(target=findfiles, args=(taggedrootdir,files,))
        threads.append(thread)
        thread.start()

        for thread in threads:
            thread.join()

def findfiles(taggedrootdir,files):
    if ((len(files)) > 0):
        oldest_file = (
            min([f for f in taggedrootdir.resolve().glob('**/*') if f.is_file()], key=os.path.getmtime))
        newest_file = (
            max([f for f in taggedrootdir.resolve().glob('**/*') if f.is_file()], key=os.path.getmtime))
        c_time_of_oldest = os.path.getctime(oldest_file)
        local_time_of_oldest = time.ctime(c_time_of_oldest)

        c_time_of_newest = os.path.getctime(newest_file)
        local_time_of_newest = time.ctime(c_time_of_newest)

    elif ((len(files)) == 0):
        local_time_of_oldest = "No File in Path"
        local_time_of_newest = "No File in Path"

    fileStatsObj = os.stat(taggedrootdir)
    modificationTime = time.ctime(fileStatsObj[stat.ST_MTIME])

    folderstat = {}
    folderstat['FolderPath'] = taggedrootdir
    folderstat['count'] = len(files)
    folderstat['OldestTimeStamp'] = local_time_of_oldest
    folderstat['NewestTimeStamp'] = local_time_of_newest
    folderstat['FolderModificationTime'] = modificationTime

    with open('MultiThreading.csv', 'a') as f:
        for key in folderstat.keys():
            f.write("%s,%s\n" % (key, folderstat[key]))
    # print(folderstat)

start_time = time.time()
Count_files_in_subd()
print("--- %s seconds ---" % (time.time() - start_time))

Error:
Exception in thread Thread-3:
Traceback (most recent call last):
  File "C:\Local\Programs\Python\Python38-32\lib\pathlib.py", line 758, in __hash__
    return self._hash
AttributeError: _hash

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Local\Programs\Python\Python38-32\lib\pathlib.py", line 746, in _cparts
    return self._cached_cparts
AttributeError: _cached_cparts


text:
Q: How to preserve date format when creating an Excel file? I have an .xlsx file that I import into Python and create a Pandas dataframe. One of the columns in the .xlsx file is formatted as a date, mm-dd-yyyy and gets imported like that. I then delete some unneeded columns from that dataframe and export that dataframe using the xlsxwriter engine to create another Excel file.
writer = pd.ExcelWriter('Sample_Master_Data_edited.xlsx', engine='xlsxwriter', date_format='mm/dd/yyyy')

When I do that, the date column's format changes and time automatically gets added to the date column. The cells in the column then follow this format, yyyy-mm-dd hh:mm:ss.
I found a potential solution but when I tried the code below,
df.set_index(df.index.map(lambda x: x.strftime('%m/%d/%Y'))).to_excel()

I get the error
AttributeError: 'int' object has no attribute 'strftime'

I also read that it isn't possible to format any cells that already have a default format applied.
Is this a lost cause? How can I preserve the pre-existing date format upon export as an .xlsx file?

A: Try this:
writer = pd.ExcelWriter('Sample_Master_Data_edited.xlsx', engine='xlsxwriter',
                        date_format='mm/dd/yyyy', datetime_format='mm/dd/yyyy')


text:
Q: TaxonomyFieldType is not installed properly? It is Image library in one SharePoint foundation site, When I am changing its view from Thumbnail to All Item, it is giving following error.

Also, When I am saving site as a template, it is giving

Error exporting the list
Sorry, something went wrong: Error exporting the list named
"CompanyAnnoucements" at the URL: CompanyAnnoucements TECHNICAL
DETAILS: Troubleshoot issues with Microsoft SharePoint Foundation.
Correlation ID: b270059e-a84e-e06c-462f-77d05095cd09

A: Managed metadata service is not available in SharePoint Foundation. You need to delete the taxonomy fields before you can save the site as a template.

For more information -

*

*SharePoint OnPremise Features

*Source


text:
Q: Is that sentence is correct I wonder that following sentence is correct way to use?
It is updated as the user inputs new information.

Does As adverb is used in right way in that sentence?
Or Do I have to use this sentence like:
It is updated when the user inputs new information.

So which one is more formal?
 Thanks

A: "as" implies that it is updated at the same time as the user is entering the information.
"when" can have the same meaning as "as" but can also mean after the user has finished inputting the information.
see also the ell stackexchange

A: The word "as" introduces a clause, so it is a conjunction and not an adverb.
I would prefer "when" or "whenever". "as" is a multifunction word and it may happen that a reader has to read your sentence two times to get the structure clear, especially as you have two words, "user" and "inputs" that can be taken for nouns at the first reading. On second reading one understands that "inputs" is a verb form.


text:
Q: How to read file capabilities using Python? On Linux systems root privileges can be granted more selectively than adding the setuid bit using file capabilities. See capabilities(7) for details. These are attributes of files and can be read using the getcap program. How can these attributes be retrieved in Python?
Even though running the getcap program using e.g. subprocess for answering such a question is possible it is not desirable when retrieving very many capabilities.
It should be possible to devise a solution using ctypes. Are there alternatives to this approach or even libraries facilitating this task?

A: Python 3.3 comes with os.getxattr. If not, yeah... one way would be using ctypes, at least to get the raw stuff, or maybe use pyxattr
For pyxattr:
>>> import xattr
>>> xattr.listxattr("/bin/ping")
(u'security.capability',)
>>> xattr.getxattr("/bin/ping", "security.capability")
'\x00\x00\x00\x02\x00 \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'

For Python 3.3's version, it's essentially the same, just importing os, instead of xattr. ctypes is a bit more involved, though.
Now, we're getting the raw result, meaning that those two are most useful only retrieving textual attributes. But... we can use the same approach of getcap, through libcap itself:
import ctypes

libcap = ctypes.cdll.LoadLibrary("libcap.so")
cap_t = libcap.cap_get_file('/bin/ping')
libcap.cap_to_text.restype = ctypes.c_char_p
libcap.cap_to_text(cap_t, None)

which gives me:
'= cap_net_raw+p'

probably more useful for you.
PS: note that cap_to_text returns a malloced string. It's your job to deallocate it using cap_free
Hint about the "binary gibberish":
>>> import struct
>>> caps = '\x00\x00\x00\x02\x00 \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
>>> struct.unpack("<IIIII", caps)
(33554432, 8192, 0, 0, 0)

In that 8192, the only active bit is the 13th. If you go to linux/capability.h, you'll see that CAP_NET_RAW is defined at 13.
Now, if you wan to write a module with all those constants, you can decode the info. But I'd say it's much more laborious than just using ctypes + libcap.

A: I tried the code from Ricardo Cárdenes's answer, but it did not work properly for me, because some details of the ctypes invocation incorrect. This issue caused a truncated path string to be passed to getxattr(...) inside of libcap, which thus returned the wrong capabilities list for the wrong item (the / directory, or other first path character, and not the actual path).
It is very important to remember and account for the difference between str and bytes in Python 3.X. This code works properly on Python 3.5/3.6:
#!/usr/bin/env python3

import ctypes
import os
import sys

# load shared library
libcap = ctypes.cdll.LoadLibrary('libcap.so')

class libcap_auto_c_char_p(ctypes.c_char_p):
    def __del__(self):
        libcap.cap_free(self)

# cap_t cap_get_file(const char *path_p)
libcap.cap_get_file.argtypes = [ctypes.c_char_p]
libcap.cap_get_file.restype  = ctypes.c_void_p

# char* cap_to_text(cap_t caps, ssize_t *length_p)
libcap.cap_to_text.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
libcap.cap_to_text.restype  = libcap_auto_c_char_p

def cap_get_file(path):
    cap_t = libcap.cap_get_file(path.encode('utf-8'))
    if cap_t is None:
        return ''
    else:
        return libcap.cap_to_text(cap_t, None).value.decode('utf-8')

print(cap_get_file('/usr/bin/traceroute6.iputils'))
print(cap_get_file('/usr/bin/systemd-detect-virt'))
print(cap_get_file('/usr/bin/mtr'))
print(cap_get_file('/usr/bin/tar'))
print(cap_get_file('/usr/bin/bogus'))

The output will look like this (anything nonexistent, or with no capabilities set just returns '':
= cap_net_raw+ep
= cap_dac_override,cap_sys_ptrace+ep
= cap_net_raw+ep


text:
Q: While filtering recyclerview, items are beeing duplicated I have a RecyclerView which shows a data fetched from Room db using MVVM. Also i have an ediitext which I use to search or filter recyclerview items. The problem is when i press on recyclerview item(updates some value in database) and then filter it, it filters but then duplicates all data.
Here is the code:
Complete Adapter code:
private Context mCtx;
private List<AttendeesTable> itemList = new ArrayList<>();
private List<AttendeesTable> filterItemList = new ArrayList<>();
private EventsViewModel eventsViewModel;
long DURATION = 500;
private boolean on_attach = true;
public AttendeesAdapter() {
}
@NonNull
@Override
public EventsViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.view_attendance, parent, false);
    return new EventsViewHolder(view, mCtx, viewType);
}
@Override
public void onBindViewHolder(@NonNull final EventsViewHolder holder, final int position) {
    final int is_arrived = itemList.get(position).getHas_arrived();
    if (is_arrived == 1){
        holder.attendee_arrived_not.setVisibility(View.INVISIBLE);
        holder.attendee_arrived.setVisibility(View.VISIBLE);
        holder.attendee_view.setCardBackgroundColor(Color.parseColor("#dcffda"));
    }else if (is_arrived ==0){
        holder.attendee_arrived_not.setVisibility(View.VISIBLE);
        holder.attendee_arrived.setVisibility(View.INVISIBLE);
        holder.attendee_view.setCardBackgroundColor(Color.WHITE);
    }
    setAnimation(holder.itemView,position);
    holder.attendeeSeatNumber.setText(itemList.get(position).getSeat_no());
    holder.attendeeTicketNo.setText(itemList.get(position).getTicket_no());
    holder.mView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
            String currentDateandTime = sdf.format(new Date());
            if (is_arrived == 0){
                eventsViewModel.updateAttendees(1,currentDateandTime, itemList.get(position).getQr_code_id());
                holder.attendee_arrived_not.setVisibility(View.INVISIBLE);
                holder.attendee_arrived.setVisibility(View.VISIBLE);
                notifyItemRemoved(position);
                holder.attendee_view.setCardBackgroundColor(Color.parseColor("#dcffda"))z
            }else if (is_arrived ==1){
                eventsViewModel.updateAttendees(0,"no_time", itemList.get(position).getQr_code_id());
                holder.attendee_arrived_not.setVisibility(View.VISIBLE);
                holder.attendee_arrived.setVisibility(View.INVISIBLE);
                holder.attendee_view.setCardBackgroundColor(Color.WHITE);
                notifyItemRemoved(position);
            }

        }
    });
}
@Override
public int getItemCount() {
    return itemList.size();
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public int getItemViewType(int position) {
    return position;
}

@Override
public Filter getFilter() {
    return new Filter() {
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            constraint = constraint.toString().toLowerCase().trim();
            itemList.clear();
            if (constraint.length() == 0) {
                itemList.addAll(filterItemList);
            } else {
                for (AttendeesTable item : filterItemList) {

                    String name =  item.getFirst_name() + " " + item.getLast_name();
                    if (item.getTicket_no().toLowerCase(Locale.getDefault()).contains(constraint) ||
                            item.getEmail().toLowerCase(Locale.getDefault()).contains(constraint) ||
                            name.toLowerCase(Locale.getDefault()).contains(constraint) ||
                            item.getSeat_no().toLowerCase(Locale.getDefault()).contains(constraint)){
                        itemList.add(item);
                    }
                }
            }
            FilterResults results = new FilterResults();
            results.values = itemList;
            return results;
        }
        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            notifyDataSetChanged();
        }
    };
}
public class EventsViewHolder extends RecyclerView.ViewHolder {
    TextView attendeeName, attendeeEmail, attendeeSeatNumber, attendeeTicketNo;
    ImageView attendee_arrived, attendee_arrived_not;
    CardView attendee_view;
    public Context context;
    View mView;

    public EventsViewHolder(View itemView, Context context, int viewType) {
        super(itemView);
        mView = itemView;
        this.context = context;

        attendeeEmail = itemView.findViewById(R.id.attendee_email);
        attendeeName = itemView.findViewById(R.id.attendee_name);
        attendeeSeatNumber = itemView.findViewById(R.id.attendee_seat_number);
        attendee_arrived = itemView.findViewById(R.id.attendee_arrived);
        attendee_arrived_not = itemView.findViewById(R.id.attendee_arrived_x);
        attendee_view = itemView.findViewById(R.id.attendee_view);
        attendeeTicketNo = itemView.findViewById(R.id.attendee_ticket_no);
    }
}
public void setAttendees(List<AttendeesTable> events, Context mCtx, EventsViewModel eventsViewModel) {
    this.itemList = events;
    this.mCtx = mCtx;
    this.eventsViewModel = eventsViewModel;
    filterItemList.addAll(events);
    notifyDataSetChanged();
}
@Override
public void onAttachedToRecyclerView(@NonNull RecyclerView recyclerView) {
    recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
            Log.d(TAG, "onScrollStateChanged: Called " + newState);
            on_attach = false;
            super.onScrollStateChanged(recyclerView, newState);
        }
    });
    super.onAttachedToRecyclerView(recyclerView);
}
private void setAnimation(View itemView, int i) {
    if(!on_attach){
        i = -1;
    }
    boolean isNotFirstItem = i == -1;
    i++;
    itemView.setAlpha(0.f);
    AnimatorSet animatorSet = new AnimatorSet();
    ObjectAnimator animator = ObjectAnimator.ofFloat(itemView, "alpha", 0.f, 0.5f, 1.0f);
    ObjectAnimator.ofFloat(itemView, "alpha", 0.f).start();
    animator.setStartDelay(isNotFirstItem ? DURATION / 2 : (i * DURATION / 3));
    animator.setDuration(500);
    animatorSet.play(animator);
    animator.start();
}

And here is my activity's edittext filtering code:
attendee_search.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
        attendeesAdapter.getFilter().filter(s.toString());
        }

@Override
public void afterTextChanged(Editable s) { }});

Here is the screenshot before clicking item:

And after clicking and filtering:

A: For me this is the better aproach working with MVVM
public class DiffExampleAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

private List<AttendeesTable> items;

private List<AttendeesTable> filteredItems = new ArrayList<>();

private String filter = "";

//Call this method each time your data change
public void setItems(List<AttendeesTable> newItems){
    items = newItems;
    filteredItems.clear();
    filteredItems.addAll(items);
    calcDiff();
}

//Call this method for filter items with the string of your editText
//Don't forget to call trim() in the string before to call this method to avoid a malformed filter
public void filterItems(String externalFilter){
    this.filter = externalFilter;
    filteredItems.clear();
    for (AttendeesTable attendeesTable:
            items) {
        //Add all your constraints here
        if (attendeesTable.getId().contains(filter)){
            filteredItems.add(attendeesTable);
        }
        calcDiff();

    }
}

//This diffUtil calculates the changes automatically
private void calcDiff(){

    DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new DiffUtil.Callback() {
        @Override
        public int getOldListSize() {
            return items.size();
        }

        @Override
        public int getNewListSize() {
            return filteredItems.size();
        }

        @Override
        public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) {
            //Just check the ID
            String oldIdAtPosition = items.get(oldItemPosition).getId();
            String newIdAtPosition = filteredItems.get(newItemPosition).getId();
            return oldIdAtPosition.equals(newIdAtPosition);
        }

        @Override
        public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) {
            // You can add more conditions here for check if the items are the same,
            // but in this case is enough to checking the ids of each item, unless
            // you have state changes like item selected or name of the item changed
            String oldIdAtPosition = items.get(oldItemPosition).getId();
            String newIdAtPosition = filteredItems.get(newItemPosition).getId();
            return oldIdAtPosition.equals(newIdAtPosition);
        }
    });

    diffResult.dispatchUpdatesTo(this);
}

@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    //Return your ViewHolder Here
}

@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
    //Play with your viewHolder here
}

@Override
public int getItemCount() {
    //return your filteredItems size
    return filteredItems.size();
}

}
With this you can assure that you will not have duplicated items.


text:
Q: Mapping a long data property to int in database In all of the examples that I've seen use int32s as the IDs. That's not always practical in production environments. Several of our databases have identity IDs that are in the realm of int64s, so our practice is to always use long for our ID properties. However, SQL Server has higher max values for the int column type.
I'm doing our first proof of concept with Entity Framework version 6. With the long ID, it's unable to map the object to the database.
I'm using Fluent API for all of my mapping. Right now, it looks like this for the ID:
Property(s => s.ID).HasColumnName("spcID");

If I add a .HasColumnType("int") to the end of the above, it gives me the following error:

Schema specified is not valid. Errors:  (7,12) : error 2019: Member
  Mapping specified is not valid. The type
  'Edm.Int64[Nullable=False,DefaultValue=]' of member 'ID' in type
  'EFConnection.Space' is not compatible with
  'SqlServer.int[Nullable=False,DefaultValue=,StoreGeneratedPattern=Identity]'
  of member 'spcID' in type 'CodeFirstDatabaseSchema.Space'.

How do you map the datatype for these to a long variable in .NET?
Edit
Right now, I have a simple Integration Test set up to make sure that I can connect:
[TestMethod]
public void TestMethod1() {
    using (var context = new Context()) {
        Assert.IsTrue(context.Spaces.Any());
        Assert.IsTrue(context.Spaces.First().IsActive);
    }
}

Without the .HasColumnType("int"), the first Assert passes, but I get an InvalidOperationException on the second:

The 'ID' property on 'Space' could not be set to a 'System.Int32' value. You must set this property to a non-null value of type 'System.Int64'.

A: C# and SQL data types are compatible:
If your table has a column of bigint use public long Id { get; set; } if your column is int use public int Id { get; set; }
SQL
bigint -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
int -2,147,483,648 to 2,147,483,647
C#
long -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
int -2,147,483,648 to 2,147,483,647
References:

*

*int, bigint, smallint, and tinyint (Transact-SQL)

*int (C# Reference)

*long (C# Reference)


text:
Q: Mass renaming using Python Say I have a bunch of files on one directory, with different extensions:
dsgxy7wusshg2.jpg
ds65321333321.png
ds2716113shg2.jpg
d3171763462g2.jpg
5432125321hg2.png
db37fv73v7av1.png
d0zhzb38b22g2.jpg
d3171763462nb.jpg

I would like to create a small script that will rename every file to the format mystring_x.ext, where mystring is a string that I set in the script, x is the number of the file being renamed, and ext would be the original extension of the file. It should not be possible to have two files using the same number, with different extensions. Only one file per number.
I understand I should use the os module to rename files, but what procedure should I try and use to do this task?

A: directory = '/path/to/dir'
base = 'mystring'

for i, f in enumerate(os.listdir(directory), 1):
    ext = f.rsplit('.', 1)[-1]
    absolutify = lambda s: os.path.join(directory, s)
    os.rename(absolutify(f), absolutify('%s_%d.%s' % (base, i, ext)))


text:
Q: how to change font of edited text using MFC in visual studio 2010 I got assignment to make Dialog when pressing the right mouse button that will allow me to enter new text, change font and size. When I enter new text and choose font (and size) it is shown but font is unchanged. I used  Tool box to add Edit control to add text (when pressed Ok) and Button for font and size. In TxtDlg.cpp :
void CTxtDlg::OnOK()
{
    m_txtEdit.GetWindowText(m_text) ;
    CDialog::OnOK();
}

void CTxtDlg::OnBnClickedButton1()
{
     CFontDialog dlg;
     int response = dlg.DoModal(); //poziv dijaloga
     dlg.GetCurrentFont(&m_lf);
}

I also declared variable m_lf as LOGFONT in TxtDlg.h, so this part should be correct
CString m_text;
CEdit m_txtEdit;
virtual void OnOK();
afx_msg void OnBnClickedButton1();
LOGFONT m_lf;

My guessing is that part of ProjectView.cpp part is incorrect(for font), should use ChangeFontIndirect but don't know how.
void CFesbView::OnRButtonDown(UINT nFlags, CPoint point)
{
    CFesbDoc*pDoc= GetDocument();
    CTxtDlg dlg;
    int response = dlg.DoModal();   //calling dialog

    if(IDOK == response)
    {
        if(dlg.m_text.IsEmpty())
            AfxMessageBox(L"You did not enter text");
        else
            pDoc->m_text = dlg.m_text;      // put text in document
        Invalidate();
    }

     pDoc->m_pos = point;    //point contain coordinates because text
                             //has to be written where clicked

                    //this is the incorrect part, also need to save text and font in document
    CFont l_font;
    LOGFONT m_lf;
    if(IDC_BUTTON1==response){
    l_font.CreateFontIndirect(&m_lf);
    pDoc->m_lf = dlg.m_lf;  }

    CView::OnRButtonDown(nFlags, point);
}

This is the first time I'm using MFC so I don't understand it completely


text:
Q: Why isn't this set of custom objects constructed sorted according to overloaded opreator < I have an Edge class defined as follows
class Edge {
public:
    //constructors & destructors
    Edge();
    Edge(const Edge& orig);
    virtual ~Edge();
    Edge(unsigned const int, const string&, const string&);

    //getters & setters
    unsigned int GetCost() const {return cost;}

    //member functions
    bool operator<(const Edge*) const;
private:
    unsigned int cost;  //cost of the edge
    string cities[2];   //cities that the edge connect
};

//cpp file
bool Edge::operator<(const Edge* e) const {
    cout << "edge" << endl;  //function is never invoked
    return this->cost < e->GetCost();
}

I want to keep those Edges (that are initially contained in a vector) in an Edge* set, and the corresponding code from main() is:
set<Edge*> edge_set;
vector<Edge*> edges;

print_vector(edges);
srand((unsigned)time(NULL));
while(edge_set.size() < K){ //randomly pick K edges that will form the tree
    edge_set.insert(edges[rand()%edges.size()]);
}
print_set(edge_set);

and I get the output:
Edge vector:
edges[0] cost = 136
edges[1] cost = 558
edges[2] cost = 872
edges[3] cost = 1615
edges[4] cost = 654
edges[5] cost = 994
.
.
.

Edge set:
858
1242
436
636
804

I tried to define a function for overloading < operator in main as well, but I couldn't manage to get this set sorted that way either, i.e. couldn't get the overloaded < operator invoked. Also note that I different type of parameters (reference, pointer, object itself) for overloading <.
What am I doing wrong here? How can I fix this issue?

A: You need operator < for both pointers. Since it's unreal by language rules and your operator is for object and pointer - default one (std::less<Edge*>) will be used.
You can store objects, or you can write your functor, that will works with pointers and use it (set object should be declared like std::set<Edge*, Functor>).
Like this
struct CompareCost : public std::binary_function<const Edge*, const Edge*, bool>
{
   result_type operator () (first_argument_type f, second_argument_type s)
   {
      return f->operator <(s);
   }
};

std::set<Edge*, CompareCost> edge_set;


text:
Q: AFNetworking - Asynchronous upload task that can have files queued for upload (w/ progress) What I want to do:

*

*Start a multipart upload of a video

*Before it finishes uploading add another video to be uploaded when 1. is completed

*Show the progress as videos are added

I've looked around but could only find help on creating an upload task for a batch upload, and no information on how to add to an existing upload task.
Thoughts?
Also I'm using swift, but I don't mind ObjC answers :)

A: I create class for you that make it
Go to my git and check it...
https://github.com/dekelm8/QueueUploading
I hop you can handle with the server side alone , the .php file :)
Hop It's helping you, if yes please mark as solved :)


text:
Q: What does "vipers" mean here?
Yeah, the cut throats and the pigs. But who wants all that blood spilled, judge, huh? Isn't there a simpler way of not pissing off the big vipers?" – Al Swearengen

From the show Deadwood
What does vipers mean here?

A: You have to understand it in its context. Earlier, Al Swearengen said:

...First come when I was watchin' you and them lawyers on line this morning. They began to slither in my sight like vipers. So as not to puke, I had to close my eyes. The vision went on. Got worse. I saw the vipers in the big nest in Washington. They were takin' us in the camp for actin' like we could set out own laws up or organizations and then saw the big viper decide to strangle and swallow us up every fuckin' thing we gain here

So, "vipers" here is referring to the judge and the lawyers.

A: Viper can be "a vicious or treacherous person". It is used here as such, rather than as the animal itself.

A: The "big vipers" in this context means the "big shots." In a rather pejorative way.


text:
Q: How to add a keyword with a blank space in Listings package? I am trying to define a listing style in order to have fortran source codes which look like vim style colors.
For example, I would like to give a specific color to end program or end module or double precision ect ...
It is easy for keywords without blank character but I do not know how to do for keyword such as those above.
As you can see in the example below, the color of program is the good one but the color of  end program is not the good one.
\documentclass{article}

\usepackage{xcolor}
\definecolor{keycolor}{RGB}{172, 42, 42}
\definecolor{vimvert}{RGB}{46, 139, 87}

\usepackage{listings}

% global parameters
\lstdefinestyle{global}{
  basicstyle=\ttfamily\scriptsize\color{black!90},%
  stringstyle=\itshape\color{magenta},%
  showstringspaces=false,%
  keywordstyle=\bfseries\color{keycolor},%
  commentstyle=\color{gray}\slshape,%
}

% fortran style
\lstdefinestyle{fortranstyle}{
  language=Fortran,%
  style=global,%
  emph=[1]{implicit none, integer, real, double precision, character, len, parameter, structure, common},%
  emphstyle=[1]\bfseries\color{vimvert},%
  emph=[2]{program,end program, module, end module, subroutine, end subroutine, function, end function},%
  emphstyle=[2]\color{violet}\bfseries\slshape,%
  emph=[3]{call, true, false},%
  emphstyle=[3]\color{teal}\slshape%
}

\begin{document}

\begin{lstlisting}[style=fortranstyle]
program calcPi

  implicit none

  integer            :: i, nbreDansCercle
  integer, parameter :: npts = 1000000000
  double precision   :: x, y, r, pi

  nbreDansCercle = 0
  do i = 1, npts, 1
      call random_number(x)
      call random_number(y)
      x = 2.d0 * x - 1.d0
      y = 2.d0 * y - 1.d0
      r = x**2 + y**2

      if (r < 1.d0) then
          nbreDansCercle = nbreDansCercle + 1
      end if
  end do

  pi = 4.d0 * dble(nbreDansCercle) / dble(npts)
  write(*,"('pi = ', F20.17)") pi

end program calcPi
\end{lstlisting}

\end{document}

A: One solution would be the use of the moredelim key (see package manual section 3.3 "Delimters")
I defined two more delimeters:

*

*moredelim=[is][emphstyle]{|>}{<|} for implicit none and double precision that also don't get highlighted as you might want to define.

*moredelim=[is][emphstyle2]{|<}{>|} for end program and end module
There is one drawback: This has to be done manually or via Search-and-Replace and Regex but still, you can't simply copypaste code from your source or include it with \lstinputlisting.
Code
\documentclass{article}

\usepackage{xcolor}
\definecolor{keycolor}{RGB}{172, 42, 42}
\definecolor{vimvert}{RGB}{46, 139, 87}

\usepackage{listings}

% global parameters
\lstdefinestyle{global}{
  basicstyle=\ttfamily\scriptsize\color{black!90},%
  stringstyle=\itshape\color{magenta},%
  showstringspaces=false,%
  keywordstyle=\bfseries\color{keycolor},%
  commentstyle=\color{gray}\slshape,%
}

% fortran style
\lstdefinestyle{fortranstyle}{
  language=Fortran,%
  style=global,%
  emph={[1]integer, real, character, len, parameter, structure, common},%
  emphstyle=[1]\bfseries\color{vimvert},%
  emph={[2]program, module, subroutine, function},%
  emphstyle=[2]\color{violet}\bfseries\slshape,%
  emph={[3]call, true, false},%
  emphstyle=[3]\color{teal}\slshape,%
  moredelim=[is][emphstyle]{|>}{<|},%
  moredelim=[is][emphstyle2]{|<}{>|}%
}

\begin{document}
\begin{lstlisting}[style=fortranstyle]
program calcPi

  |>implicit none<|

  integer            :: i, nbreDansCercle
  integer, parameter :: npts = 1000000000
  |>double precision<|   :: x, y, r, pi

  nbreDansCercle = 0
  do i = 1, npts, 1
  end do

  pi = 4.d0 * dble(nbreDansCercle) / dble(npts)
  write(*,"('pi = ', F20.17)") pi

|<end program>| calcPi
\end{lstlisting}
\end{document}

Output

PS: You could also use moredelim=[s][emphstyle]{implicit}{none} (note the missing i) but this works only if you use implicit with a following none. The same applies to double precision and most importantly end program.
It would fail when it encounters an end do because end is still a delimiter which does not find a program and it will all be set in emphstyle.


text:
Q: Using an if block in awk I'm processing a file in awk.
I want to pass along the rows in the file that have blanks in column positions 25 through 34 and I want to do work on the rows that have blanks in column positions 10 through 19.
Specifically I want to replace the blanks in columns positions 10 through 19 with 0s.
That way the output file will have the original rows with blanks in 25-34 untouched. and the rows with blanks in 10-19 with have been replaced with '0's. So the output file will be the same as the input file only with zeros in the relevant rows in positions 10-19.
The file looks like this:
###########################################
#########          ########################
###########################################
###########################################
###########################################
###########################################
###########################################
###########################################
#########          #####          #########
###########################################
###########################################
###########################################

I know I have to use an if block but I've never used one before in awk. The syntax below is what I think I need but please help me with the details. Specifically what I'm using to specify 'blanks' in the if statements.
I apologize  ahead of time for the bad syntax. This is my first time using an If block in awk. I know the syntax doesn't work, which is one of the reasons I'm posting this.
cat scr2 | awk 'BEGIN {
    pos1=substr($0,25,10);
    pos2=substr($0,10,10);

      if (pos1 = ^[[:blank:]]$)
         printf $0
      else if (pos2 == ^[[:blank:]]$)
         {val=substr($0,25,10)}
         gsub(/ /,0,val){$0=substr($0,1,24) val substr($0,35)} 1}'`

The sample output would be :
###########################################
#########0000000000########################
###########################################
###########################################
###########################################
###########################################
###########################################
###########################################
#########          #####          #########
###########################################
###########################################
###########################################

So the row with blanks only at positions 10-19 gets changed and the row with blanks at both 10-19 and 25-34 get left alone.

A: With your shown samples, please try following awk code, written and tested in GNU awk, should work in any awk.
awk '
substr($0,10,10) ~ /^ +$/ && substr($0,20) !~ / / {
  $0=substr($0,1,9) "0000000000" substr($0,20)
}
1
' Input_file

Explanation: Simple explanation would be, checking 2 conditions in main program of awk. 1st to make sure position 10th to 20th contains only space AND 2nd rest of the line's values are NOT having spaces in it, if this is the case then enter zeroes in place of spaces and print edited/non-edited lines.

A: Another option is using match() to fill the RSTART built-in variable specifying the start of the block of spaces. You can then use substr() in a regex comparison to verify the remainder of the line is comprised only of '#' characters. For example:
awk '{if (match($0,/[ ]{10}/) && RSTART == 10 && substr($0,20) ~ /^#*$/) sub(/[ ]{10}/,"0000000000")}1' file

The above will match() each line with 10-spaces beginning at column 10 and replace them with 10 '0's.
Example Use/Output
With your input in the file named file, you would have:
$ awk '{if (match($0,/[ ]{10}/) && RSTART == 10 && substr($0,20) ~ /^#*$/) sub(/[ ]{10}/,"0000000000")}1' lines
###########################################
#########0000000000########################
###########################################
###########################################
###########################################
###########################################
###########################################
###########################################
#########          #####          #########
###########################################
###########################################
###########################################

A: I'd use sed here:
sed -E 's/^(.{9}) {10}(.{5}[^ ]{10})/\10000000000\2/' file

A: You can do it in awk without any if statement:
awk '{print gensub(/^(.{9}) {10}([^ ]{24})/, "\\10000000000\\2", "g")}' file

This will replace 10 blanks by 10 0 in positions 10 to 19 only on the lines where there are no blanks in positions 20 to 43, which is what you want, I guess.


text:
Q: What is the relation between FreeType, Fontconfig and Xft I just started research on how fonts work under Linux. Till now, I got to know that the Linux font system consists of:

*

*FreeType, which is a rasterizer for rasterizing vector-based text to bitmap-based.

*Fontconfig, which is a library for managing and locating fonts inside the operating system.

*Xft that is used for displaying desired output on X windows system or so.

(Correct me if I am wrong.)
Is there any direct relation between these three? What is the workflow? And under what circumstances these system libraries are invoked?

A: They're related like this (using ldd):

*

*Xft is a library, which depends on (among other things) the fontconfig library and the freetype library.

*fontconfig is a set of programs, a library and data.  Its library depends upon the freetype library.

*freetype is a library, which does not depend on the other two.

For example:
$ ldd /usr/lib/x86_64-linux-gnu/libXft.so.2.3.1
        linux-vdso.so.1 =>  (0x00007fffb3df7000)
        libfontconfig.so.1 => /usr/lib/x86_64-linux-gnu/libfontconfig.so.1 (0x00007f40ea07a000)
        libfreetype.so.6 => /usr/lib/x86_64-linux-gnu/libfreetype.so.6 (0x00007f40e9ddb000)
        libXrender.so.1 => /usr/lib/x86_64-linux-gnu/libXrender.so.1 (0x00007f40e9bd1000)
        libX11.so.6 => /usr/lib/x86_64-linux-gnu/libX11.so.6 (0x00007f40e9896000)
        libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f40e9509000)
        libz.so.1 => /lib/x86_64-linux-gnu/libz.so.1 (0x00007f40e92f2000)
        libexpat.so.1 => /lib/x86_64-linux-gnu/libexpat.so.1 (0x00007f40e90c8000)
        libxcb.so.1 => /usr/lib/x86_64-linux-gnu/libxcb.so.1 (0x00007f40e8ea8000)
        libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007f40e8ca4000)
        /lib64/ld-linux-x86-64.so.2 (0x00007f40ea4c6000)
        libXau.so.6 => /usr/lib/x86_64-linux-gnu/libXau.so.6 (0x00007f40e8aa1000)
        libXdmcp.so.6 => /usr/lib/x86_64-linux-gnu/libXdmcp.so.6 (0x00007f40e889c000)

Some applications (such as xterm) use Xft, which uses an MIT-license.  Others (generally the GPL-licensed ones) use libpango.  Besides licensing concerns on pango, it has twice as many library-dependencies as Xft.
Looking at the symbols from fontconfig used by Xft:
FcCharSetCopy
FcCharSetCount
FcCharSetDestroy
FcCharSetHasChar
FcConfigGetBlanks
FcConfigSubstitute
FcDefaultSubstitute
FcFontList
FcFontMatch
FcFreeTypeCharIndex
FcFreeTypeCharSet
FcInit
...
FcPatternPrint
FcPatternVaBuild
FcStrCmpIgnoreCase
FcUtf16ToUcs4
FcUtf8ToUcs4

and those from freetype:
FT_Done_Face
FT_GlyphSlot_Embolden
FT_Init_FreeType
FT_Library_SetLcdFilter
FT_Load_Glyph
FT_New_Face
FT_Render_Glyph
FT_Set_Char_Size
FT_Set_Transform
FT_Vector_Transform

you can see that Xft uses fontconfig for locating fonts based on patterns, but uses freetype to actually load, display or adjust (scale, etc) a font.
fontconfig uses different calls to freetype to obtain information about a font (the overall size, the number of glyphs, etc):
FT_Done_Face
FT_Done_FreeType
FT_Get_BDF_Property
FT_Get_Char_Index
FT_Get_First_Char
FT_Get_Glyph_Name
FT_Get_Next_Char
FT_Get_PS_Font_Info
FT_Get_Sfnt_Name
FT_Get_Sfnt_Name_Count
FT_Get_Sfnt_Table
FT_Get_X11_Font_Format
FT_Has_PS_Glyph_Names
FT_Init_FreeType
FT_Load_Glyph
FT_Load_Sfnt_Table
FT_New_Face
FT_Select_Charmap
FT_Select_Size

Without freetype, fontconfig hasn't any information: fontconfig organizes information but is not a complete source of information by itself.


text:
Q: ffmpeg capture frame from input on demand I'm trying to capture image frames from a webcam on demand. I'm using ffmpeg and I was thinking of keeping a stream running, sort of as a daemon, with:
ffmpeg -f v4l2 -i /dev/video0 /dev/null

Is it possible, and how would I go about capturing an image from that stream on demand?
I need the capture to be as quick as possible.
To add a little bit of context, my project is using a Raspberry Pi to control multiple servos. I want to be able to send back image stills from 2 cameras along with servo position data, so they're in sync. This would hopefully be up to 5fps? Am I dreaming, or should something like this be possible?
Any help is greatly appreciated


text:
Q: Best performance: $this->var Vs $_SESSION superglobal with big arrays I have a method that works with array with ~30000 entries. The method can be called usually about 100 times.
The idea is to use $this->response var and when the method is called another time save SQL querys...
Example:
function myMethod(){
    $sql = "SELECT * FROM table LIMIT 30000";
            if(!isset($this->data_kpi))
                $this->data_kpi  = myclass::myPDOmethod($sql); //array entries

        //rest of method use $this->data_kpi
}

If I use a $_SESSION superglobal I get a best performance 6 Vs 19 seconds. I don't know why but i think is a bad practice use a superglobal for this....
Example with superglobal:
function myMethod(){
        $sql = "SELECT * FROM table LIMIT 30000";
                if(!isset($_SESSION['tmp']))
                    $_SESSION['tmp']  = myclass::myPDOmethod($sql); //array entries

            //rest of method use $_SESSION['tmp']
}

 __destruct(){
    unset($_SESSION['tmp']);
    }

Any suggestions?


text:
Q: Python - Selenium - Checkbox by contains value So that is what the html looks like, and i want to check the box that contains "4845" in the ID or  in the Value, how can i do it ?

 04845 - B.pippo

    <input class="checkbox" name="selectatm1" type="checkbox" value="N031394845|H" tabindex="5">
4
HALA
03139
4845
    Stree 123
0
0
0

                4567.77
        4567.77
31/03/2022 15:50
G20
        31
    04/04/2022 11:13

A: You can try
checkbox_elem = driver.find_element_by_xpath("//input[contains(@value, '4845') or contains(@id, '4845')]")
if not checkbox_elem.is_selected():
    checkbox_elem.click()

A: To click() on the checkbox that contains 4845 in the Value you can use either of the following locator strategies:

*

*Using css_selector:
driver.find_element(By.CSS_SELECTOR, "tr[id^='tr'][id$='4845'] td > input[value*='4845']").click()

*Using xpath:
driver.find_element(By.XPATH, "//tr[starts-with(@id, 'tr') and contains(@id, '4845')]//td/input[contains(@value, '4845')]").click()


text:
Q: Не работает условие IF при проверке типа данных На начальной стадии изучения Python, никак не могу понять почему не срабатывает условие?
print('Введите цифры: ')
a = input()
if (type(a) == int):
    print('Вы ввели цифры: ', a)
else:
    print('Вы ввели не цифры, а другие символы!')

Так же пробовал второй вариант кода. Все равно ничего не получается...
print('Введите цифры: ')
a = input()
if isinstance(a, int):
    print('Вы ввели цифры: ', a)
else:
    print('Вы ввели не цифры, а другие символы!')

Если в 2й строке пишу a =  int(input()), то выдает ошибку File "C:/PYTHON/Studies/lesson2.py", line 2, in
a = int(input())
ValueError: invalid literal for int() with base 10: 'gj'

A: a = input()
if (type(a) == int):

input всегда возвращает строку, поэтому не может быть числом
нужно сделать такой код для вышей цели
try:
    value = int(input())
    print(f'Вы ввели цифры: {value}')
except ValueError:
    print('Вы ввели не цифры, а другие символы!')

так же можно использовать такой вариант:
value = input()

if value.isnumeric():
    print(f'Вы ввели цифры: {value}')
else:
    print('Вы ввели не цифры, а другие символы!')

A: Можно проверить ещё вот так:
print('Введите цифры: ')
a = input()
if a.isdigit():
    print('Вы ввели цифры: ', a)
else:
    print('Вы ввели не цифры, а другие символы!')

input возвращает строку, но у строк есть методы проверки, в том числе, что строка состоит из цифр, что я и проверяю в этом коде.


text:
Q: Putting data inside prop to make it look tidy Vue.js I have a create page, I make a POST request using Axios and it works great. But I think my code is not healthy at all.
That is how I define my props:
data () {
            return {

                first_name: '',
                last_name: '',
                student_number: '',
                phone_number: '',
                email: '',
                birth_date: '',
                school_name: '',
            };
        },

These things are v-model's objects. I use them to make a POST request to my API. But instead of writing them one by one, can I put these in an array or a prop?
When I'm making a request to API, I define my v-model's one by one again.
Like this
axios.post(`/api/students`, {

                first_name:this.first_name,
                last_name:this.last_name,
                student_number:this.student_number,
                phone_number:this.phone_number,
                email:this.email,
                birth_date:this.birth_date,
                school_name:this.school_name,

Can I send them in just one or two line?
Like: postedData:this.studentData;

A: While the previous answer is correct for this particular use-case, if you were to add properties that you don't want to send, it wouldn't work anymore. A better approach is to put all those properties inside an object, let's name it studentData, like this:
data() {
  return {
    studentData: {
      first_name: '',
      last_name: '',
      student_number: '',
      phone_number: '',
      email: '',
      birth_date: '',
      school_name: '',
    },
  };
}

and then you can do
axios.post('/api/students', this.studentData);

Note that you'll also need to update your v-models like v-model="studentData.first_name" instead of v-model="first_name".

A: You can access component props or data from this.$props or this.$data,
So you can simply do
axios.post(`/api/students`, this.$data);

But this means that your are sending the entire component data on the request, to avoid this, try @BogdanL answer which is recommended.


text:
Q: R Convert string vector to date with unusual date format I am trying to convert a vector of factors to a vector of dates in R.  I know there are a number of questions on this topic, but I couldn't find an answer on how to convert this particular type of vector.
The data and my attempt is as follows:
dates <- c(1/4/2005, 1/5/2005, 1/6/2005, 1/7/2005, 1/8/2005, 1/9/2005, 1/10/2005)
class(dates)
 "factor"
dates <- as.character(dates)
class(dates)
 "character"

I then tried two approaches to convert from this string format to the date format using:
dates <- as.date(dates)  #This converts the vector to 0001-04-20, 0001-11-20, NA, NA, 0002-01-20,..
dates <- strptime(dates, "%m/%d/%y")  #This converts the vector to 2020-01-04, 2020-01-02, ...

I believe it is because the date column is saved with single numbers for each month and day, e.g. "1" instead of "01" for the month and "5" instead of "05" for the day.  Is there a way to convert this character vector to the correct date format?  Thank you.

A: Problem 1: Your dates are numeric, i.e., 1/4/2005 equals (1/4)/2005 = 1.24E-4
Problem 2: You need "%Y" for 4-digit-years (%y is for 2-digit-years)
This should work:
dates <- c("1/4/2005", "1/5/2005", "1/6/2005", "1/7/2005", "1/8/2005", "1/9/2005", "1/10/2005")
strptime(dates, "%m/%d/%Y")

A: I assume your dates are the short date format (maybe from Excel), which is what I encounter most of the time when the data is exported from excel to csv and read into R via read.csv.
dates <- c("1/4/2005", "1/5/2005", "1/6/2005", "1/7/2005", "1/8/2005")
df <- data.frame(dates = dates) # emulate df = read.csv(file)

Then you would want to add a Date column to df by
df$Date <- as.Date(df$dates, format="%m/%d/%Y")
df
     dates       Date
1 1/4/2005 2005-01-04
2 1/5/2005 2005-01-05
3 1/6/2005 2005-01-06
4 1/7/2005 2005-01-07
5 1/8/2005 2005-01-08

You can then use the Date column for timeseries manipulation, e.g. through xts.


text:
Q: django-userena "get_visible_profiles" error I have been using django userena for my new project and everything worked fine.
Now when I am browsing to /accounts/ is get the following error:
AttributeError: 'Manager' object has no attribute 'get_visible_profiles'

I think it is related to a recent update of userena. Did anyone else encounter this issue?

A: Problem solved.
I had an explicit entry:
objects = models.Manager()

In the model class. Removing it fixed the problem.

A: You can also just lift the method from UserenaBaseProfileManager and place it in your class or derive your Manger class from that class.  I opted for the former because I build my managers as QuerySet objects and then use
    objects = ModelQuerySet.as_manager()

And Userena was built before that was possible.  I needed some methods in my Manager class so just deleting objects =  was not an option for me.


text:
Q: RegEx to match text outside of square and curved brackets I have a log file that I need to search for. The text outside of the brackets is always the same, so to be as precise as I can, I would like to ignore the text inside both square and curved brackets.
So the log is;
[09/May/2022:11:04:05 +0000] NSMMReplicationPlugin - process_postop: Failed to apply update (6278e86f000627440000) error (-1).  Aborting replication session(conn=5361 op=6)

Where I do not need the date at the start inside the [ ] or the numbers & text inside both sets of ( ) either side of the (-1) as the (-1) part is key to the search.
I just need to search on;
NSMMReplicationPlugin - process_postop: Failed to apply update error (-1).  Aborting replication session

I cannot figure this out! I tried a lazy qualifier but as there's ( ) that I need it didn't work;
(?<=NSMMReplicationPlugin - process_postop: Failed to apply update)(.*)(?=error (-1).  Aborting replication session)
I somehow need to escape the ( ) to get the -1 part?

A: We can use the following pattern which divides the text into 4 groups and only uses group 2 and 4.
(\[.*\])(.*)(\(\w*\))(.*)

to get group 2 and 4 we use \2\4 or $2$4 depending on the flavour of regex.
See https://regex101.com/r/v6izps/1 for an example.
Depending on the language and the tools there may not be any need to put brackets around the 1st and 3rd groups.


text:
Q: Error while writing an Equation in LaTeX! i just started off with LaTeX. And so, getting stuck for petty issues.
Would be cool to get some help.
Here's the error i got.

Please use \mathaccent for accents in math mode.
\add@accent ...@spacefactor \spacefactor }\accent
                                                  #1 #2\egroup \spacefactor ...
l.39 \end{split}

and here is my code
\begin{equation*}
\begin{split}
E_(w) &= \frac{1}{*2}*\sum\limits_{i=1}\^ N t_i (phi{x_i}-y_i)^2
\end{split}
\end{equation*}

A: you have more issues in your equation

*

*instead of \^N you should write \hat{N}

*why you use split environment if you have on line equation?

*don't * use as multiplication operator

*meaning of \frac{1}{*2} is unclear

*instead of phi{x_i} i suspect that you probably like to write \phi_{x_i}

*...

\documentclass[12pt]{article}
\usepackage{amsmath}

\begin{document}
\[
E(w) = \frac{1}{2}\sum\limits_{i=1} \hat{N} t_i (\phi_{x_i}-y_i)^2
\]
\end{document}

it also seems that you maybe try to write:

\documentclass[12pt]{article}
\usepackage{amsmath}

\begin{document}
\[
E(w) = \frac{1}{2}\sum\limits_{i=1}^{N} t_i (\phi_{x_i}-y_i)^2
\]
\end{document}

writing of equation is demanding task ...
edit: considering valuable comments of Au101 and Mico i make number of edits by which i try to improve my answer.

A: The error mainly comes from \^ that you have written. You also need \phi() and no need for split in a one-line formula. Some terms are unclear, if you're unsure about how to typset some terms, you can post an image of the desired output.
\documentclass[12pt,a4paper]{article}
\usepackage{amsmath}
\begin{document}

\begin{equation*}
  E(w) = \frac{1}{2}*\sum\limits_{i=1}^N t_i (\phi(x_i)-y_i)^2
\end{equation*}

\end{document}

Edit
Also, note that \limits is the default for a sum in a display, unless it's in a fraction or array as pointed out by @barbarabeeton in a comment. So, just \sum_{i=1}^N is sufficient in your case. And the multiplication * can also be removed but we are not sure about what guidelines you follow or what the desired output should be.

A: @Zarko and @AboAmmar have already provided valiant efforts at guessing what the equation should really look like. Here's a third guess. Note the use of the upright ("Roman") letter E to denote the mathematical expectation. (In math typography, italic letters are generally used for variables, whereas "operators" are generally displayed using non-italic or "Roman" letters.)

\documentclass{article}
\usepackage{amsmath} % for "\DeclareMathOperator" macro and "equation*" env.
\DeclareMathOperator{\E}{E} % expectations operator

\begin{document}
\begin{equation*}
\E_w = \frac{1}{2}\sum_{i=1}^N t_i (\phi x_i-y_i)^2
\end{equation*}
\end{document}


text:
Q: rails before_create not trigering method I'm trying to trigger a method right before saving an instance. I've got the User model:
class User < ActiveRecord::Base

    has_secure_password
    attr_accessible :name, :first_surname,:second_surname,:email, :password, :password_confirmation,:number,:credit

    before_save{ self.email.downcase! }
    before_create :generate_auth_token

    default_scope order: 'users.created_at ASC'

    has_many :operations

    def consume(what,price,agent)
        self.operations.create(category:what,price:price, agent_id:agent)
    end
end

And each User has many Operation(note the use of the pry debuger via binding.pry:
class Operation < ActiveRecord::Base
  attr_accessible :agent_id, :comment, :postcredit, :precredit, :category, :user_id,:price
  validates_presence_of :user_id
  validates_presence_of :agent_id
  validates_presence_of :price
  validates_presence_of :precredit
  validates_presence_of :postcredit
  validates_presence_of :category
  #before_save :compute_prices, :on => :create
  before_create :compute_prices
  belongs_to :user

  private

  def compute_prices
      binding.pry
      user=User.find(self.user_id)
      self.precredit=user.credit
      #select whether adding or subtracting
      if self.category == 'credit'
          self.postcredit=self.precredit+self.price
      else
          self.postcredit=self.precredit-self.price
      end
      user.update_attributes(credit:self.postcredit)
  end
end

I populate the database with users and operations, and test it via the console $rails c --sandbox. Then I:
>fi=User.first
>ope=fi.operations.create(category:'credit',price:12.2,agent_id:3)
#Now here the debugger should start and does not

I try it with both before_create and before_save, but none work.
before_create :compute_prices
before_save :compute_prices, :on => :create

The only option that worked is after_initialize :compute_prices, but this gets triggered after every find or initilialization.
Any ideas?
SOLUTION
As explained as a comment to the first answer, the solution was to user before_validation (function), on: :create, instead of before_save ....

A: Is your operation valid?  The callback lifecycle is here: http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html and if validation fails, it won't get to the create callbacks


text:
Q: Unwanted resizing of forms in C# I'm and a friend are working on a training project. My friend's laptop monitor is full HD and my monitor is HD.
This difference in resolution has caused the project to change its size when it is transferred back to my system when it is transferred from my system to my friend's system.
To be clear, we are working on Visual Studio and suppose we have a form 1080 by 720 which in my system is OK when we edit the form. But when we save the project and move that on my friend's system to continue the project, because the monitor has a higher resolution, the size of the form becomes 1124 by 812, and this disrupts the whole design work.
The point is that the forms that we do not open on my friend's system remain in the same dimensions of 1080 by 720 and there is no change in them.
What is the way to solve this problem?
Thanks a lot

A: Under the Layout section of your Form's properties set the AutoScaleMode to None.
Alternatively, if your AutoScaleMode is currently set to Font (the typical setting), then make sure that your system fonts are the same size.

A: What you need is responsive design. if you design your program responsive, so every element of your app in any resolution load correctly.
I suggest reading this link to figure out how to do that
Dynamically Resizing Controls On Windows Forms


text:
Q: porting isnan to c++11 When I'm switching the compiler version from gcc 4.6 to gcc 4.8 I get the following error
error: call of overloaded 'isnan(double)' is ambiguous.
This is because in c++11 there are differend function declarations:
C: int isnan(double)
C++11: bool isnan(double)
from cpluplus:

*

*In C, this is implemented as a macro that returns an int value. The type of x shall be float, double or long double.

*In C++, it is implemented with function overloads for each floating-point type, each returning a bool value.

How can I fix this?

A: In C++11 there should not be ambiguity between the C and C++ isnan function. It works as expected, even with using namespace std.
Please check that you are not doing both #include <math.h> and #include <cmath>. Only include cmath.
Alternatively, perhaps you somewhere have in your project a user-defined isnan(double) function, or some header includes "math.h".
Also please note, that if one wants to write generic code, it is incorrect to use the 'std::' prefix on the math functions as it breaks the argument dependent lookup (ADL). (Because the C++ standard does not allow injecting functions in the std:: namespace)
The correct use for isnan in generic code is using std::isnan; then use just isnan on the variables. Otherwise your code with user defined floating point types such as for arbitrary precision, automatic differentiation and such wont work. The root of this inconsistency is that the built in types such as double do not reside in the namespace std but the functions that operate on them do.

A: Although you can mitigate this problem by not saying using namespace std; everywhere, you can avoid it by being explicit about using std::isnan:
#include <cmath>
#include <iostream>

int main()
{
  double x = ....;
  std::cout << std::boolalpha;
  std::cout << std::isnan(x) << std::endl;
}


text:
Q: Flutter Firestore Error: Field does not exist within the DocumentSnapshotPlatform I'm having trouble reading data from firestore. I want to display a user's name on screen after it is stored in firestore.
firestore document
my code is as follows, and thank you in advance for any assistance given:
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

class Test extends StatefulWidget {
  @override
  _TestState createState() => _TestState();
}

class _TestState extends State<Test> {
  final db = FirebaseFirestore.instance.collection('users').snapshots();

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        title: Text('Test'),
      ),
body: StreamBuilder<QuerySnapshot>(
        stream: db,
        builder: (context, snapshot) {
          if (!snapshot.hasData) {
            return Center(
              child: CircularProgressIndicator(),
            );
          } else
            return ListView(
              children: snapshot.data!.docs.map((doc) {
                return Card(
                  child: ListTile(
                    title:
                    // Text(doc.data()['title']),
                    Text(doc.get('First name')

                  ),
                ));
              }).toList(),
            );
        },
      ),

A: final Stream<DocumentSnapshot<Map<String, dynamic>>> db = FirebaseFirestore.instance
      .collection('users')
      .doc('Personal details')
      .snapshots();

...
body: StreamBuilder<DocumentSnapshot>(
  stream: db,
  builder:
      (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
    if (snapshot.hasError) return Text('Something went wrong');
    if (snapshot.connectionState == ConnectionState.waiting)
      return CircularProgressIndicator();

    dynamic data = snapshot.data.data();
    print(data);
    print(data['First name']); // should print 'Guy'
    print(data['Last name']); // should print 'Fang'
    return Text(data['First name']);
  },
),

In the code you showed, you are listening to the 'users' collection, instead, listen to the document 'Personal details' as shown above.


text:
Q: Using JavaScript/jQuery methods on array of objects? I have an array of Objects in JavaScript and I'm having trouble accessing JS methods on my array.
Is there a way to use methods such as removeClass or attr on an array without having to use a for loop? For example, in jQuery if I do $("li.listing").removeClass("listing")....it will remove the listing class from all li tags where this class is present.
Is there a way without having to use multiple for loops, to use these methods on an array (so that it looks at each element/object in the array)?
Example
cars.removeClass("listing") // Remove listing class from every element in cars array - is this syntax or something similar possible? Thanks!
Array index [0] example
0: m.fn.init [
  li#listing-MCMR-R-ZT-BFNT001-ZT-BFNT001.listing.filtered-out-by-car-type.listing-filtered-out,
  prevObject: m.fn.init(1),
  context: car,
  selector: "li.listing"
]

A: You can use Array.prototype.map to simplify the syntax a bit, but it is essentially also going to loop through all the elements. Under the hood, jQuery is also looping through them, all it is doing is giving you a nice way to access that without having to write the loop yourself
for your example:
cars.map(function(car) {
   return car.removeClass('listing');
});

As pointed out in the comments, Array.prototype.forEach Is probably preferable if you're only looking to mutate or apply the function on the current array and not return anything new. In either case, this is the most succinct way of going through an array without using an explicit for loop


text:
Q: Ember App Kit: Controller without Route is not recognized? as I mentioned in several questions here I am migrating an already existing and running Ember project to use Ember App Kit and I ran into several problems... here's another "problem" which wasn't a problem before :)
I've got a NotificationCollectionController which is placed under app/controllers/notification/collection.js.
file 'app/controllers/notification/collection.js':
export default Ember.ArrayController.extend({
  addNotification: function (options) {
    // some code
  },
  notifyOnDOMRemove: function (notification) {
    this.removeObject(notification);
  }
});

As this is the controller for notifications which are rendered through a named outlet I didn't declare a route for it.
Within my ApplicationRoute I want to access this controller within a function
file: 'app/routes/application.js'
import BaseRoute from 'appkit/routes/base';

export default BaseRoute.extend({
  addGlobalNotificationCollection: function () {
    var controller = this.controllerFor('notificationCollection');
    // some more code...
  }
});

But as soon as the application starts and this piece of code gets called I traced down the following error:

"Assertion Failed: The controller named 'notificationCollection' could
  not be found. Make sure that this route exists and has already been
  entered at least once. If you are accessing a controller not
  associated with a route, make sure the controller class is explicitly
  defined."

What does it mean and why is it thrown? What do I have to do to make it run again?

A: I didn't recognize that the hint is already given at the Naming Conventions section of the Ember App Kit Webpage:
It says, that the naming convention for a Controller is, for example: stop-watch.js

And if it's a route controller, we can declare nested/child controllers like such:
  app/controllers/test/index.js

So I placed my NotifcationCollectionController in controllers/notification-collection.js and call it like Route#controllerFor('notification-collection') and everything works as expected :)


text:
Q: Provide backwards compatibility layer with older versions of the ECore I use EMF to store the main data of my application. However, the ECore model evolves over time. Every time a new release is done, I use a different base URI for my package. This way, it remains very clear which version a file was stored in.
I would like to add a backwards compatibility layer. This way, I can also read older versions and convert them to a new version of the model. How would I go about this? Can I just use an older version of the .Ecore to parse the file reflectively and try to create a new model automatically? How do you guys do this in practice?

A: Have a look at the EMF recipes