text:
Q: How should I exit a C++ program cleanly after printing the CLI help message from a function? I'm trying to figure out the best way to exit my program cleanly after printing the CLI help information in my program. Currently it looks like this.
int main(int argc, *char[] argv) {
    try {
    std::string settings_file = process_args(argc, argv);

    do_more_stuff();
    ...
    ...
    } catch (...) {
        std::cerr << "Error" << std::endl;
        return (EXIT_FAILURE)
    }
}

std::string process_args(int argc, char *argv[]) {
    boost::program_options::options_description desc("Program options");
    desc.add_options()("help,h", "Print usage message")(
      "settings,s", boost::program_options::value<std::string>(),
      "Specify settings file");

    boost::program_options::variables_map vm;

    store(parse_command_line(argc, argv, desc), vm);

    if (vm.count("help")) {
        std::cout << desc << std::endl;
        ---->!!!!!!!! WHAT DO I DO HERE TO GET OUT !!!!!!!!<----
    }
    if (vm.count("settings")) {
        std::cout << "Settings file " << vm["settings"].as<std::string() << std::endl;
        return vm["settings"].as<std::string>();
    } else {
        throw std::runtime_error("Settings file must be specified.");
    }
}

So my question is after I print the CLI 'help' message what do I do to exit my program?

*

*Should my function not be returning std::string and just return an error code?

*Should I throw an exception and catch it in main and then exit?

*Is there a much nicer / better way to do it?
Thanks in advance.

A: Another better way in my opinion, according to this post : C++ catching all exceptions
#include <cstdlib>
#include <iostream>
#include <stdexcept>

static bool checkHelp(char * const argv[])
{
    bool usage = (!strcmp(argv[1], "-h") or !strcmp(argv[1], "--help"));

    if (usage) {
        std::cout << "Print your usage" << std::endl;
    }
    return usage;
}

int main(int argc, char *argv[])
{
    /* Set eval to default value */
    int eval = EXIT_SUCCESS;

    try {
        if (!checkHelp(argv)) {
            /*
            ** do some stuff here
            */
        }
    } catch (std::exception const &err) {
         /* update eval on throwed exceptions */
         eval = EXIT_FAILURE;
         std::cerr << "error: " << err.what() << std::endl;
    }
    return eval;
}

Doing by this way, you can manage all your program execution in error context and choose what to do : update return value, do other stuff, etc.
You don't break your main thread and prevent you from memory errors/leaks without exit by exit() function.
1) eval (for 'exit value') is instancianted and destroyed with main context. In accordance with the type of main's return value, we have to change it's value if an error occurred before returning it while exit the program.
2) In my example, I send argv to the checkHelp function who returned true if the first argument of my software (argv[1] here) is equal to "-h" or "--help", if not checkHelp returns false. You can also do a loop on all argv arguments received by main.
3) Finally, catch (std::exception const &err) allows you to get your throwed exception by reference and print his message. So, you are using your main try/catch block in all his integrity.

A: Here is my personal opinion: there isn't a best practice way but I prefer the first approach!
1. Approach:
https://en.cppreference.com/w/cpp/utility/program/exit
You can call the following function:
std::exit( EXIT_FAILURE );

2. Approach:
Create an exception.
throw "Please call me with some parameters!"

But I do not prefer this approach. For some users the exception looks like there is an internal software error...


text:
Q: Referencing an existing property in Object Literal Instantiation for Linq to Entity public class Person
{
  public string FirstName { get; set; }
  public string LastName { get; set; }
  public string FullName { get; set; }
}

var joe = new Person {
  FirstName = "Joe",
  LastName = "Smith",
  //The following line produces the error:
  //The Name FirstName does not exist in the current context
  FullName = Firstname + " " + LastName
}

If I try to do this in C#, it will not allow me to reference the other properties.
If I do it this way:
var joe = new Person ()
joe.FirstName = "Joe";
joe.LastName = "Smith";
joe.FullName = Firstname + " " + LastName;

All is fine.
My understanding is that with Object Literal instantiation, the compiler turns everything into the second example at compile time.
However, in Linq to Entity, we have to use Object Literals in Object Instantiation like so:
List<PersonDTO> people = dbContext.Person.Where(x => x.IsAlive)
  .Select(y => new PersonDTO
                {
                  FirstName = y.FirstName,
                  LastName = y.LastName,
                  FullName = ???
                }

I know I can reference y.FirstName + " " y.LastName but that creates extra code in the resulting SQL query.
And while this is a simple example, I'm working with much larger and more complex data sets.
So the question is:
Is there a way to concatenate properties together in an Object Literal Instantiation?
If not, can I pass y into an object constructor somehow?
If not, what is the best way to do something like this?

A: My recommendation in this case is use a NotMapped property in your Person entity:
public class Person
{
  //..
  [NotMapped]
  public string FullName
  get
  {
    return FirstName + " " + LastName;
  }
}

A: If your looking for a way to create a FullName property in your class, then the best way to do this is to create a class file in your project that contains a partial class to Person.
public partial class Person
{
   public string FullName
     get
     {
       return FirstName + " " + LastName
     }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why linear_search function do not work correctly? Why this code works only if target==theFirstElement ? it return None even though target==5 or any other element in the list.
def linear_search(lista, target):
    for i in range(8):
        if lista[i]==target:
            return i
        return None

def verify(index):
    if index is not None:
        print("Target found at index:", index)
    else:
        print ("Target not found in list")

numbers =[1,2,3,4,5,6,7,8]

result=linear_search(numbers, 4)

verify(result)

A: There is a bug with your code: you should return None only once the for loop is done and you visited all the elements:
def linear_search(lista, target):
    for i, elem in enumerate(lista):
        if elem == target:
            return i
    # if you don't find the target return None
    return None

A: If you want to know if a particular value can be found in a list and you want the index of where it's found then you could do this:
def linear_search(lista, target):
  try:
    return lista.index(target)
  except ValueError:
    pass

This function will return either the index of the target value in the given list or None of it's not found


text:
Q: Poisson Random Variables - Application problem On a random day, the number of vacant rooms of a big hotel in New York City is 35, on average. What
is the probability that next Saturday this hotel has at least 30 vacant rooms?
I know the answer is 0.823 but do not understand how they got this.

A: Define a random variable $X$ to be the number of vacant rooms of a big hotel. Since the title is Poisson Random Variables, let's assume that this random variable is distributed Poisson. Since you know there are 35 vacant rooms on average, you have that $E(X) = 35$, so you know the parameter of your distribution. You are asked to find the probability there are at least 30 vacant rooms, this is just $P(X=30) + P(X = 31) + ....$ or $ 1 - (P(X = 0) + P(X = 1) + ... P(X = 29)) $ Both should evaluate to your desired answer, if I am not mistaken!


text:
Q: Apache problem.Failed to start I have problem with apache2 (or something else) when i do install apache2. Then i started to reinstall and this happens:
sudo apt install --reinstall apache2
Reading package lists... Done
Building dependency tree
Reading state information... Done
0 upgraded, 0 newly installed, 1 reinstalled, 0 to remove and 0 not upgraded.
Need to get 0 B/95,5 kB of archives.
After this operation, 0 B of additional disk space will be used.
dpkg: warning: files list file for package 'mysql-server' missing; assuming pack
age has no files currently installed
dpkg: warning: files list file for package 'mysql-server-8.0' missing; assuming
package has no files currently installed
dpkg: warning: files list file for package 'mysql-common' missing; assuming pack
age has no files currently installed
dpkg: warning: files list file for package 'mysql-client-core-8.0' missing; assu
ming package has no files currently installed
dpkg: warning: files list file for package 'mysql-server-core-8.0' missing; assu
ming package has no files currently installed
dpkg: warning: files list file for package 'mysql-client-8.0' missing; assuming
package has no files currently installed
(Reading database ... 177193 files and directories currently installed.)
Preparing to unpack .../apache2_2.4.41-1ubuntu1_amd64.deb ...
Unpacking apache2 (2.4.41-1ubuntu1) over (2.4.41-1ubuntu1) ...
Setting up apache2 (2.4.41-1ubuntu1) ...
Job for apache2.service failed because the control process exited with error cod
e.
See "systemctl status apache2.service" and "journalctl -xe" for details.
invoke-rc.d: initscript apache2, action "restart" failed.
● apache2.service - The Apache HTTP Server
   Loaded: loaded (/lib/systemd/system/apache2.service; enabled; vendor preset:
enabled)
   Active: failed (Result: exit-code) since Fri 2019-10-18 23:48:36 EEST; 5ms ag
o
     Docs: https://httpd.apache.org/docs/2.4/
  Process: 10605 ExecStart=/usr/sbin/apachectl start (code=exited, status=127)

жов 18 23:48:36 name systemd[1]: Starting The Apache HTTP Server...
жов 18 23:48:36 name apachectl[10605]: /usr/sbin/apachectl: 174: /usr/sbin/apache
2: not found
жов 18 23:48:36 name apachectl[10605]: Action 'start' failed.
жов 18 23:48:36 name apachectl[10605]: The Apache error log may have more informa
tion.
жов 18 23:48:36 name systemd[1]: apache2.service: Control process exited, code=ex
ited, status=127/n/a
жов 18 23:48:36 name systemd[1]: apache2.service: Failed with result 'exit-code'.
жов 18 23:48:36 name systemd[1]: Failed to start The Apache HTTP Server.
Processing triggers for systemd (242-7ubuntu3) ...
Processing triggers for man-db (2.8.7-3) ...
Processing triggers for ufw (0.36-1ubuntu3) ...

when i do type
journalctl -xe
--
-- An ExecStart= process belonging to unit apache2.service has exited.
--
-- The process' exit code is 'exited' and its exit status is 127.
жов 19 00:14:44 name systemd[1]: apache2.service: Failed with result 'exit-code'.
-- Subject: Unit failed
-- Defined-By: systemd
-- Support: http://www.ubuntu.com/support
--
-- The unit apache2.service has entered the 'failed' state with result 'exit-cod
жов 19 00:14:44 name systemd[1]: Failed to start The Apache HTTP Server.
-- Subject: A start job for unit apache2.service has failed
-- Defined-By: systemd
-- Support: http://www.ubuntu.com/support
--
-- A start job for unit apache2.service has finished with a failure.
--
-- The job identifier is 20214 and the job result is failed.
жов 19 00:14:44 name sudo[14155]: pam_unix(sudo:session): session closed for user
жов 19 00:15:00 name xdg-desktop-por[2472]: Failed to get application states: GDB
жов 19 00:15:01 name CRON[14237]: pam_unix(cron:session): session opened for user
жов 19 00:15:01 name CRON[14238]: (root) CMD (command -v debian-sa1 > /dev/null &
жов 19 00:15:01 name CRON[14237]: pam_unix(cron:session): session closed for user

A: It looks to me that mysql needs to be reinstalled (note the warnings in your post about mysql). Have a look at this post: how to reinstall mysql?


text:
Q: ZipOutputStream blocking Vertx event loop I am working on a scenario where I am reading files in a directory and then creating a zip file.
But this operation sometimes blocks the Vertx thread and I received the following exception in Vertx trace:
021-06-01 14:46:22.533 io.vertx.core.impl.BlockedThreadChecker [WARNING] Thread Thread[vert.x-eventloop-thread-4,5,main]=Thread[vert.x-eventloop-thread-4,5,main] has been blocked for 65088 ms, time limit is 2000 ms
io.vertx.core.VertxException: Thread blocked
    at java.util.zip.Deflater.deflateBytes(Native Method)
    at java.util.zip.Deflater.deflate(Deflater.java:444)
    at java.util.zip.Deflater.deflate(Deflater.java:366)
    at java.util.zip.DeflaterOutputStream.deflate(DeflaterOutputStream.java:251)
    at java.util.zip.DeflaterOutputStream.write(DeflaterOutputStream.java:211)
    at java.util.zip.ZipOutputStream.write(ZipOutputStream.java:331)

Following is my method for creating a zip file
 private String zipDirectory(File dir, String zipDirName) {
     _log.info("Entered zip file utility2");
     String zipFilePath;

        try(FileOutputStream fos = new FileOutputStream(zipDirName);
            ZipOutputStream zos = new ZipOutputStream(fos);) {
            populateFilesList(dir);

            for(String filePath : _filesListInDir){
                _log.info("FILES: "+filePath);
                File file = new File(filePath);

                if(!"zip".equals(Files.getFileExtension(file.getName()))) {
                    ZipEntry ze = new ZipEntry(filePath.substring(dir.getAbsolutePath().length()+1, filePath.length()));
                    zos.putNextEntry(ze);
                    FileInputStream fis = new FileInputStream(filePath);
                    byte[] buffer = new byte[1024];
                    int len;
                    while ((len = fis.read(buffer)) > 0) {
                        zos.write(buffer, 0, len);
                    }
                    zos.flush();
                    zos.closeEntry();
                    fis.close();

                }else {
                    _log.info("Ignore zip for writing");
                }

            }
            Path zipFilePathDir = Paths.get(zipDirName);
            zipFilePath = zipFilePathDir.getFileName().toString();
            _log.info("Zip file name: "+zipFilePath);
            zos.close();
            fos.close();
        } catch (IOException e) {
            zipFilePath = "FAILURE";
            _log.error("Error creating zip file: "+e.getMessage());
        }

        return zipFilePath;
    }

Can anyone provide any  suggestion as how can I make sure that I dont block the main event loop on Vertx

A: You can use Vertx.executeBlocking to run the method in a worker pool managed by Vert.x:
Future<String> fut = vertx.executeBlocking(promise -> promise.complete(zipDirectory(dir, zipDirName));

If your method needs to block for more than 5 or 10 seconds, you may also want to create your own dedicated ThreadPool just for executing that method, which Vert.x calls a WorkerExecutor, and use WorkerExecutor.executeBlocking instead.
// Create a WorkerExecutor with 1 thread, where each method call
// can run for 2 minutes before Vertx logs blocked thread warnings
WorkerExecutor we = vertx.createSharedExecutor("zip", 1, 2, TimeUnit.MINUTES)
Future<String> fut = we.executeBlocking(promise -> promise.complete(zipDirectory(dir, zipDirName));


text:
Q: How to fill in NA values with grouped means in R Say I have a df that looks like:
rat  let num
1     A   3
3     c   12
3     B   41
1     B   NA
1     A   NA
2     B   2
2     C   20
1     C   NA
2     A   33
3     C   10

I would like to group_by 'rat' and 'let' and get the mean of 'num' for each group and use that to fill in the NA values.
I have done the grouping and got the mean but don't know how to apply the values to fill in the NA values in my original df. Different methods would be greatly appreciated! Thanks.
df %>% group_by(rat,let) %>% summarise(num_avg = mean(num,na.rm=T))

A: Here's one way.
df <- df %>% group_by(rat,let) %>% mutate(num_avg = mean(num,na.rm=T))
df$num[is.na(df$num)] <- df$num_avg[is.na(df$num)]

A: Here is one option with ave and na.aggregate from zoo
library(zoo)
df$num <- with(df, ave(num, rat, let, FUN = na.aggregate))


text:
Q: How do I completely recreate my database in Android Room? I have a situation where I want to be able to do a hard reset of my database using Android Room. Using SQLiteOpenHelper, I could do this by writing a method to drop all tables and indices, then manually call SQLiteOpenHelper.onCreate().
I'm aware that I can get access to a SupportSQLiteOpenHelper via room and drop all the tables myself, but there doesn't seem to be a good way to kick-off the recreation process.
Also, I'm aware that I could delete every item from each table without dropping it, but that's not what I want. That doesn't reset the auto-incrementing primary key, so the "id" field of new items won't reset back to 1.
Thanks!
EDIT:
This is something I want to be able to do arbitrarily at runtime.
EDIT 2:
The method should be maintainable, i.e. not involve hand-writing SQL that matches Room's behavior. Ideally there would be some way to retrieve the SQL that Room generates, or a SQLiteOpenHelper.onCreate() equivalent method. Or anything else that solves this problem! :)

A: Simple answer is to increment your @Database version number. Generally speaking you should do this for schema changes, however it will achieve your aims of clearing the database and resetting all primary key values.
@Database(entities = { Hello.class }}, version = 1) // <- you want to increase version by 1
@TypeConverters({})
public abstract class AppDatabase extends RoomDatabase {
    public abstract HelloDao helloTextDao();
}

EDIT: IF you want to do this at run time, I would clear all the data from your tables (to avoid FK issues), then call DROP TABLE table_name, on all of your respective tables. Then you will need to write queries for creating the tables ie : CREATE TABLE table_name (uid INTEGER PRIMARY KEY, name STRING);.
This will mean you have to maintain a list of create table queries up to date with your POJO's unfortunatly. Ideally you'd be able to use reflection to generate the query, howerever @ColumnInfo currently doesn't support reflection as it has its RetentionPolicy set to CLASS.
Hopefully this solves your problem, feel free to ask for further clarification in the comments. Happy hunting!

A: I found it easiest to do this via context.deleteDatabase("name") and then simply reinstantiating and repopulating the database via the Room.databaseBuilder().addCallback upon first access.

A: This may help you.

*

*upgrade your Database version

*When you call DatabaseBuilder, remember add this to your code fallbackToDestructiveMigration
Room.databaseBuilder(context, Database::class.java, DB_NAME)
.allowMainThreadQueries()
.fallbackToDestructiveMigration()
.build()
More detail please refer this

A: For my case, deleting database with context.deleteDatabase("name") still caches the data of the old database.
I solved this by manually deleting the database file
File databasesDir = new File(context.getApplicationInfo().dataDir + "/databases");
new File(databasesDir, "MyDatabaseName.db").delete();

A: I was not able to find a way to do this programatically.
But, you can go to yourApp -> Long click -> App Info -> Storage & Cache -> clear both cache and Storage.
Clearing storage displays a verification dialog that indicates that databases will be destroyed.

A: As per the answers given here, and here, and here, I could do it as following:
public void deleteAndReset() {
    SQLiteDatabase database;
    database = SQLiteDatabase.openOrCreateDatabase(context.getDatabasePath(MY_DATABASE_NAME), null);
    String deleteTable = "DELETE FROM " + MY_TABLE_NAME;
    database.execSQL(deleteTable);
    String deleteSqliteSequence = "DELETE FROM sqlite_sequence WHERE name = '" + MY_TABLE_NAME + "'";
    database.execSQL(deleteSqliteSequence);
}


text:
Q: Reporting Services 2005: matrix plus table has not the expected width I have a problem with a report that contains a matrix and a table to it´s right. The matrix contains 13 columns, the table one column. The columns are designed so that in interactive view, they have a combined width of 26.5 cm: 5.5 cm + 12 * 1.5 cm + 3cm, fitting a DinA4 page.
The report is rendered correctly in Internet Explorer 9 but in all other browsers I use (FF, Opera, Safari, all pretty much up to date), the matrix is much to slim, only stretching just about over half of the page.
Without the table right to the matrix, everything is rendered fine in all browsers.
Using a rectangle around elements didn´t help.
Has anyone perhaps had a similar issue? I use Reporting Services 2005.

A: Rendering for SSRS 2005 and ReportViewer version 9 are terrible in non-IE browsers. MSDN recommends IE 6 or 7 for viewing reports.
Starting with VS2010 and ReportViewer version 10 browser support improved... a lot. I think upgrading is really your only option (short of telling your users to stick with IE).
You haven't told us how your users are viewing the report: through the web manager, the ReportViewer, or some other way? If it's through a ReportViewer, AFAIK you can hook up the 10.0.0.0 controls to SSRS 2005 as well.


text:
Q: jquery append not working in IE works fine in FF this code works fine in FF, not in IE.
var target = $("#targetSelectBox")
var vals   = values.split(";");
for (var i = 0; i < vals.length; i++) {
        var parts = vals[i].split(":");
 target.append($('<option />').val(parts[0].trim()).text(parts[1].trim()));
}

A: You're missing a semi-colon after the first line:
var target = $("#targetSelectBox")//;

Be sure that this selector is actually finding your element:
<select id="targetSelectBox">
  <!-- options to come -->
</select>

We'll also need to see the full portion of your code, including what values is to begin with. Additionally, make sure that jQuery is properly referenced, and you might even consider wrapper your inner target reference in the jQuery wrapper as well:
var newOption = $("<option>").val( parts[0] ).text( parts[1] );
$(target).append(newOption);

Functional example online: http://jsbin.com/ibeci/edit


text:
Q: Наследование от абстрактного класса Есть следующий не большой проект:
AbstractClass.cs
public abstract class AbstractClass
{

}

Gover.cs
class Gover : AbstractClass
{

}

Program.cs
class Program
{
    public List<AbstractClass> list;
    void Main(string[] args)
    {
        list = new List<Gover>(); //Ошибка: Неявное преобразование типа "...List<abstrac.Gover>" в "...List<abstrac.AbstractClass>
    }

Но появляется (как показано выше) ошибка не понятная мне. Почему я не могу присвоит объекту AbstractClass объект Gover? Ведь Gover унаследован от AbstractClass?

A: Проблема вот в чём: List<T> не ковариантен по T. Нормальными словами: Если T1 — подкласс T2, то при этом List<T1> не подкласс List<T2>.
Почему это так? Смотрите. Допустим, что такое, как вы написали, было бы возможно:
public List<AbstractClass> list;

List<Gover> goverList = new List<Gover>();
list = goverList;

Тогда было бы возможно написать:
list.Add(new Gover2());

где Gover2 — другой потомок AbstractClass. То есть в списке goverList, который вроде бы имеет тип List<Gover>, внезапно оказался бы элемент постороннего типа Gover2. Катастрофа!

Вывод: так, как вы написали, не получится. Пишите list = new List<Gover>(), например. Или сделайте тип списка шаблонным. Или ещё что-нибудь, в зависимости от того, что вам нужно.

A: Как уже сказал @VladD, проблема в том, что List<T> не ковариантен по T (т.к. List<T> - класс, а классы в C# могут быть только инвариантны). Однако вместо него можно использовать реализуемый им ковариантный интерфейс IEnumerable<T>, чтобы сделать ваш код рабочим. Например:
public class Test
{
    public static IEnumerable<AbstractClass> list;

    static void Main(string[] args)
    {
        list = new List<Gover>();
    }
}


text:
Q: Verify if user has account in my app with iCloud auth approach I have just read an article where it was explained how to get the token from iCloud in order to execute authentication with the iOS platform.
How can we combine Android and iOS with such an approach?
How Android will know that user has iOS account?
Which kind of credentials do I need to ask users to verify if they already have an account on the iOS platform?

A: Aleksey,
This code, confirms somebody is logged into iCloud by trying to access an iCloudKit container. The first method checks and sends a notification if it if it fails, the second method trigger by said failure shunts the user to the control panel so they can sign into iCloud.
 func isAuthorized4Cloud() {
    container = CKContainer(identifier: "iCloud.X")
    publicDB = container.publicCloudDatabase
    privateDB = container.privateCloudDatabase
    var userID: CKRecordID!
    container.fetchUserRecordID( completionHandler: { recordID, error in
        if error == nil {
            userID = recordID
            print("files_setup userID \(userID.recordName)")
            NotificationCenter.default.post(name: Notification.Name("cloudConnected"), object: nil, userInfo: nil)
        } else {
            NotificationCenter.default.post(name: Notification.Name("noCloud"), object: nil, userInfo: nil)
            print("files_setup \(error?.localizedDescription)")
        }
    })
}

In your view Controller...
  NotificationCenter.default.addObserver(self, selector: #selector(noCloud), name: Notification.Name("noCloud"), object: nil)

  func noCloud(notification:NSNotification) {
    DispatchQueue.main.async {
        self.navigation.isHidden = true
        let alert = UIAlertController(title: "Stop", message: "Sorry, you need to log into iCloud ...", preferredStyle: UIAlertControllerStyle.alert)
        let settingsAction = UIAlertAction(title: "Settings", style: .default) { (_) -> Void in
            guard let settingsUrl = URL(string: UIApplicationOpenSettingsURLString) else {
                return
            }

            if UIApplication.shared.canOpenURL(settingsUrl) {
                UIApplication.shared.open(settingsUrl, completionHandler: { (success) in
                    print("Settings opened: \(success)") // Prints true
                })
            }
        }
        alert.addAction(settingsAction)
        let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil)
        alert.addAction(cancelAction)
        self.present(alert, animated: true, completion: nil)
    }
}


text:
Q: How Bulk Creation of Custom Objects can be implemented? How Bulk Creation of Custom Objects can be implemented?
Assuming we need to replicate and debug a case where there are 3000 custom objects in the customer org. To replicate this situation, we could create as many custom objects as we could. However, it takes a lot of time to create single object.
Is there any way to automate this or create many objects at once?

A: There could be several ways to automate sobject creation, if we need to create multiple custom objects.
If you use SFDX, it is possible to use shane plugin to create custom object metadata file and then deploy those files or create a package from them and install the package.
upperlim=2000

for ((i=0; i<=upperlim; i++)); do
   echo "$i"
   sfdx shane:object:create -t custom -l "CustomObject$i" -p "CustomObjects$i" -a "CustomObject${i}__c"
done

Another option is to use Metadata API and create them in Apex
for (Integer i = 0; i < 100; i++) {
    HttpResponse res = MetadataApiCustomObjectCreate.add('CustomObject' + i);
    System.debug(res.getBody());
}

with use of the following class
public without sharing class MetadataApiCustomObjectCreate {
   private static String getSoapBodyXml(String name) {
        return ''
            + '<?xml version="1.0" encoding="utf-8"?>'
            + '<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">'
            + '<env:Header>'
            + '<urn:SessionHeader xmlns:urn="http://soap.sforce.com/2006/04/metadata">'
            + '<urn:sessionId>' +  UserInfo.getSessionId() + '</urn:sessionId>'
            + '</urn:SessionHeader>'
            + '</env:Header>'
            + '<env:Body>'
            + '<createMetadata xmlns="http://soap.sforce.com/2006/04/metadata">'
            + '<metadata xsi:type="CustomObject">'
            + '' + name + ''
            + '<pluralLabel>' + name +'s' + '</pluralLabel>'
            + '<fullName>' + name + '__c' + '</fullName>'
            + '<nameField>Name<type>Text</type></nameField>'
            + '<deploymentStatus>Deployed</deploymentStatus>'
            + '<sharingModel>ReadWrite</sharingModel>'
            + '</metadata>'
            + '</createMetadata>'
            + '</env:Body>'
            + '</env:Envelope>'
        ;
    }

    public static HttpResponse add(String name) {
        HttpRequest req = new HttpRequest();
        req.setEndpoint(URL.getOrgDomainUrl().toExternalForm() + '/services/Soap/m/50.0');
        req.setMethod('POST');
        req.setHeader('Content-Type', 'text/xml');
        req.setHeader('SOAPAction', '""');
        req.setBody(getSoapBodyXml(name));
        return new Http().send(req);
    }
}


text:
Q: HTC One keyboard does not change language, inputType=textVisiblePassword I have a problem with native HTC One keyboard in multilanguage environment.
There is a button on the keyboard which allows to switch the language:

When I enter the text in "plain" EditText this button is enabled, so I can enter text using any language.
However when the inputType=textVisiblePassword is added:
<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="textVisiblePassword" />

the change-the-language button becomes disabled:

Any another keyboard (Swype+Dragon, ...) works ok.
Does anybody know how to fix this problem?

A: I think for password fields only english language is supported as you need to validate it with server and so.


text:
Q: Raspberry PI : Pi-Hole with 2x ethernet unable to get eth1 traffic directed via pi-hole So where do I start. well after about 20 attempts maybe 30hours I have decided to ask for help :(
so what am I trying to do? Well, I have a raspberry pi with 1x onboard Ethernet which is eth0 and I have a Ethernet to USB that is eth1, on eth1 is a basic ceiling mount access point and from that we have 30-70 mobile phones connecting however I am trying to limit the mobile phones or any device connecting to the AP to one website only, eth0 is connected to a switch and I have no access to the router or any other part of the network I have one port on the switch.
What have I tried:
1: I have done a direct bridge but then I can't restrict anything to one website
2: Next on the list was to forward traffic from one eth0 to eth1 but its not an WiFi dongle and everything out there is wlan0 and so related; can't get it to work
3: Pi-Hole got that working on eth0 but cant get eth1 to work with it tried different ways of configuration but not able to get any of the devices work or get an IP so.
With that said; I am trying to figure out where to go from here. I know it can be done as it was setup like this before but the SD card corrupted, don't have a back up an I did not do the original setup.
Any help or even direction would honestly be a huge help.
Thank you all in advance.


text:
Q: How to set different basepath for images in production and development in React I'm retrieving my images on production as:
src="/dibble_back_end/images/icon.png"
Which then is proxied through my nginx:
location /dibble_back_end {
    proxy_pass http://dibble_back_end:4000;
    rewrite ^/dibble_back_end(.*)$ $1 break;
}

The issue is that on development react server is running in ExpressJS not on ngInx. I'd want to based on environment variable be able to switch between production and development.
e.g.
Dev:
src="localhost:4000/images/icon.png"

Production:
src="/dibble_back_end/images/icon.png"

A: You are not providing details about your setup but if you are using Create a React App than you can use the NODE_ENV environment variable, something like:
const src = process.env.NODE_ENV === 'production' ? "/dibble_back_end/images/icon.png" : "localhost:4000/images/icon.png"

or
const basePath = process.env.NODE_ENV === 'production' ? "/dibble_back_end" : "localhost:4000";
const src = `${src}/images/icon.png`;


text:
Q: How to draw a line with touch? I am trying to draw a line with LineRenderer that follows the user's finger movements. So far I have been unable to draw a line.
This is the code i got.
how do i do it?
 var c1 : Color = Color.white;
 var c2 : Color = Color.white;

 var line : GameObject;

 var lengthOfLineRenderer : int = 5;

 function Update () {

var touchCount : int = 0;

if (Input.GetMouseButtonDown (0)) {

touchCount++;

}

if (Input.touchCount == 1) {

if (Input.GetTouch(0).phase == TouchPhase.Moved) {

  var lineRenderer : LineRenderer = line.AddComponent(LineRenderer);
  lineRenderer.SetColors(c1, c2);
  lineRenderer.SetWidth(0.2,0.2);
  lineRenderer.SetVertexCount(lengthOfLineRenderer);
  lineRenderer.SetPosition(0, gameObject.transform.position);

 }

 }

 }

A: The idea would be to check the displacement of the input position. If no movement, or too small delta, then wait, if the movement is large enough than you add a vertex and reset all positions:
This is pseudo-code:
Vector3 previous;
int vertexCount = 0;
List<Vector3>positions;
void Update(){
    if(Input.detected){
       Vector3 current = Input.position;
       if(Vector3.Distance(previous, current) < threshold){ return; }
       SetVertexCount(++vertexCount);
       positions.Add(current);
       for (int i= 0; i < vertexCount; i++)
       {
           lineRenderer.SetPosition(i, positions[i].transform.position);
       }
   }
}

The list of positions will keep all previous positions to be passed to the line renderer.
The whole input section is only pseudo code and should be turned into Desktop or mobile input.


text:
Q: How to test a Vuex module action is called in Vue component mounted function? I have a Vue component like this...
<template>

</template>

...and I am trying to test that  the mapViewModule.initalizeMapView function gets called, which is an action in my Vuex module.
I am using Jest and have looked to other answers such as: https://stackoverflow.com/a/66987942/2052752 but have had no luck....
import { shallowMount, createLocalVue } from "@vue/test-utils";
import Vuex from "vuex";
import GeospatialMap from "@/components/Geospatial.vue";

describe("GeospatialMap - ", () => {
  const localVue = createLocalVue();
  localVue.use(Vuex);
  const modules = {
    mapViewModule: {
      state: {},
      actions: {
        initializeMapView: jest.fn()
      },
      namespaced: true
    }
  };
  const store = new Vuex.Store({ modules });

  shallowMount(GeospatialMap, { localVue, store });

  it("when component created, initializes the map view", async () => {
    expect(modules.mapViewModule.actions.initializeMapView).toHaveBeenCalled();
  });
});

Simply put...the jest.fn says its not called in the console..
expect(jest.fn()).toHaveBeenCalled()

    Expected number of calls: >= 1
    Received number of calls:    0

I'm not sure where it is going wrong. Am I not mocking the module action right?
I just want to test that the Vuex action gets called when this component is initialized.

A: Yep, you are not mocking the store right. And I also would like to say, that you are using the store in a little strange way but it is up to you.
I made some changes to component to make the decision of your problem as clear as possible.
<template>

    I am

</template>

When your are calling mapViewModule.initializeMapView in mount hook you are just using simple js-function so I tried to mock that call by creating __mock__ folder in @/helpers/ with someModule.ts file in it with the code below:
// @/helpers/__mock__/someModule.ts
export const mapViewModule = {
  initializeMapView: jest.fn((el: HTMLDivElement) => console.log('I am MOCK!!!', el))
}

Then in spec-file we must tell Jest to use our mock-file instead of real file like that:
import { shallowMount, Wrapper } from '@vue/test-utils'
import GeospatiaMap from '@/components/GeospatiaMap/GeospatiaMap.vue'
import { mapViewModule } from '@/helpers/someModule'

jest.mock('../../helpers/someModule.ts') // there you put your path to module you want to mock
let wrapper: Wrapper<GeospatiaMap & { [key: string]: any }>

describe('GeospatiaMap.vue', () => {
  test('initializeMapView was called', () => {
    wrapper = shallowMount(GeospatiaMap) // wrapper property is useless now but you can use it your future tests
    expect(mapViewModule.initializeMapView).toBeCalled()
  })
})

That's it. Hope that'd help.


text:
Q: Passport-Facebook not Searching my model I am trying to use passportjs with facebook and on sails js.in the middleware, this is my implementation
var verifyHandler = function (token, tokenSecret, profile, done) {
process.nextTick(function () {

    //check if the user exist or not
    var uid=profile.id;

    User.findOne({uid:profile.id}).done(function(err,user){
       if(user)
       {
        console.log('found');
        //done(null,user);
       }
       else
       {
        console.log('user does not exists');
       }
     });
   };

The weird thing is that it is not able to search through the model.Where Am I doing it wrongly?

A: I have finally figured it out and I hope it will assist anyone having the same issue with MySQL.
1. Within your user model, the uid datatype should be a STRING not an INTEGER.Please make sure you have effect the same changes on the database table structure to VARCHAR.
2.Change middleware.js verifyHandler to this(omitting parseInt)
var passport = require('passport')
, GitHubStrategy = require('passport-github').Strategy
, FacebookStrategy = require('passport-facebook').Strategy
, GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;

var verifyHandler = function (token, tokenSecret, profile, done) {
process.nextTick(function () {

    User.findOne({uid: profile.id}).done(function (err, user) {

            if (user) {
               return done(null, user);

            } else {

                var data = {
                    provider: profile.provider,
                    uid: profile.id,
                    name: profile.displayName
                };

                if(profile.emails && profile.emails[0] && profile.emails[0].value) {
                    data.email = profile.emails[0].value;
                }
                if(profile.name && profile.name.givenName) {
                    data.firstname = profile.name.givenName;
                }
                if(profile.name && profile.name.familyName) {
                    data.lastname = profile.name.familyName;
                }

                User.create(data).done(function (err, user) {
                        return done(err, user);
                    });

          }

        });

});
};

passport.serializeUser(function (user, done) {
done(null, user.uid);
});

passport.deserializeUser(function (uid, done) {
User.findOne({uid:uid}).done(function (err, user) {
    done(err, user)
});
});
module.exports = {

// Init custom express middleware
express: {
    customMiddleware: function (app) {

        passport.use(new FacebookStrategy({
                clientID: "****",
                clientSecret: "********",
                callbackURL: "http://localhost:1337/auth/facebook/callback"
            },
            verifyHandler
        ));

        app.use(passport.initialize());
        app.use(passport.session());

    }
}

};

Hope this helps someone out.Cheers!


text:
Q: Mutlilevel expandable listview How to parse below json in multilevel expandable listview Any idea or suggesstion is appreciated.
 {
        "Company": {
            "HR Dept.": [],
            "Admin": [],
            "Technology": [
                {
                    "T_NAME": "TEAM1",
                    "T_MEMBERS": [
                        "XYZ",
                        "PQR"
                    ]
                },
                {
                    "T_NAME": "TEAM2",
                    "T_MEMBERS": [
                        "STU",
                        "WXY"
                    ]
                },
                {
                    "T_NAME": "TEAM3",
                    "T_MEMBERS": [
                        "ABC",
                        "DEF",
                        "GHI"
                    ]
                }
            ]
        }
    }


text:
Q: ng-click to affect only the element it is inside I am using ng-repeat to generate some elements...

{{ form.form_name }}

{{ form.url }}

{{ form.count }}

{{ form.submit }}

As you can see, ng-click="showResults()" toggles the display of the other elements. The problem is, I only want the ng-click to toggle the elements inside the same container, not toggle all elements.
In short, I only want the click event to affect the elements in the same container that the function is called, how can I do this?
this is showResults in my controller...
$scope.showResults = function(){
  return ($scope.results ? $scope.results=false : $scope.results=true)
}

A: ng-repeat provides you with a special variable (unless you already have an identfier): $index.
Using this, you can store (instead of a single boolean value) an object $index => toggleState in your angular code:
$scope.hiddenHeroes = {};

$scope.toggleHero = function (idx) {
    $scope.hiddenHeroes[idx] = !$scope.hiddenHeroes[idx];
}

And in your HTML:

  {{hero}}

  All you want to know about {{hero}}!

  Toggle {{hero}}

See it live on jsfiddle.net!

A: You can use $index to index item/containers and show the corresponding results:

{{ form.form_name }}

{{ form.url }}

{{ form.count }}

{{ form.submit }}

And your function
$scope.showResults = function(index){
  return ($scope.results[index] ? $scope.results[index]=false : $scope.results[index]=true)
}


text:
Q: Whats the best practice for creating Stateless Utility classes in Java What's the best practice for creating the Utility (which do not hold any state) classes in Java.
In most of the cases we end up creating static methods for such tasks.
Other possible way could be "create the singleton objects" for performing this operation.
What should be the design consideration when requirement is the code should be easily unit testable?

A: I think the most common way is to create static methods. As an example see StringUtils in Apache Commons Lang, Strings in Guava or even Arrays in JDK.
Also the class should be made final and it should have a private constructor to avoid inheriting it or instantiating it.
Either you use static methods or a singleton, it should be the same effort to unit test it. In the latter case, you might write a little bit more code (characters).
I know that OO purists will argue the very existence of such classes and I will tend to agree with them, but these are added only for the sake of simplicity and you should limit the number of such classes.

A: If you'll indulge my metaphor for a bit…
You probably have seen one of these before:

Notice that we call it a toaster.  We do not call it a "BreadUtil."
Similarly, utility methods can and should be placed in a class named for specific functionality, not "miscellaneous stuff related to bread."
Most of the time, your static methods belong on a related class;  for instance, Integer.parseInt is a static method of the Integer class, not a member of a theoretical IntegerUtil or NumberUtil class.
In the past, one case for creating a separate utility class was when the primary class of interest was an interface.  An example of this is java.util.Collections.  However, as of Java 8, this is not an excuse, as interfaces can have static methods and default methods.  In fact, Collections.sort(List) has already been migrated to List.sort.
If you have a lot of utility methods and you feel they would clutter the relevant class, it's fine to put them in a separate class, but not a "BreadUtil" class.  It is never acceptable to put the word "util" in a class name (or "utils," "utilities," "misc," "miscellaneous," "general," "shared," "common," or "framework").  Give the class a meaningful name that describes what the methods are for.  If the methods are too diverse to allow for such a class name, you probably need to split them up into multiple classes.  (Small classes with only a few methods are perfectly acceptable;  many people even consider that good design.)
Going back to the Integer example, if you felt the methods were cluttering the class, you could create new classes like this:
public class IntegerMath {
    private IntegerMath() { }

    public static int compare(int x, int y) { /* ... */ }
    public static int compareUnsigned(int x, int y) { /* ... */ }
    public static int divideUnsigned(int dividend, int divisor) { /* ... */ }
    public static int min(int a, int b) { /* ... */ }
    public static int max(int a, int b) { /* ... */ }
    public static int remainderUnsigned(int dividend, int divisor) { /* ... */ }
    public static int signum(int i) { /* ... */ }
    public static int sum(int a, int b) { /* ... */ }
    public static long toUnsignedLong(int i) { /* ... */ }
}

public class IntegerBits {
    private IntegerBits() { }

    public static int bitCount(int i) { /* ... */ }
    public static int highestOneBit(int i) { /* ... */ }
    public static int lowestOneBit(int i) { /* ... */ }
    public static int numberOfLeadingZeros(int i) { /* ... */ }
    public static int numberOfTrailingZeros(int i) { /* ... */ }
    public static int reverse(int i) { /* ... */ }
    public static int reverseBytes(int i) { /* ... */ }
    public static int rotateLeft(int i, int distance) { /* ... */ }
    public static int rotateRight(int i, int distance) { /* ... */ }
}

public class IntegerParser {
    private IntegerParser() { }

    public static int parseInt(String s) { /* ... */ }
    public static int parseInt(String s, int radix) { /* ... */ }
    public static int parseUnsignedInt(String s) { /* ... */ }
    public static int parseUnsignedInt(String s, int radix) { /* ... */ }
}

The last of those is an example of something that might be better without static methods:
public class IntegerParser {
    public IntegerParser() { this(10); }
    public IntegerParser(int radix) { /* ... */ }

    public int parseInt(String s) { /* ... */ }
    public int parseUnsignedInt(String s) { /* ... */ }
}

A: If you use frameworks like Spring, you can create a utility class with @Service annotation.
This will ensure it's single instace (SIngleton), and an easy way to inject it itno any other class which'll have a need in its methods.
In any other case, I'd suggest to make it a singleton, using factory pattern, or in cotrast, using only static methods.

A:
What's the best practice for creating the Utility (which do not hold any state) classes in Java.

In my opinion the best way is to omit utility classes whenever possible.
A utility class reverses the idea of object-oriented programming. When you come to the point that you need a new method you usually add it to the class with the highest cohesion. This means to the class that holds most of the information the method needs. The other information will be passed into  the method as parameters. If the parameter list gets too long it is often an indicator for a misplaced method.
There are rare situations when you really need a utility class to provide a method for some type. E.g.

*

*if you can't add the method to the source code, because you do not own it (But you might either create a wrapper or subclass it)

*if a class that needs the additional method is final and you don't own the source code (e.g. StringUtility)

In most of the cases we end up creating static methods for such tasks. Other possible way could be "create the singleton objects" for performing this operation.
What should be the design consideration when requirement is the code should be easily unit testable?

If you take a look at utility classes from a unit testability perspective and you want to be able to mock the utiltiy class you should use the singleton, because object references can be replaced.
Either by changing the singleton instance reference (the static variable) or at the client side by using an object field. E.g.
 private SomeUtility someUtility = SomeUtiltiy.INSTANCE;

 public void someMethod(...){
    // Can be replaced by changing the someUtility reference
    someUtility.doSomething(....);

    // A static call like
    // SomeUtility.doSomething(...);
    // can not be easily replaced.
 }

Static method calls are hard to replace. Some test frameworks like powermock support mocking of static calls by rewriting the client bytecode. But I think that those frameworks were designed to support unit testing of bad legacy code. If you need powermock for new code you should rethink your design.

A: Static is a singleton. singleton instance with non-static methods need only when you need multiple Utility class variations with different property(ies)/setting(s) value(s) to use. As example when your utility has some property (i.e. customProperty) and you need two different cases at the same time.

*

*when Utility need to use customProperty=value1

*when Utitlity need to use customProperty=value2...
but it is quite strange, clumsy and not good... Utility caller can provide needed property value into static method.
So, do not stuck with that. Make Utility methods always static and do not care about "theoretical" patterns... :)


text:
Q: Home loan calculation formula (algorithm)? How a bank calculate home loan's payments?
For example,

$1,000,000 at 5.00% over a 25 year period.
Monthly payment: $5,845.90

              Current Payment                                 To Date
Payment  --------------------------        ----------------------------------------------
Number   Interest         Principal        Interest Paid    Principal Paid    Balance
1        $4,166.67        $1,679.23        $4,166.67        $1,679.23         $998,320.77
2        $4,159.67        $1,686.23        $8,326.34        $3,365.46         $996,634.54
3        $4,152.64        $1,693.26        $12,478.98       $5,058.72         $994,941.28
4        $4,145.59        $1,700.31        $16,624.57       $6,759.03         $993,240.97
5        $4,138.50        $1,707.40        $20,763.07       $8,466.43         $991,533.57
6        $4,131.39        $1,714.51        $24,894.46       $10,180.94        $989,819.06
7        $4,124.25        $1,721.65        $29,018.71       $11,902.59        $988,097.41
8        $4,117.07        $1,728.83        $33,135.78       $13,631.42        $986,368.58
9        $4,109.87        $1,736.03        $37,245.65       $15,367.45        $984,632.55
10       $4,102.64        $1,743.26        $41,348.29       $17,110.71        $982,889.29
I'm trying to do same calculations in Excel, but I get another numbers...

A: The algorithms are well shown and discussed here (in Javascript) -- implement exactly the same algorithms in Excel's VBA, Javascript, Ruby, whatever, and you'll get pretty much the same results!-)

A: the magic words are amortization schedule.

A: The difference you see in Excel is probably to do with the way the compound interest is calculated. Most banks add compound interest daily (gets them more money).
The wikipedia article has a nice example of the equation used by US banks. You can code that up.


text:
Q: Subtract at runtime in Android I have three edittext named et1,et2,et3. I want to subract et1 and et2 and show the answer in et3. But this should be done without clicking any button. As soon as I write values in et1 and et2, the calculations have to be done and displayed in et3.
Thank You,
Spandan Joshi

A: You will need to use addTextChangedListener() on edittext.
Check this link - android on Text Change Listener
Hope it will help you!


text:
Q: Dynamic Mapping and Concat with Grunt Uglify I'm trying to use dynamic mapping AND concat Javascript files with Grunt Uglify.
I have the following which is not working correctly.
Here is my folder structure:
javascript
    |- account
        |- custom.js
    |- bills
        |- billing-one.js
        |- billing-two.js
    |- test (output folder)

Here is what I'm expecting:
javascript
    |- account
        |- custom.js
    |- bills
        |- billing-one.js
        |- billing-two.js
    |- test
        |- billing-one.min.js (this file includes billing-one.js AND custom.js)
        |- billing-two.min.js (this file includes billing-two.js AND custom.js)

This is what I'm currently getting:
javascript
    |- account
        |- custom.js
    |- bills
        |- billing-one.js
        |- billing-two.js
    |- test
        |- bills
            |- billing-one.min.js (this file includes just billing-one.js)
            |- billing-two.min.js (this file includes just billing-two.js)
        |- account
            |- custom.min.js (this file includes just custom.js)

It is not including the custom.js file but instead creates a 2 folders test/account/custom.min.js
'test/bills/billing-one.js' - see above
options: {
    beautify: true,
    mangle: false,
    compress: false,
    preserveComments: 'all'
},
files: [
  {
    expand: true,     // Enable dynamic expansion.
    cwd: 'javascript/',      // Src matches are relative to this path.
    src: [[bills/*.js'], 'account/custom.js'], // Actual pattern(s) to match.
    dest: 'test/',   // Destination path prefix.
    ext: '.min.js',   // Dest filepaths will have this extension.
    extDot: 'first'   // Extensions in filenames begin after the first dot
  },
],

I want all the Javascript files within the bills/ folder to contain custom.js
So if there are 2 files:
bills/billing-one.js
bills/billing-two.js
I would expect test/ folder to include
test/billing-one.min.js (this file would contain billing-one + custom.js)
test/billing-two.min.js (this file would contain billing-two + custom.js)
I don't want to hard code the file names in. If more files are added tobills/ folder the should be concat and output to the test/ folder.
Any help much appreciated.
UPDATE SINCE ANSWER ACCEPTED:
Use the follow updated code to make sure this works as intended - otherwise you'll run into errors when running GRUNT.
I did try adding this to the answer by submitting an edit for review. But it got rejected, twice, by the all knowing all superior mods... when in fact it's a valid input and improves on the answer given. Note the [], cwd and src changes.
files: [{
    expand: true,
    cwd: 'javascript/bills/',
    src: ['*.js'],
    dest: 'test/',
    ext: '.min.js',
    extDot: 'first'
}],

A: You can use the banner property of grunt-contrib-uglify to append the content.
https://github.com/gruntjs/grunt-contrib-uglify#banner
Here is the grunt configuration:

grunt.initConfig({
    uglify: {
      options: {
        banner: grunt.file.read('./javascript/account/custom.js'),
        beautify: true,
        mangle: false,
        compress: false,
        preserveComments: 'all'
      },
      files: {
        expand: true,
        cwd: 'javascript/',
        src: ['bills/*.js'],
        dest: 'test/',
        ext: '.min.js',
        extDot: 'first'
      },
    }
  });

In the above configuration every file in the bills folder will get the content of custom.js configured in the banner property.
I hope it helps you.


text:
Q: Neuralnet in R not giving me what I want to see I am currently working on some research and we are trying to do some Time-Series prediction using neural networks. To get started, I was using the paper published by G. Peter Zhang (Time Series forcasting using a hybrid ARIMA and NN model) since I am no expert in either R or statistics, I could really do with some help.
I got R and the neuralnet lib setup and then took the Lynx dataset, then created a data-frame with the data long with the lags to set as input. My data now looks something like this (this is only for t, t-1, and t-2 lags)
     x     x1    x2
1   269    NA    NA
2   321   269    NA
3   585   321    269

Now I want to train a NN with input x1 and x2 and get output at x.
I do the training with the following code
nn <- neuralnet(x~x1+x2, data=dat, hidden = 2, linear.output = T) # I am using t-1 ... t-4 so using hidden layer of 2

This does train the model, but the error is really high, and when I use it to do any computation the results of the second layer neuron is alway 1. I was discussing with some freinds and they said that its because I am maybe using the wrong activation function. I looked in the help for the act.fct and tried with both logistic and tanh but the results remain the same.
I have been stuck on this for a few days now, so could really use some help. May I am doing something wrong? Or missing something?
Thanks

A: So,
Ill probably answer my own question, as now after more than a week of trying to figure out what was going wrong, I think I know what I was doing, and how to maybe solve it.
Firstly, I was having the problem with the hidden layer neurons, in that they would always output 1, now that was absurd and I did some looking under the hood, turns out everything was as it should be, i.e I did not do any mistake and the activation function was the sigmoid func that I wanted, the error is coming from the fact that the model is not adjusting the weights to lower the inputs to the hidden layer, and if the input to the hidden layer is any where close to 10 the sigmoid function is outputting a 1, which is then messing things up. Normally I would assume the weights to compensate for this, but some how it's not happening.
A work around I found that seems okay at the moment is to normalize the data, it is giving me better results, but not as great as I'd expect. So? Use MATLAB its giving me a great OP


text:
Q: Matrix derivative of a matrix with constraints I am looking for a general method to obtain derivative rules of a constrained matrix with respect to its matrix elements.
In the case of a symmetric matrix $S_{ij}$ (with $S_{ij}=S_{ji}$), one way to do that is the following (see Variation of the metric with respect to the metric). We say that a variation of a matrix element $\delta S_{ij}$ is the same than that of $\delta S_{ji}$, and thus
$$
\delta S_{ij}=\frac{\delta S_{ij}+\delta S_{ji}}{2}=\frac{\delta_{ik}\delta_{jl}+\delta_{il}\delta_{jk}}{2}\delta S_{kl}=\mathcal S_{ij;kl}\delta S_{kl}.
$$
The tensor $\mathcal S_{ij;kl}$ has the nice property that $\mathcal S_{ij;kl}\mathcal S_{kl;mn}=\mathcal S_{ij;mn}$.
One then says that
$$
\frac{\delta S_{ij}}{\delta S_{kl}}=\mathcal S_{ij;kl}.
$$
I must admit that why this is the correct procedure is not quite clear to me (that seems to be quite arbitrary, although obviously it works to compute derivatives of a function of a symmetric matrix). This means that it is not clear to me how to generalize that when the constraint is different.
For example, let's take the set of matrices $O$ belonging to the group $SO(N)$. Is there a way to write $\frac{\delta O_{ij}}{\delta O_{kl}}$ in terms of a tensor $\mathcal B_{ij;kl}$, with all the same nice properties ?
In the case of $SO(2)$, this seems quite easy, since then $O_{ji}=(-1)^{i+j}O_{ij}$, and one finds in that case
$$
\frac{\delta O_{ij}}{\delta O_{kl}}=\frac{\delta_{ik}\delta_{jl}+(-1)^{i+j}\delta_{il}\delta_{jk}}{2},
$$
which indeed does the job. Note however that I haven't use the defining property of $SO(N)$, that is $O O^T=1$, and I am not sure if this is relevant...
Already in the case of $SO(3)$, it does not seem to be easy to find the equivalent tensor...

Side note : using the defining property of $SO(2)$, one can massage the formulas to obtain
$$
\frac{\delta O_{ij}}{\delta O_{kl}}=-O_{il}O_{kj}.
$$
First of all, it depends explicitly on $O$, which seems bad. Furthermore, if we tentatively define $\mathcal B_{ij;kl}[O]=-O_{il}O_{kj}$ (which already is different from what we found for $SO(2)$), then we have $\mathcal B_{ij;kl}[O]\mathcal B_{kl;mn}[O]=\delta_{im}\delta_{jn}$, which seems pretty weird...

If anyone knows the standard procedure (if any exists) or a good reference, that would be greatly appreciated. In any case, a nice explanation (maybe a bit formal) in the case of symmetric matrix might also help me to get my head around the problem.

A: *

*Setup. Let there be given an $m$-dimensional manifold $M$ with coordinates $(x^1, \ldots, x^m)$. Let there be given an $n$-dimensional physical submanifold $N$ with physical coordinates $(y^1, \ldots, y^n)$. Let there be given $m-n$ independent constraints
$$ \chi^1(x)~\approx~ 0,\quad  \ldots,\quad  \chi^{m-n}(x)~\approx~ 0, \tag{1}$$
which defines the physical submanifold $N$. [Here the $\approx$ symbol means weak equality, i.e. equality modulo the constraints.] Assume that
$$(y^1, \ldots, y^n, \chi^1, \ldots,\chi^{m-n})\tag{2}$$
constitutes a coordinate system for the extended manifold $M$.

*Dirac derivative. In analogy with the Dirac bracket, let us introduce a Dirac derivative
$$\begin{align}\left(\frac{\partial}{\partial x^i}\right)_{\! D}
~:=~&\frac{\partial}{\partial x^i}
-\sum_{a=1}^{m-n}\frac{\partial \chi^a}{\partial x^i}\left(\frac{\partial }{\partial \chi^a}\right)_{\! y}
~=~\sum_{\alpha=1}^n\frac{\partial y^{\alpha}}{\partial x^i} \left(\frac{\partial }{\partial y^{\alpha}}\right)_{\! \chi}
,\cr & \qquad i~\in~\{1,\ldots, m\}, \end{align}\tag{3}$$
that projects onto the physical submanifold
$$\left(\frac{\partial}{\partial x^i}\right)_{\! D} y^{\alpha}~=~\frac{\partial y^{\alpha}}{\partial x^i} , \qquad \left(\frac{\partial}{\partial x^i}\right)_{\! D} \chi^a~=~0, $$
$$i~\in~\{1,\ldots, m\},\qquad \alpha~\in~\{1,\ldots, n\},\qquad a~\in~\{1,\ldots, m\!-\!n\}.\tag{4}$$

*Remark. In many important cases it is possible to choose the physical coordinates $(y^1, \ldots, y^n)$ such that the Dirac derivative (4) can be written as linear combinations of unconstrained partial $x$-derivatives only, without referring to the $(y,\chi)$-coordinate system (2), cf. eqs. (10) & (14) below.

*Does Dirac derivatives commute? Does the commutator
$$\left[ \left(\frac{\partial}{\partial x^i} \right)_{\! D},
\left(\frac{\partial}{\partial x^j}\right)_{\! D}\right]
~=~\sum_{\alpha,\beta=1}^n\frac{\partial y^{\alpha}}{\partial x^i}\left[\left(\frac{\partial }{\partial y^{\alpha}}\right)_{\! \chi},
\frac{\partial y^{\beta}}{\partial x^j}\right]
\left(\frac{\partial }{\partial y^{\beta}}\right)_{\! \chi} - (i\leftrightarrow j)~\stackrel{?}{\approx}~0
\tag{5}$$
vanishes weakly? Not necessarily. But if the coordinate transformation $x^i \leftrightarrow (y^{\alpha}, \chi^a)$ is linear, then the Dirac derivatives commute.

*Example. Let the physical subspace be the hyperplane $N=\{\chi(x)=0\}$ with the constraint $$\chi~=~\sum_{i=1}^m x^i.\tag{6}$$ Define physical coordinates
$$y^{\alpha}~=~ x^{\alpha} -\frac{1}{m}\sum_{i=1}^m x^i,
\qquad  \alpha~\in~\{1,\ldots, n\!=\!m\!-\!1\}.\tag{7} $$
Conversely,
$$ x^{\alpha}~=~y^{\alpha} +\frac{1}{m}\chi,
\qquad  \alpha~\in~\{1,\ldots, n\}, \qquad
x^m~=~-\sum_{\beta=1}^n y^{\beta}+\frac{1}{m}\chi.\tag{8}$$
The derivatives are related as
$$\frac{\partial}{\partial x^{\alpha}}
~=~\left(\frac{\partial }{\partial y^{\alpha}}\right)_{\! \chi} -\frac{1}{m} \sum_{\beta=1}^n\left(\frac{\partial }{\partial y^{\beta}}\right)_{\! \chi} +\left(\frac{\partial }{\partial \chi}\right)_{\! y},
\qquad  \alpha~\in~\{1,\ldots, n\}, $$
$$\frac{\partial}{\partial x^m}
~=~ -\frac{1}{m} \sum_{\beta=1}^n\left(\frac{\partial }{\partial y^{\beta}}\right)_{\! \chi} +\left(\frac{\partial }{\partial \chi}\right)_{\! y}.\tag{9}$$
The Dirac derivative becomes after some algebra
$$\left(\frac{\partial}{\partial x^i}\right)_{\! D}
~=~\frac{\partial}{\partial x^i} -\left(\frac{\partial }{\partial \chi}\right)_{\! y}
~=~\frac{\partial}{\partial x^i} -\frac{1}{m} \sum_{j=1}^m\frac{\partial}{\partial x^j},\qquad  i~\in~\{1,\ldots, m\}.\tag{10}$$

*Example. Differentiation wrt. a symmetric matrix can be viewed as a Dirac differentiation (3), where the constraints (1) are given by antisymmetric matrices. Define
$$ \begin{align}s_{(ij)}~:=~ \frac{M_{ij}+M_{ji}}{2} &\quad\text{and}\quad a_{(ij)}~:=~ \frac{M_{ij}-M_{ji}}{2}\quad\text{for}\quad i~>~j;\cr
 &\quad\text{and}\quad d_{(i)}~:=~M_{ii}.\end{align}\tag{11}$$
Conversely,
$$ M_{ij}~=~\theta_{ij}(s_{(ij)}+a_{(ij)})+\theta_{ji}(s_{(ji)}-a_{(ji)}) + \delta_{ij}d_{(i)}  ,\tag{12}$$
where the discrete Heaviside step function $\theta_{ij}$ here is assumed to obey $\theta_{ii}=0$ (no implicit sum).
The derivatives are related as
$$\frac{\partial}{\partial M_{ij}} ~=~\frac{\theta_{ij}}{2}\left(\frac{\partial}{\partial s_{(ij)}}+\frac{\partial}{\partial a_{(ij)}}\right)+\frac{\theta_{ji}}{2}\left(\frac{\partial}{\partial s_{(ji)}}-\frac{\partial}{\partial a_{(ji)}}\right) + \delta_{ij}\frac{\partial}{\partial d_{(i)}}  .\tag{13}$$
The Dirac derivative becomes after some algebra
$$ \left(\frac{\partial}{\partial M_{ij}}\right)_{\! D}~=~\frac{\theta_{ij}}{2}\frac{\partial}{\partial s_{(ij)}}+\frac{\theta_{ji}}{2}\frac{\partial}{\partial s_{(ji)}} + \delta_{ij}\frac{\partial}{\partial d_{(i)}}
~=~\frac{1}{2} \left(\frac{\partial}{\partial M_{ij}}
+\frac{\partial}{\partial M_{ji}}\right).\tag{14}$$

*Remark. Additional complications arise if the coordinates and/or constraints are not globally defined. For starters, it is actually enough if (2) is a coordinate system in a tubular neighborhood of $N$.

*Reparametrizations of the constraints. Assume that there exists a second coordinate system
$$(\tilde{y}^1, \ldots, \tilde{y}^n, \tilde{\chi}^1, \ldots,\tilde{\chi}^{m-n})\tag{15}$$
(which we adorn with tildes), such that
$$\tilde{y}^{\alpha}~=~f^{\alpha}(y), \qquad  \tilde{\chi}^a ~=~ g^a(y,\chi)~\approx~0.\tag{16}$$
This implies that
$$
\left(\frac{\partial }{\partial \chi^a}\right)_{\! y}
~=~ \left(\frac{\partial \tilde{\chi}^b}{\partial \chi^a}\right)_{\! y}  \left(\frac{\partial }{\partial \tilde{\chi}^b}\right)_{\! \tilde{y}}, \qquad
\left(\frac{\partial }{\partial y^{\alpha}}\right)_{\! \chi}
~\approx~\left(\frac{\partial \tilde{y}^{\beta}}{\partial y^{\alpha}}\right)_{\! \chi} \left(\frac{\partial }{\partial \tilde{y}^{\beta}}\right)_{\! \tilde{\chi}},
\tag{17}$$
i.e
$$\Delta_{\chi}~:=~{\rm span}\left\{\left(\frac{\partial }{\partial \chi^1}\right)_{\! y}, \ldots ,\left(\frac{\partial }{\partial \chi^{n-m}}\right)_{\! y}\right\} ~\subseteq~ TM\tag{18}$$
is an involutive distribution, while
$$\Delta_y~:=~{\rm span}\left\{\left(\frac{\partial }{\partial y^1}\right)_{\! \chi}, \ldots ,\left(\frac{\partial }{\partial y^n}\right)_{\! \chi}\right\} ~\subseteq~ TM\tag{19}$$
is a weak distribution.
One may show that the Dirac derivative and its commutators
$$ \left(\frac{\partial}{\partial x^i}\right)^{\sim}_{\! D}~\approx~\left(\frac{\partial}{\partial x^i}\right)_{\! D}, \qquad
\left[ \left(\frac{\partial}{\partial x^i} \right)^{\sim}_{\! D},
\left(\frac{\partial}{\partial x^j}\right)^{\sim}_{\! D}\right]~\approx~
\left[ \left(\frac{\partial}{\partial x^i} \right)_{\! D},
\left(\frac{\partial}{\partial x^j}\right)_{\! D}\right],
\tag{20}$$
[wrt. the tilde and the untilde coordinate systems (15) and (2), respectively] agree weakly. This shows that the Dirac derivative (3) is a geometric construction.

*Subsubmanifold. Given a $p$-dimensional physical subsubmanifold $P$ with physical coordinates $(z^1,\ldots,z^p)$. Let there be given $n-p$ independent constraints
$$ \phi^1(y)~\approx~ 0,\quad  \ldots,\quad  \phi^{n-p}(y)~\approx~ 0, \tag{21}$$
which defines the physical submanifold $P$. Assume that
$$(z^1, \ldots, z^p, \phi^1, \ldots,\phi^{n-p})\tag{22}$$
constitutes a coordinate system for the submanifold $N$. One may show that
$$\left(\frac{\partial}{\partial x^i}\right)^{\!(P)}_{\! D} ~=~\left(\frac{\partial}{\partial x^i}\right)^{\!(N)}_{\! D} - \sum_{a=1}^{n-p}\left(\frac{\partial \phi^a}{\partial x^i}\right)^{\!(N)}_{\! D}\left(\frac{\partial }{\partial \phi^a}\right)_{\!z}, \qquad i~\in~\{1,\ldots, m\}. \tag{23}$$
This shows that the Dirac derivative construction behaves naturally wrt. further constraints.

A: To me it seems a bit inappropriate to differentiate an orthogonal matrix with respect to its components. By definition, this would mean that you want to find out how the other matrix components change if you vary a component. However, this is only uniquely defined in the case of SO(2), but not for SO($N>2$). To see this more explicitly, consider a rotation in 3D. Here you have 3 angles, and if you want to change one entry there are in general different possibilities. This is of course nothing but the statement that SO($N>2$) has more than one generator.
Therefore, a more reasonable way (IMHO) to differentiate an orthogonal matrix is to write it as
$$ O=\exp(T)\;,\quad\text{where}~T~\text{is antisymmetric}$$
and differentiate w.r.t. the components of $T$ in the analogous way to what you quote for the symmetric matrix differentiation. This can be applied in a similar fashion to all matrix groups, e.g. for unitary matrices $T$ will be anti-Hermitean.
Just to elaborate on your statement that the dependence of the derivative is bad: you could derive the formula for SO(2) also by using the paramterization
$$ O=\exp(\theta\cdot T_1)=\begin{pmatrix}\cos\theta & \sin\theta\\ -\sin\theta & \cos\theta\end{pmatrix}\;,$$
where $T_0$ is the antisymmetric "unit" matrix. Then
$$ \frac{\partial O_{ij}}{\partial O_{k\ell}}=\frac{\partial O_{ij}}{\partial \theta}\cdot\frac{\partial \theta}{\partial O_{k_\ell}}=
\frac{\partial O_{ij}}{\partial \theta}\cdot\left(\frac{\partial O_{k_\ell}}{\partial \theta}\right)^{-1}\;.$$
This leads to the same result as above since
$$ \frac{\partial O}{\partial \theta}=\begin{pmatrix}-\sin\theta & \cos\theta\\ -\cos\theta & -\sin\theta\end{pmatrix}\;.$$
But it is also clear that the point at which you take the derivative matters.


text:
Q: Battery Reserve Capacity - how do you determine lower load capacity? I understand that Reserve Capacity is the number of minutes a battery can deliver a useful voltage under a 25A load. I have a 2A load and I'm researching the correct battery for my application. Is it simply a matter of dividing the 25A by my actual load to determine "my" reserve capacity?
In other words, would a battery with a Reserve Capacity rating of 120 have an effective capacity of 1,500 under a 2A load?
1,500 = 120 * (25/2)

A: No.  First there are many many types of batteries, so arbitrarily defining Reserve Capacity, whatever that is really supposed to mean, as something related to a fixed amount of current like 25 A is absurd.  A CR2032 coin cell, for example, can't ever provide remotely close to 25 A under any circumstances for any amount of time.
Your "reserve capacity" is in units of current times time (charge), which is also the units used for normal battery capacity.  Normal battery capacity is usually expressed in A-h or mA-h, but this can be directly converted back and forth to your 25A-minutes.
You can as a rough first approximation estimate battery life time by dividing its capacity by the current you will draw.  However, batteries are complicated, and this is far from a ideal relationship.  If a battery is rated for 10 Ah, for example, then you will probably get close to 2 hours of use at 5 A and 10 hours at 1 A.  But, currents both significantly smaller or larger can affect the overall capacity significantly.  Large currents usually degrade capacity.  At very small curents it can also be less because the self-discharge becomes significant.  Temperature can also have a major influence on overall capacity.
The best way to estimate length of time a battery will be good for at a particular
current is to examine the datasheet carefully.  Look at the graphs of capacity versus current, what the cutoff voltage is used to determine "dead" and how that relates to your application, and the temperature this was all assumed at.  The age of the battery will also matter, and the number of charge/discharge cycles if it's a rechargable type.  Then realize these graphs generally show typical, not minimum guaranteed, values.  Derate somewhat for worst case.
For particularly tricky cases, contact the manufacturer for guidance, and/or do a bunch of your own tests.

A: The primary usage of a car battery is to start the motor. Beyond that point all electricity should be delivered from the alternator.
When the motor is off or to much current is drawn, the additional energy must be deliverd from the battery. In such cases the battery provides some reserve energy.
In my opinion it only makes sense to talk about reserve capacity of a battery, when there's a main usage and a secondary or emergency usage. In all other cases the reserve capacity simply equals the usable battery capacity.
In any case the reserve capacity is a quantity of the application and not the battery alone. First you have to define the required current for your emergency situation, than you can take the datasheet of the battery and determine the reserve capacity.


text:
Q: The folding of ternary operator in a list The following code is available (demo)
f=lambda m, x:m and(x&1 and m.pop(0)or m.pop(0)[::-1])+f(m, x+1)
print(f([[4, 3, 2, 1], [5, 6, 7, 8], [12, 11, 10, 9], [13, 14, 15, 16]],0))

# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]

Here there is logic:
m.pop(0) if x&1 else m.pop(0)[::-1]

Please explain why when folding to the following view, is the code not executing correctly?
[m.pop(0)[::-1],m.pop(0)][x&1]

I don't know much about Python, will be grateful for any help, thank you.
UPD: If I change the logic, I get this result:
f=lambda m,x:m and([m.pop(0)[::-1],m.pop(0)][x&1])+f(m,x+1)
print(f([[4, 3, 2, 1], [5, 6, 7, 8], [12, 11, 10, 9], [13, 14, 15, 16]],0))

# [1, 2, 3, 4, 13, 14, 15, 16]

PS. Code-golf (If this is important, the essence of the code is that it bypasses the two-dimensional array in the form of a snake)
Solution:
[m.pop(0)[::-1],m.pop(0)][x&1] => (lambda: m.pop(0)[::-1], lambda: m.pop(0))[x&1]().
https://ideone.com/u6Qp4O

A: The issue is that the trinary if only evaluates one of its branch so only one pop call occurs. In your code there are two pop calls that both are evaluated.
[m.pop(0)[::-1], m.pop(0)][x&1]

To avoid that, if one must write it this way, and not using an a trinary A if C else B, one has to thunk, lambda:, each case and then after indexing the list of cases, call the case that was selected:
[lambda: m.pop(0)[::-1], lambda: m.pop(0)][x&1]()

One then could remove the common expression:
item = m.pop(0)
[lambda: item[::-1], lambda: item][x&1]()

Doing this before thunking, would result in:
item = m.pop(0)
[item[::-1], item][x&1]

This would not produce an error if item was slice-able. But it would uselessly  produce and discard a reversed copy of item. But if the item is say an int when x is odd and a list when even this would result in an error:
>>> 3[::-1]
TypeError: 'int' object has no attribute '__getitem__'

Because all sub expressions in an expression are evaluated unless they have been delayed by a lambda.
A thunk is a term for a function that takes no arguments.

A: The short-circuiting behavior is different between all three versions of the expression given (if certain elements of m are false).  The a and b or c idiom was commonly used before Python had a conditional operator, but is inequivalent if b is false.


text:
Q: (h, w) = image.shape[:2] AttributeError: 'tuple' object has no attribute 'shape' I have been trying to implement OpenCv CSRT algorithm for object tracking. Below is the code.
from imutils.video import VideoStream
from imutils.video import FPS
import argparse
import imutils
import time
import cv2
file1 = 'traffic.mp4'

tracker = cv2.TrackerCSRT_create()
initBB = None
vs = cv2.VideoCapture(file1)
fps = None

while True:
    frame = vs.read()

    if frame is None:
        break

    frame = imutils.resize(frame, width=500)
    (H, W) = frame.shape[:2]

    if initBB is not None:
        (success, box) = tracker.update(frame)
        if success:
            (x, y, w, h) = [int(v) for v in box]
            cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)

        fps.update()
        fps.stop()

        info = [
            ("Tracker", "CSRT"),
            ("Success", "Yes" if success else "No"),
            ("FPS", "{:.2f}".format(fps.fps())),
        ]

        for (i, (k, v)) in enumerate(info):
            text = "{}: {}".format(k, v)
            cv2.putText(frame, text, (10, H - ((i * 20) + 20)),
                cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2)

    cv2.imshow("Frame", frame)
    key = cv2.waitKey(1) & 0xFF

    if key == ord("s"):
        initBB = cv2.selectROI("Frame", frame, fromCenter=False, showCrosshair=True)
        tracker.init(frame, initBB)
        fps = FPS().start()

    elif key == ord("q"):
        break

vs.release()
cv2.destroyAllWindows()

I got the code from https://www.pyimagesearch.com/. But they have implemented the code for both webcam and videocapture option in addition to running it from the command line. But I just wanted to run in my IDLE for the videocapture option. So I have modified a bit to run in IDLE. But when I run it, I am getting the following error
line 20, in <module> frame = imutils.resize(frame, width=500)
  File "C:\Python37\lib\site-packages\imutils\convenience.py", line 69, in resize
    (h, w) = image.shape[:2]
AttributeError: 'tuple' object has no attribute 'shape'

Could you please point me towards the right direction.

A: The function .read() returns a bool (True/False) and a frame (an array). If the frame is read correctly, it will be True. So you should change the frame = vs.read() to _, frame = vs.read() as following (I hope it should work if there is no other errors):
...

while True:
    _, frame = vs.read()

    frame = imutils.resize(frame, width=500)
    (H, W) = frame.shape[:2]
    ...


text:
Q: fullScreenRequested does not work fully in my test browser that uses PyQt5 I am building a browser with python using pyqt5. I enabled fullscreen support and also enabled plugins,
self.webView.page().fullScreenRequested.connect(self.handleFullscreenRequest)
QWebEngineSettings.globalSettings().setAttribute(QWebEngineSettings.PluginsEnabled, True)
QWebEngineSettings.globalSettings().setAttribute(QWebEngineSettings.FullScreenSupportEnabled, True)

As you can also see that I connected fullscreenrRequested signal to a function called self.handleFullscreenRequest . Here is the function,
    def handleFullscreenRequest(self, request):

       print("requested")

       if(request.toggleOn()):
          request.accept()
          self.gridLayout.removeWidget(self.webView)
          self.webView.setParent(None, QtCore.Qt.Window)
          self.webView.showFullScreen()
       else:
          request.accept()
          self.gridLayout.addWidget(self.webView)

Result:

*

*It works very well with youtube videos, facebook videos. Videos get full screen when requested.

Problems:

*

*It doesn't work for videos of some websites including dailymotion. Video
plays but never gets full screened.

*I think it doesn't event emits the fullScreenRequested signal, as nothing is printed from handleFullscreenRequest() function in the console.

I want videos from any website to play in fullscreen mode if requested. Help me geeks please.


text:
Q: Nginx try_files points to wrong folder I'm hosting a vue history site using nginx docker and the nginx config is the following
server {
        listen 80;
        location / {
                root   /var/www/dist/;
                index  index.html index.htm;
                try_files $uri $uri/ index.html;
        }

}

I can access "http://the.ip.of.server". However when I tried to visit "http://the.ip.of.server/search", it shows the following error. It tries to open "/etc/nginx/htmlindex.html" instead of "/var/www/dist/index.html" which makes no sense.
2020/05/10 04:24:01 [error] 7#7: *2 open() "/etc/nginx/htmlindex.html" failed (2: No such file or directory),
client: xx.xx.xx.xx, server: , request: "GET /search HTTP/1.1", host: "the.ip.of.server"

I have no idea where "/etc/nginx/htmlindex.html" comes. The configuration should be right since I can access /.

A: You should put the root element outside the location block.
server {
   listen 80;
   root /var/www/dist;
   index index.html index.htm
   location / {
      try_files $uri $uri/ =404;
   }
}

After change the configuration remember to restart your nginx instance (if using docker force build image).


text:
Q: How to automatically format picture inserted in workbook via CTRL+V with macro? I use PERSONAL.XLSB to run macros in all workbooks. I have a macro that formats selected picture. Every time I paste a picture in a workbook via CTRL+V shortcut I have to press additional shortcut keys to run mentioned macro. Is it possible to somehow connect a macro to the CTRL+V shortcut? Like if these keys were pressed and selected object is an image, then format it? I tried to add a Workbook_Change event to the PERSONAL.XLSB, but it seems it doesn't affect other open workbooks.
Sub FormatScreenshot()

Dim r As Object

Set r = Selection

r.ShapeRange.Line.Visible = msoTrue
r.ShapeRange.Line.Weight = 2

End Sub


text:
Q: Why is the light reflected at the same angle from mirror? From the school physics I know that the material objects bounce from the plane surface at the same angle, losing some kinetic energy. In the same school I was taught that the light (and waves in general) obeys this principle too.
Obviously, in the case of light the plane surface should be a perfect mirror. But I can't understand how should this work from the quantum point of view. Let's assume that our mirror consists of a single silver atom.
Why should the electrons of this atom re-emit consumed photons at some specific angle?

A: The alternative "textbook" electromagnetism answer is to use the boundary condition for the electric field either side of an interface - this is that the component of electric field parallel to the interface (i.e. perpendicular to the normal to the surface) must be the same immediately either side of the interface.
If we have an incoming wave travelling in the $xy$ plane, incident upon an interface plane defined by $y=0$, with amplitude $E_i$ at incidence angle $\theta_i$ that produces a reflected wave at angle $\theta_r$ and a transmitted wave at $\theta_t$ to the normal, then you can write down the following equation (where I assume the electric field is $z$-polarised with its direction also parallel to the interface plane).
$$E_i \exp(i(k_ix\sin\theta_i - \omega_i t )) + E_r \exp(i(k_r x\sin\theta_r - \omega_r t)) = E_t \exp(i(k_t x\sin\theta_t - \omega_t t)),$$
where this must be true for all values of $x$ and $t$.
The only way this can happen is if the arguments of the exponentials are all equal to each other for all values of $x$ and $t$ and this yields $\omega_i=\omega_r=\omega_t$ (frequency unchanged for the reflected and transmitted components) and $k_i \sin\theta_i = k_t\sin \theta_t$ (Snell's law); and finally that $k_i \sin\theta_i = k_r \sin\theta_r$ and since they travel in the same medium with the same frequency, speed and wavelength, then $k_i = k_r$ and hence the desired result $\theta_i = \theta_r$.
This explains nothing from the atomic/quantum point of view, but as explained in one of the comments, it is only when you have vast numbers of atoms that this classical behaviour emerges at all.

A: That's a good question. Without realising it you have stumbled across the Huygens-Fresnel principle.
The starting point it that a single silver atom is far smaller than the wavelength of light, so any scattering from it will be isotropic i.e. it will scatter the light equally in all directions.
But suppose we have two silver atoms side by side. Each atom will scatter isotropically, so in effect we have two closely spaced emitters of light and the system behaves like a Young's slits setup. Now the light isn't simply isotropically scattered, but instead it's scattered into preferred directions. (I'm oversimplifying because two atoms would be too closely spaced to act as Young's slits, but bear with me.)
Now add lots of atoms in a row, and you get something like a diffraction grating. Add lots more to make a 2D surface, then add more layers of silver atoms below, and you're building up a system where the overall light scattering is the sum of individual scattering from huge numbers of individual silver atoms. This is basically the Huygen's construction, and if you do the sums for a surface you can show that the overall scattering is only non-zero when the angle of reflection is equal to the angle of incidence. Any optics textbook should have the calculation, or a quick Google found an example here.

A: In many materials, the outer electrons are not confined to an orbital around a single atom. The orbitals spread out, extending across many atoms. Many electrons overlap. The Pauli exclusion principal says overlapping electrons cannot all have the same state. The orbitals have a range of slightly different energies and momenta. This forms a band.
Sometimes the electrons fill all available states in the band. These materials are insulators. For every electron with a momentum to the right, there is another to the left. There is no net transport of charge.
Sometimes the band is half full. This is a a conduction band. There are empty states at energies just above the most energetic electron. This material is a metal. Metals are good conductors because an electric field can easily excite an electron to a state with a momentum in the direction of the field.
To make a mirror, metal is polished to a smooth surface. Usually the surface is a plane. This defines the boundary condition for the electrons.

Typically a mirror is used at a distance from the light source. The light can be reasonably approximated by a plane wave. The approximation is not perfect, and the light is often not monochromatic.
Light is comprised of photons. If light is a monochromatic plane wave, the wave function of each photon is a plane wave. If not, the wave function is a superposition of monochromatic plane waves with various directions and frequencies. We can understand what happens by considering a monochromatic plane wave photon.
When a photon strikes a mirror, it will be absorbed by one electron. That electron will be excited, gaining energy and momentum. Later, it will drop back to the previous state, emitting a photon.

Neither the photon nor the electron have a well defined position. Both can be decomposed into states with well defined energies and momenta. The momentum of the photon can be resolved into components parallel and perpendicular to the plane of the mirror.
The momentum of the emitted photon will have the same parallel component, but a perpendicular component in the opposite direction. I can't give you a quantum mechanical reason for that. As one of the comments indicated, the theory of how light and electrons interact is quantum chromodynamics. Perhaps someone familiar with it can add to this?


text:
Q: How deal with flatten operator when we use conditional I want to use flatten operation in conditional operation :
((FLATTEN(LIMIT_CEP.CD_AXE_MCH) == 'PME') ? 'E':'F')        AS CD_AXE_MCH_GCP,

Because LIMIT_CEP.CD_AXE_MCH is given like :
 {(COMM)}
 {(ARTI)}

But the problem here that the program return this error message

Syntax error, unexpected symbol at or near 'FLATTEN'

EDIT :
I tried also something like :
FLATTEN((LIMIT_CEP.CD_AXE_MCH=='PME') ? ('E') : ('P'))   AS CD_AXE_MCH_GCP,

But I got this error :

mismatched input '?' expecting RIGHT_PAREN

How can I resolve it please ?

A: The idea is to do flatten without including conditional in first time :
EPSE_ENR_GCP = FOREACH (GROUP EPSE_ENR BY IDT_GCP) {

   ORDER_GROUP = ORDER EPSE_ENR BY IDC_PSE_PCL DESC, DA_PRM_CTR_ORDER DESC, IDT_ETT_PSE DESC;
   LIMIT_CEP = LIMIT ORDER_GROUP 1;

   GENERATE

    group                                          AS IDT_GCP,
    FLATTEN(LIMIT_CEP.CD_FRM_JUR)                  AS CD_FRM_JUR,
    FLATTEN(LIMIT_CEP.DA_CRE_EPS)                  AS DA_CRE_EPS,
    FLATTEN(LIMIT_CEP.NO_SIREN)                    AS NO_SIREN,
    FLATTEN(LIMIT_CEP.CD_POST)                     AS CD_POST,
    FLATTEN(LIMIT_CEP.CD_OSCE_PAYS_FIS)            AS CD_OSCE_PAYS_FIS,
    FLATTEN(LIMIT_CEP.CD_NAF)                      AS CD_NAF,
    FLATTEN(LIMIT_CEP.CD_NACE)                     AS CD_NACE,
    FLATTEN(LIMIT_CEP.CD_AXE_MCH)                  AS CD_AXE_MCH,
    FLATTEN(LIMIT_CEP.CD_AXE_SNIV_MCH)             AS CD_AXE_SNIV_MCH;

};

Then, in second time do conditional without any problem :
EPSE_ENR_GCP1 = FOREACH EPSE_ENR_GCP GENERATE

IDT_GCP AS IDT_GCP,
CD_FRM_JUR AS CD_FRM_JUR,
DA_CRE_EPS AS DA_CRE_EPS,
NO_SIREN AS NO_SIREN,
CD_POST AS CD_POST,
CD_OSCE_PAYS_FIS AS CD_OSCE_PAYS_FIS,
CD_NAF AS CD_NAF,
CD_NACE AS CD_NACE,
(CD_AXE_MCH IN ('PLIB','ATPE','COMM') ? 'P':
   (CD_AXE_MCH == 'PME'  ? 'E':
   (CD_AXE_MCH == 'AGRI' ? 'A':
   (CD_AXE_MCH == 'OBNL' ? 'O':
   (CD_AXE_MCH == 'COLL' ? 'C':
   (CD_AXE_MCH == 'EFIN' ? 'B':'X'))))))         AS CD_AXE_MCH_GCP,
CD_AXE_SNIV_MCH AS CD_AXE_SNIV_MCH;


text:
Q: When is "value !== value" ever true? I'm researching object equality test functions and ran across this code in Lodash's "isEqual" function:
https://bit.dev/lodash/lodash/internal/_base-is-equal/~code
function baseIsEqual(value, other, bitmask, customizer, stack) {
  if (value === other) {
    return true;
  }
  if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) {
    return value !== value && other !== other;
  }
  return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
}

TLDR: When would return value !== value && other !== other; ever return true?
The part that stumps me is the 2nd conditional and its return. Clearly the 1st condition catches simple strict equality cases. But, looking at the next test, I make the following observations (assumptions?):

*

*value == null is true only for 'null' and 'undefined'

*the "isObjectLike" clause eliminates anything not a primitive or a function

So, if the only values for value and other are primitives, undefined, null or functions, what values could satisfy the condition for a true return? Seeing this code in Lodash lends it credibility, so I'm also "assuming" it is legit ("assumptions"! ... yes, I know ... ).


text:
Q: Copy elision with tuples I always had the wrong impression that if I create temporaries in a function that returns a tuple, and use std::forward_as_tuple in the return statement, then there is no copy, just like automatic copy elision for non-tuple return types.
How then can we avoid a copy? For example, in the following code, func1 "copies" the values 1 and 2 into temp as it is being constructed, and there is no additional copy upon returning. func2 on the other hand does the same construction, but additionally copies when a tuple is created in the return statement.
I tried to be witty about it, and declare the temporary to be returned a tuple and construct a My_struct in place, like this: std::tuple<My_struct> temp {{1,2}}. But the copy constructor is still called. Adding a move constructor won't help as far as I can see since the data members are simple types.
#include <iostream>
#include <tuple>

struct My_struct {
    int x, y;
    My_struct(int x, int y) :
      x(x), y(y)
    {
        std::cout << "Constructor called\n";
    }
    My_struct(const My_struct &a) :
      x(a.x), y(a.y)
    {
        std::cout << "Copy constructor called!\n";
    }
};

My_struct func1()
{
    My_struct temp {1,2};
    return temp;
}

std::tuple<My_struct> func2()
{
    My_struct temp {1,2};
    return std::forward_as_tuple(temp);
}

int main()
{
    std::cout << "# Calling func1\n";
    auto result1 = func1();

    std::cout << "# Calling func2\n";
    auto result2 = func2();
}

result:
# Calling func1
Constructor called
# Calling func2
Constructor called
Copy constructor called!


text:
Q: Check transparency in .png image using jquery but without using canvas I am working on an application in which I have placed the div background and I'm masking it with a .PNG image. In that .PNG image there is a transparent area from which user can see the background image of the div. I want to know if the user clicks on the transparent area or the white area of the .PNG image.
I have found this example:
fiddle example using canvas
But I want to do this without using canvas. Is it possible?
I'm simply appending the png image on my div called drop.
var url = "url(./img/imagesapp/background.jpg?"+Math.random()+")";
$('.drop').css('background-image', url)
var id=triangle;
var test="<img id='img"+id+"' class='shapeOfAC' src='./img/shapes/"+id+".png'/>";
$(".drop").append(test);

Thanks in advance :)

A: The only real alternative I can think of (without serverside assistance) is to write some code that examines the PNG image to make a map of its transparency for each pixel and turn that into a long string containing just the alpha channel which you could read via javascript.
Problem with this though is that it'd be a lot of data. If you stored it just a lump of HEX it'd be 2xHxW bytes in length. Although you could improve this by gzipping the data and decompressing it in javascript.


text:
Q: Hide and show a directive based on a button click in Angular I am new to AngularJS. So,please apologies for such a stupid question.
I want to hide/show a directive based on a button click .

                Welcome to the world of directives!

                    {{fruit.label}}
                    <my-div></my-div>

Whenever a link in clicked , I want to show the alert with the respective fruit name which comes from the directive function.
But no errors are as such in console.
What am I missing ?
Please give an explanation .

A: Instead of define the function in directive define it in controller as below
app.controller('appCtrl',function($scope){
     // Fruits
    $scope.fruits = [{
            label:"Apple"
        },{
            label:"Orange",
        },{
            label:"Grapes"
        }];

    $scope.itemClicked = function(value){
        alert('myDiv clicked : ' + value);
    }
});

And also change ng-click="itemClicked(fruit.label)" in your html as well.


text:
Q: How to make nginx redirect to a different port I have the following location block in the nginx.conf file.
Location /e-ui/ {
    proxy_pass https://hostname:9000
}

I need to know how I can redirect sites in the following manner:
https://abc/e-ui/ should be redirected to https://abc:9000
OR
https://xyz/e-ui/ should be redirected to https://xyz:9000
The server name is changing ( as the code is deployed on many servers ). Is there anyway I can get the server name from the /etc/hosts file if it is already defined there and use it somehow to redirect the sites as mentioned above ?
Thank you.


text:
Q: Nodejs and Node show two different versions. How can this be? I've been all over looking for a solution. I've read that I should purge both node and nodejs, do a fresh installation then link the two together. This did not work. I was told to try nodejs legacy. This did not work.
I am trying to install something that requires a newer version of node. My nodejs has upgraded just fine, but node, unfortunately, has not.
node -v
v5.4.1

nodejs -v
v8.**** (latest)

I can't be the only person who is experiencing this. Does anyone have a fix? Running Ubuntu 16.04
fappycow@fappycow-desktop:~$ type -a node nodejs
node is /home/fappycow/.nvm/versions/node/v5.4.1/bin/node
node is /usr/local/bin/node
node is /usr/bin/node
nodejs is /usr/bin/nodejs

A: The problem here is that node has been installed with nvm. Whenever you want to upgrade to the latest version of node, just run nvm install node.
I would also uninstall nodejs: sudo apt purge nodejs
Using nvm is much better than the nodejs binary.